示例#1
0
 def getSessionCipher(self, recipientId):
     if recipientId in self.sessionCiphers:
         return self.sessionCiphers[recipientId]
     else:
         self.sessionCiphers[recipientId] = SessionCipher(
             self.store, self.store, self.store, self.store, recipientId, 1)
         return self.sessionCiphers[recipientId]
示例#2
0
 def _get_session_cipher(self, recipientid):
     logger.debug("get_session_cipher(recipientid=%s)" % recipientid)
     if recipientid in self._session_ciphers:
         session_cipher = self._session_ciphers[recipientid]
     else:
         session_cipher= SessionCipher(self._store, self._store, self._store, self._store, recipientid, 1)
         self._session_ciphers[recipientid] = session_cipher
     return session_cipher
示例#3
0
 def _get_session_cipher(self, jid, device_id):
     try:
         return self._session_ciphers[jid][device_id]
     except KeyError:
         cipher = SessionCipher(self._storage, self._storage, self._storage,
                                self._storage, jid, device_id)
         self._session_ciphers[jid][device_id] = cipher
         return cipher
示例#4
0
    def get_session_cipher(self, jid, device_id):
        if jid not in self.session_ciphers:
            self.session_ciphers[jid] = {}

        if device_id not in self.session_ciphers[jid]:
            cipher = SessionCipher(self.store, self.store, self.store,
                                   self.store, jid, device_id)
            self.session_ciphers[jid][device_id] = cipher

        return self.session_ciphers[jid][device_id]
示例#5
0
def handle_data_msg(store, who, body):
    messageBytes = binascii.unhexlify(body)
    print("UNWRAPPED >>> [%r]" % binascii.hexlify(messageBytes))

    try:
        sc = SessionCipher(store, store, store, store, who, 1)
        print("SessionCipher >>>", sc)

        wm = WhisperMessage(serialized=messageBytes)
        print("WhisperMessage >>>", wm)

        data = sc.decryptMsg(wm)
        print("DECRYPTED >>> ", data)

    except Exception as e:
        print("EXCEPTION >>>", e)

        exc_type, exc_value, exc_traceback = sys.exc_info()
        print("*** print_tb:")
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
示例#6
0
def handle_data_msg(store, who, body):
    messageBytes = binascii.unhexlify(body)
    print("UNWRAPPED >>> [%r]" % binascii.hexlify(messageBytes))

    try:
        sc = SessionCipher(store, store, store, store, who, 1)
        print("SessionCipher >>>", sc)

        wm = WhisperMessage(serialized=messageBytes)
        print("WhisperMessage >>>", wm)

        data = sc.decryptMsg(wm)
        print("DECRYPTED >>> ", data)

    except Exception as e:
        print("EXCEPTION >>>", e)

        exc_type, exc_value, exc_traceback = sys.exc_info()
        print("*** print_tb:")
        traceback.print_tb(exc_traceback, limit=1, file=sys.stdout)
    def runInteraction(self, aliceSessionRecord, bobSessionRecord):
        aliceStore = InMemoryAxolotlStore()
        bobStore   = InMemoryAxolotlStore()

        aliceStore.storeSession(2, 1, aliceSessionRecord)
        bobStore.storeSession(3, 1, bobSessionRecord)

        aliceCipher    = SessionCipher(aliceStore, aliceStore, aliceStore, aliceStore, 2, 1)
        bobCipher      = SessionCipher(bobStore, bobStore, bobStore, bobStore, 3, 1)

        alicePlaintext = "This is a plaintext message."
        message        = aliceCipher.encrypt(alicePlaintext)
        bobPlaintext   = bobCipher.decryptMsg(WhisperMessage(serialized=message.serialize()))

        self.assertEqual(alicePlaintext, bobPlaintext)

        bobReply      = "This is a message from Bob."
        reply         = bobCipher.encrypt(bobReply)
        receivedReply = aliceCipher.decryptMsg(WhisperMessage( serialized=reply.serialize()))

        self.assertEqual(bobReply, receivedReply)

        aliceCiphertextMessages = []
        alicePlaintextMessages = []

        for i in range(0, 50):
            alicePlaintextMessages.append("смерть за смерть %s" % i)
            aliceCiphertextMessages.append(aliceCipher.encrypt("смерть за смерть %s" % i))

        #shuffle(aliceCiphertextMessages)
        #shuffle(alicePlaintextMessages)


        for i in range(0, int(len(aliceCiphertextMessages)/2)):
            receivedPlaintext = bobCipher.decryptMsg(WhisperMessage(serialized=aliceCiphertextMessages[i].serialize()))
            self.assertEqual(receivedPlaintext, alicePlaintextMessages[i])


        """
示例#8
0
文件: core.py 项目: xmikos/pyxolotl
 def getSessionCipher(self, identity):
     """Construct SessionCipher for given identity"""
     return SessionCipher(self.store, self.store, self.store, self.store,
                          identity, self.DEFAULT_DEVICE_ID)
    def test_basicPreKeyV3(self):
        aliceStore = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore, aliceStore, aliceStore, aliceStore, self.__class__.BOB_RECIPIENT_ID, 1)

        bobStore =   InMemoryAxolotlStore()
        bobPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeyPair = Curve.generateKeyPair()
        bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(),
                                                                           bobSignedPreKeyPair.getPublicKey().serialize())

        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                              31337, bobPreKeyPair.getPublicKey(),
                                              22, bobSignedPreKeyPair.getPublicKey(),
                                              bobSignedPreKeySignature,
                                              bobStore.getIdentityKeyPair().getPublicKey())

        aliceSessionBuilder.processPreKeyBundle(bobPreKey)
        self.assertTrue(aliceStore.containsSession(self.__class__.BOB_RECIPIENT_ID, 1))
        self.assertTrue(aliceStore.loadSession(self.__class__.BOB_RECIPIENT_ID, 1).getSessionState().getSessionVersion() == 3)

        originalMessage    = "L'homme est condamné à être libre"
        aliceSessionCipher = SessionCipher(aliceStore, aliceStore, aliceStore, aliceStore, self.__class__.BOB_RECIPIENT_ID, 1)
        outgoingMessage    = aliceSessionCipher.encrypt(originalMessage)

        self.assertTrue(outgoingMessage.getType() == CiphertextMessage.PREKEY_TYPE)

        incomingMessage = PreKeyWhisperMessage(serialized=outgoingMessage.serialize())
        bobStore.storePreKey(31337, PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair))
        bobStore.storeSignedPreKey(22, SignedPreKeyRecord(22, int(time.time() * 1000), bobSignedPreKeyPair, bobSignedPreKeySignature))

        bobSessionCipher = SessionCipher(bobStore, bobStore, bobStore, bobStore, self.__class__.ALICE_RECIPIENT_ID, 1)

        plaintext = bobSessionCipher.decryptPkmsg(incomingMessage)
        self.assertEqual(originalMessage, plaintext)
        # @@TODO: in callback assertion
        # self.assertFalse(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))

        self.assertTrue(bobStore.containsSession(self.__class__.ALICE_RECIPIENT_ID, 1))

        self.assertTrue(bobStore.loadSession(self.__class__.ALICE_RECIPIENT_ID, 1).getSessionState().getSessionVersion() == 3)
        self.assertTrue(bobStore.loadSession(self.__class__.ALICE_RECIPIENT_ID, 1).getSessionState().getAliceBaseKey() != None)
        self.assertEqual(originalMessage, plaintext)

        bobOutgoingMessage = bobSessionCipher.encrypt(originalMessage)
        self.assertTrue(bobOutgoingMessage.getType() == CiphertextMessage.WHISPER_TYPE)

        alicePlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobOutgoingMessage.serialize()))
        self.assertEqual(alicePlaintext, originalMessage)

        self.runInteraction(aliceStore, bobStore)

        aliceStore          = InMemoryAxolotlStore()
        aliceSessionBuilder = SessionBuilder(aliceStore, aliceStore, aliceStore, aliceStore, self.__class__.BOB_RECIPIENT_ID, 1)
        aliceSessionCipher  = SessionCipher(aliceStore, aliceStore, aliceStore, aliceStore, self.__class__.BOB_RECIPIENT_ID, 1)

        bobPreKeyPair            = Curve.generateKeyPair()
        bobSignedPreKeyPair      = Curve.generateKeyPair()
        bobSignedPreKeySignature = Curve.calculateSignature(bobStore.getIdentityKeyPair().getPrivateKey(), bobSignedPreKeyPair.getPublicKey().serialize())
        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(),
                                 1, 31338, bobPreKeyPair.getPublicKey(),
                                 23, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                 bobStore.getIdentityKeyPair().getPublicKey())

        bobStore.storePreKey(31338, PreKeyRecord(bobPreKey.getPreKeyId(), bobPreKeyPair))
        bobStore.storeSignedPreKey(23, SignedPreKeyRecord(23, int(time.time() * 1000), bobSignedPreKeyPair, bobSignedPreKeySignature))
        aliceSessionBuilder.processPreKeyBundle(bobPreKey)

        outgoingMessage = aliceSessionCipher.encrypt(originalMessage)

        try:
            plaintext = bobSessionCipher.decryptPkmsg(PreKeyWhisperMessage(serialized=outgoingMessage))
            raise AssertionError("shouldn't be trusted!")
        except Exception:
            bobStore.saveIdentity(self.__class__.ALICE_RECIPIENT_ID, PreKeyWhisperMessage(serialized=outgoingMessage.serialize()).getIdentityKey())

        plaintext = bobSessionCipher.decryptPkmsg(PreKeyWhisperMessage(serialized=outgoingMessage.serialize()))
        self.assertEqual(plaintext, originalMessage)


        bobPreKey = PreKeyBundle(bobStore.getLocalRegistrationId(), 1,
                                 31337, Curve.generateKeyPair().getPublicKey(),
                                 23, bobSignedPreKeyPair.getPublicKey(), bobSignedPreKeySignature,
                                 aliceStore.getIdentityKeyPair().getPublicKey())
        try:
            aliceSessionBuilder.process(bobPreKey)
            raise AssertionError("shouldn't be trusted!")
        except Exception:
            #good
            pass
    def runInteraction(self, aliceStore, bobStore):
        """
        :type aliceStore: AxolotlStore
        :type  bobStore: AxolotlStore
        """

        aliceSessionCipher = SessionCipher(aliceStore, aliceStore, aliceStore, aliceStore, self.__class__.BOB_RECIPIENT_ID, 1)
        bobSessionCipher   = SessionCipher(bobStore, bobStore, bobStore, bobStore, self.__class__.ALICE_RECIPIENT_ID, 1)

        originalMessage = "smert ze smert"
        aliceMessage = aliceSessionCipher.encrypt(originalMessage)

        self.assertTrue(aliceMessage.getType() == CiphertextMessage.WHISPER_TYPE)

        plaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceMessage.serialize()))
        self.assertEqual(plaintext, originalMessage)

        bobMessage = bobSessionCipher.encrypt(originalMessage)

        self.assertTrue(bobMessage.getType() == CiphertextMessage.WHISPER_TYPE)

        plaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobMessage.serialize()))
        self.assertEqual(plaintext, originalMessage)

        for i in range(0, 10):
            loopingMessage = "What do we mean by saying that existence precedes essence? " \
                             "We mean that man first of all exists, encounters himself, " \
                             "surges up in the world--and defines himself aftward. %s" % i
            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)
            loopingPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceLoopingMessage.serialize()))
            self.assertEqual(loopingPlaintext, loopingMessage)


        for i in range(0, 10):
            loopingMessage = "What do we mean by saying that existence precedes essence? " \
                 "We mean that man first of all exists, encounters himself, " \
                 "surges up in the world--and defines himself aftward. %s" % i
            bobLoopingMessage = bobSessionCipher.encrypt(loopingMessage)

            loopingPlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobLoopingMessage.serialize()))
            self.assertEqual(loopingPlaintext, loopingMessage)

        aliceOutOfOrderMessages = []

        for i in range(0, 10):
            loopingMessage = "What do we mean by saying that existence precedes essence? " \
                 "We mean that man first of all exists, encounters himself, " \
                 "surges up in the world--and defines himself aftward. %s" % i
            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)
            aliceOutOfOrderMessages.append((loopingMessage, aliceLoopingMessage))

        for i in range(0, 10):
            loopingMessage = "What do we mean by saying that existence precedes essence? " \
                 "We mean that man first of all exists, encounters himself, " \
                 "surges up in the world--and defines himself aftward. %s" % i
            aliceLoopingMessage = aliceSessionCipher.encrypt(loopingMessage)
            loopingPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceLoopingMessage.serialize()))
            self.assertEqual(loopingPlaintext, loopingMessage)

        for i in range(0, 10):
            loopingMessage = "You can only desire based on what you know: %s" % i
            bobLoopingMessage = bobSessionCipher.encrypt(loopingMessage)

            loopingPlaintext = aliceSessionCipher.decryptMsg(WhisperMessage(serialized=bobLoopingMessage.serialize()))
            self.assertEqual(loopingPlaintext, loopingMessage)

        for aliceOutOfOrderMessage in aliceOutOfOrderMessages:
            outOfOrderPlaintext = bobSessionCipher.decryptMsg(WhisperMessage(serialized=aliceOutOfOrderMessage[1].serialize()))
            self.assertEqual(outOfOrderPlaintext, aliceOutOfOrderMessage[0])