コード例 #1
0
ファイル: test_consumer_db.py プロジェクト: skoulouzis/PyNDN2
def generateRsaKeys():
    params = RsaKeyParams()
    decryptKey = RsaAlgorithm.generateKey(params)
    decryptionKeyBlob = decryptKey.getKeyBits()
    encryptKey = RsaAlgorithm.deriveEncryptKey(decryptionKeyBlob)
    encryptionKeyBlob = encryptKey.getKeyBits()

    return (encryptionKeyBlob, decryptionKeyBlob)
コード例 #2
0
ファイル: test_consumer_db.py プロジェクト: MAHIS/PyNDN2
def generateRsaKeys():
    params = RsaKeyParams()
    decryptKey = RsaAlgorithm.generateKey(params)
    decryptionKeyBlob = decryptKey.getKeyBits()
    encryptKey = RsaAlgorithm.deriveEncryptKey(decryptionKeyBlob)
    encryptionKeyBlob = encryptKey.getKeyBits()

    return (encryptionKeyBlob, decryptionKeyBlob)
コード例 #3
0
ファイル: test_nac_producer.py プロジェクト: named-data/PyCNL
    def __init__(self, contentPrefix, userKeyName, keyChain, certificateName):
        self._enabled = True
        self._responseCount = 0

        # Imitate test_consumer from the PyNDN integration tests.
        contentName0 = Name(contentPrefix).append("Content").appendSegment(0)
        contentName1 = Name(contentPrefix).append("Content").appendSegment(1)
        cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        dKeyName = Name("/Prefix/READ/D-KEY/1/2")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
          fixtureDKeyBlob).getKeyBits()

        # The user key.
        fixtureUserEKeyBlob = Blob(FIXTURE_USER_E_KEY)

        # Load the C-KEY.
        fixtureCKeyBlob = Blob(AES_KEY, False)

        # Imitate createEncryptedContent. Make two segments.
        encryptParams = EncryptParams(EncryptAlgorithmType.AesCbc)
        encryptParams.setInitialVector(Blob(INITIAL_VECTOR, False))
        self._contentData0 = Data(contentName0)
        Encryptor.encryptData(
          self._contentData0, Blob(DATA0_CONTENT, False), cKeyName,
          fixtureCKeyBlob,  encryptParams)
        self._contentData0.getMetaInfo().setFinalBlockId(
          Name().appendSegment(1)[0])
        keyChain.sign(self._contentData0, certificateName)

        self._contentData1 = Data(contentName1)
        Encryptor.encryptData(
          self._contentData1, Blob(DATA1_CONTENT, False), cKeyName,
          fixtureCKeyBlob,  encryptParams)
        self._contentData1.getMetaInfo().setFinalBlockId(
          Name().appendSegment(1)[0])
        keyChain.sign(self._contentData1, certificateName)

        # Imitate createEncryptedCKey.
        self._cKeyData = Data(cKeyName)
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        Encryptor.encryptData(
          self._cKeyData, fixtureCKeyBlob, dKeyName, fixtureEKeyBlob,
          encryptParams)
        keyChain.sign(self._cKeyData, certificateName)

        # Imitate createEncryptedDKey.
        self._dKeyData = Data(dKeyName)
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        Encryptor.encryptData(
          self._dKeyData, fixtureDKeyBlob, userKeyName, fixtureUserEKeyBlob,
          encryptParams)
        keyChain.sign(self._dKeyData, certificateName)
コード例 #4
0
    def __init__(self, contentPrefix, userKeyName, keyChain, certificateName):
        self._enabled = True
        self._responseCount = 0

        # Imitate test_consumer from the PyNDN integration tests.
        contentName0 = Name(contentPrefix).append("Content").appendSegment(0)
        contentName1 = Name(contentPrefix).append("Content").appendSegment(1)
        cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        dKeyName = Name("/Prefix/READ/D-KEY/1/2")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            fixtureDKeyBlob).getKeyBits()

        # The user key.
        fixtureUserEKeyBlob = Blob(FIXTURE_USER_E_KEY)

        # Load the C-KEY.
        fixtureCKeyBlob = Blob(AES_KEY, False)

        # Imitate createEncryptedContent. Make two segments.
        encryptParams = EncryptParams(EncryptAlgorithmType.AesCbc)
        encryptParams.setInitialVector(Blob(INITIAL_VECTOR, False))
        self._contentData0 = Data(contentName0)
        Encryptor.encryptData(self._contentData0, Blob(DATA0_CONTENT, False),
                              cKeyName, fixtureCKeyBlob, encryptParams)
        self._contentData0.getMetaInfo().setFinalBlockId(
            Name().appendSegment(1)[0])
        keyChain.sign(self._contentData0, certificateName)

        self._contentData1 = Data(contentName1)
        Encryptor.encryptData(self._contentData1, Blob(DATA1_CONTENT, False),
                              cKeyName, fixtureCKeyBlob, encryptParams)
        self._contentData1.getMetaInfo().setFinalBlockId(
            Name().appendSegment(1)[0])
        keyChain.sign(self._contentData1, certificateName)

        # Imitate createEncryptedCKey.
        self._cKeyData = Data(cKeyName)
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        Encryptor.encryptData(self._cKeyData, fixtureCKeyBlob, dKeyName,
                              fixtureEKeyBlob, encryptParams)
        keyChain.sign(self._cKeyData, certificateName)

        # Imitate createEncryptedDKey.
        self._dKeyData = Data(dKeyName)
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        Encryptor.encryptData(self._dKeyData, fixtureDKeyBlob, userKeyName,
                              fixtureUserEKeyBlob, encryptParams)
        keyChain.sign(self._dKeyData, certificateName)
コード例 #5
0
    def setUp(self):
        self.decryptionKeys = {}  # key: Name, value: Blob
        self.encryptionKeys = {}  # key: Name, value: Data

        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.databaseFilePath = "policy_config/test.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupName = Name("/Prefix/READ")
        self.contentName = Name("/Prefix/SAMPLE/Content")
        self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        self.eKeyName = Name("/Prefix/READ/E-KEY/1/2")
        self.dKeyName = Name("/Prefix/READ/D-KEY/1/2")
        self.uKeyName = Name("/U/Key")
        self.uName = Name("/U")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            self.fixtureDKeyBlob).getKeyBits()

        # Generate the user key.
        self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            self.fixtureUDKeyBlob).getKeyBits()

        # Load the C-KEY.
        self.fixtureCKeyBlob = Blob(AES_KEY, False)

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())

        # Initialize the storage.
        keyName = Name("/testname/DSK-123")
        self.certificateName = keyName.getSubName(
            0,
            keyName.size() - 1).append("KEY").append(
                keyName.get(-1)).append("ID-CERT").append("0")
        identityStorage.addKey(keyName, KeyType.RSA,
                               Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
        privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                               DEFAULT_RSA_PUBLIC_KEY_DER,
                                               DEFAULT_RSA_PRIVATE_KEY_DER)
コード例 #6
0
ファイル: test_producer.py プロジェクト: pedosb/PyNDN2
    def createEncryptionKey(self, eKeyName, timeMarker):
        params = RsaKeyParams()
        eKeyName = Name(eKeyName)
        eKeyName.append(timeMarker)

        dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits()
        self.decryptionKeys[eKeyName] = dKeyBlob

        keyData = Data(eKeyName)
        keyData.setContent(eKeyBlob)
        self.keyChain.sign(keyData, self.certificateName)
        self.encryptionKeys[eKeyName] = keyData
コード例 #7
0
ファイル: test_producer.py プロジェクト: MAHIS/PyNDN2
    def createEncryptionKey(self, eKeyName, timeMarker):
        params = RsaKeyParams()
        eKeyName = Name(eKeyName)
        eKeyName.append(timeMarker)

        dKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        eKeyBlob = RsaAlgorithm.deriveEncryptKey(dKeyBlob).getKeyBits()
        self.decryptionKeys[eKeyName] = dKeyBlob

        keyData = Data(eKeyName)
        keyData.setContent(eKeyBlob)
        self.keyChain.sign(keyData, self.certificateName)
        self.encryptionKeys[eKeyName] = keyData
コード例 #8
0
    def setUp(self):
        self.decryptionKeys = {} # key: Name, value: Blob
        self.encryptionKeys = {} # key: Name, value: Data

        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.databaseFilePath = "policy_config/test.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupName = Name("/Prefix/READ")
        self.contentName = Name("/Prefix/SAMPLE/Content")
        self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        self.eKeyName = Name("/Prefix/READ/E-KEY/1/2")
        self.dKeyName = Name("/Prefix/READ/D-KEY/1/2")
        self.uKeyName = Name("/U/Key")
        self.uName = Name("/U")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
          self.fixtureDKeyBlob).getKeyBits()

        # Generate the user key.
        self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey(
          self.fixtureUDKeyBlob).getKeyBits()

        # Load the C-KEY.
        self.fixtureCKeyBlob = Blob(AES_KEY, False)

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())

        # Initialize the storage.
        keyName = Name("/testname/DSK-123")
        self.certificateName = keyName.getSubName(0, keyName.size() - 1).append(
          "KEY").append(keyName.get(-1)).append("ID-CERT").append("0")
        identityStorage.addKey(
          keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
        privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
          DEFAULT_RSA_PRIVATE_KEY_DER)
コード例 #9
0
ファイル: test_producer.py プロジェクト: pedosb/PyNDN2
        def checkEncryptionKeys(result, testTime, roundedTime,
                                expectedExpressInterestCallCount):
            self.assertEqual(expectedExpressInterestCallCount,
                             expressInterestCallCount[0])

            self.assertEqual(True, testDb.hasContentKey(testTime))
            contentKey[0] = testDb.getContentKey(testTime)

            params = EncryptParams(EncryptAlgorithmType.RsaOaep)
            for i in range(len(result)):
                key = result[i]
                keyName = key.getName()
                self.assertEqual(cKeyName, keyName.getSubName(0, 6))
                self.assertEqual(keyName.get(6), roundedTime)
                self.assertEqual(keyName.get(7), Encryptor.NAME_COMPONENT_FOR)
                self.assertEqual(True,
                                 keyName.getSubName(8) in self.decryptionKeys)

                decryptionKey = self.decryptionKeys[keyName.getSubName(8)]
                self.assertEqual(True, decryptionKey.size() != 0)
                encryptedKeyEncoding = key.getContent()

                content = EncryptedContent()
                content.wireDecode(encryptedKeyEncoding)
                encryptedKey = content.getPayload()
                retrievedKey = RsaAlgorithm.decrypt(decryptionKey,
                                                    encryptedKey, params)

                self.assertTrue(contentKey[0].equals(retrievedKey))

            self.assertEqual(3, len(result))
コード例 #10
0
ファイル: test_producer.py プロジェクト: MAHIS/PyNDN2
        def checkEncryptionKeys(
          result, testTime, roundedTime, expectedExpressInterestCallCount):
            self.assertEqual(expectedExpressInterestCallCount,
                             expressInterestCallCount[0])

            self.assertEqual(True, testDb.hasContentKey(testTime))
            contentKey[0] = testDb.getContentKey(testTime)

            params = EncryptParams(EncryptAlgorithmType.RsaOaep)
            for i in range(len(result)):
                key = result[i]
                keyName = key.getName()
                self.assertEqual(cKeyName, keyName.getSubName(0, 6))
                self.assertEqual(keyName.get(6), roundedTime)
                self.assertEqual(keyName.get(7), Encryptor.NAME_COMPONENT_FOR)
                self.assertEqual(
                  True, keyName.getSubName(8) in self.decryptionKeys)

                decryptionKey = self.decryptionKeys[keyName.getSubName(8)]
                self.assertEqual(True, decryptionKey.size() != 0)
                encryptedKeyEncoding = key.getContent()

                content = EncryptedContent()
                content.wireDecode(encryptedKeyEncoding)
                encryptedKey = content.getPayload()
                retrievedKey = RsaAlgorithm.decrypt(
                  decryptionKey, encryptedKey, params)

                self.assertTrue(contentKey[0].equals(retrievedKey))

            self.assertEqual(3, len(result))
コード例 #11
0
ファイル: test_encryptor.py プロジェクト: tuple71/PyNDN2
    def test_content_asymmetric_encrypt_small(self):
        for input in encryptorRsaTestInputs:
            rawContent = Blob(
                bytearray([
                    0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc,
                    0xba, 0x98, 0x76, 0x54, 0x32, 0x10, 0x63, 0x6f, 0x6e, 0x74,
                    0x65, 0x6e, 0x74, 0x73
                ]), False)

            data = Data()
            rsaParams = RsaKeyParams(1024)

            keyName = Name("test")

            decryptKey = RsaAlgorithm.generateKey(rsaParams)
            encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

            eKey = encryptKey.getKeyBits()
            dKey = decryptKey.getKeyBits()

            encryptParams = EncryptParams(input.type)

            Encryptor.encryptData(data, rawContent, keyName, eKey,
                                  encryptParams)

            self.assertTrue(
                data.getName().equals(Name("/FOR").append(keyName)),
                input.testName)

            extractContent = EncryptedContent()
            extractContent.wireDecode(data.getContent())
            self.assertTrue(
                keyName.equals(extractContent.getKeyLocator().getKeyName()),
                input.testName)
            self.assertEqual(extractContent.getInitialVector().size(), 0,
                             input.testName)
            self.assertEqual(extractContent.getAlgorithmType(), input.type,
                             input.testName)

            recovered = extractContent.getPayload()
            decrypted = RsaAlgorithm.decrypt(dKey, recovered, encryptParams)
            self.assertTrue(rawContent.equals(decrypted), input.testName)
コード例 #12
0
    def test_content_asymmetric_encrypt_small(self):
        for input in encryptorRsaTestInputs:
            rawContent = Blob(bytearray([
                0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef,
                0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
                0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73
              ]), False)

            data = Data()
            rsaParams = RsaKeyParams(1024)

            keyName = Name("test")

            decryptKey = RsaAlgorithm.generateKey(rsaParams)
            encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

            eKey = encryptKey.getKeyBits()
            dKey = decryptKey.getKeyBits()

            encryptParams = EncryptParams(input.type)

            Encryptor.encryptData(data, rawContent, keyName, eKey, encryptParams)

            self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)),
                            input.testName)

            extractContent = EncryptedContent()
            extractContent.wireDecode(data.getContent())
            self.assertTrue(
              keyName.equals(extractContent.getKeyLocator().getKeyName()),
              input.testName)
            self.assertEqual(
              extractContent.getInitialVector().size(), 0, input.testName)
            self.assertEqual(
              extractContent.getAlgorithmType(), input.type, input.testName)

            recovered = extractContent.getPayload()
            decrypted = RsaAlgorithm.decrypt(dKey, recovered, encryptParams)
            self.assertTrue(rawContent.equals(decrypted), input.testName)
コード例 #13
0
    def test_create_d_key_data(self):
        # Create the group manager.
        manager = GroupManager(
            Name("Alice"), Name("data_type"),
            Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1,
            self.keyChain)

        newCertificateBlob = self.certificate.wireEncode()
        newCertificate = IdentityCertificate()
        newCertificate.wireDecode(newCertificateBlob)

        # Encrypt the D-KEY.
        data = manager._createDKeyData(
            "20150825T000000", "20150827T000000", Name("/ndn/memberA/KEY"),
            self.decryptKeyBlob,
            newCertificate.getPublicKeyInfo().getKeyDer())

        # Verify the encrypted D-KEY.
        dataContent = data.getContent()

        # Get the nonce key.
        # dataContent is a sequence of the two EncryptedContent.
        encryptedNonce = EncryptedContent()
        encryptedNonce.wireDecode(dataContent)
        self.assertEqual(0, encryptedNonce.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.RsaOaep,
                         encryptedNonce.getAlgorithmType())

        blobNonce = encryptedNonce.getPayload()
        decryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        nonce = RsaAlgorithm.decrypt(self.decryptKeyBlob, blobNonce,
                                     decryptParams)

        # Get the D-KEY.
        # Use the size of encryptedNonce to find the start of encryptedPayload.
        payloadContent = dataContent.buf()[encryptedNonce.wireEncode().size():]
        encryptedPayload = EncryptedContent()
        encryptedPayload.wireDecode(payloadContent)
        self.assertEqual(16, encryptedPayload.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.AesCbc,
                         encryptedPayload.getAlgorithmType())

        decryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
        decryptParams.setInitialVector(encryptedPayload.getInitialVector())
        blobPayload = encryptedPayload.getPayload()
        largePayload = AesAlgorithm.decrypt(nonce, blobPayload, decryptParams)

        self.assertTrue(largePayload.equals(self.decryptKeyBlob))
コード例 #14
0
    def test_create_d_key_data(self):
        # Create the group manager.
        manager = GroupManager(
          Name("Alice"), Name("data_type"),
          Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1,
          self.keyChain)

        newCertificateBlob = self.certificate.wireEncode()
        newCertificate = IdentityCertificate()
        newCertificate.wireDecode(newCertificateBlob)

        # Encrypt the D-KEY.
        data = manager._createDKeyData(
          "20150825T000000", "20150827T000000", Name("/ndn/memberA/KEY"),
          self.decryptKeyBlob, newCertificate.getPublicKeyInfo().getKeyDer())

        # Verify the encrypted D-KEY.
        dataContent = data.getContent()

        # Get the nonce key.
        # dataContent is a sequence of the two EncryptedContent.
        encryptedNonce = EncryptedContent()
        encryptedNonce.wireDecode(dataContent)
        self.assertEqual(0, encryptedNonce.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.RsaOaep, encryptedNonce.getAlgorithmType())

        blobNonce = encryptedNonce.getPayload()
        decryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        nonce = RsaAlgorithm.decrypt(self.decryptKeyBlob, blobNonce, decryptParams)

        # Get the D-KEY.
        # Use the size of encryptedNonce to find the start of encryptedPayload.
        payloadContent = dataContent.buf()[encryptedNonce.wireEncode().size():]
        encryptedPayload = EncryptedContent()
        encryptedPayload.wireDecode(payloadContent)
        self.assertEqual(16, encryptedPayload.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.AesCbc, encryptedPayload.getAlgorithmType())

        decryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
        decryptParams.setInitialVector(encryptedPayload.getInitialVector())
        blobPayload = encryptedPayload.getPayload()
        largePayload = AesAlgorithm.decrypt(nonce, blobPayload, decryptParams)

        self.assertTrue(largePayload.equals(self.decryptKeyBlob))
コード例 #15
0
    def test_encryption_decryption(self):
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep, 0)

        privateKeyBlob = Blob(b64decode(PRIVATE_KEY))
        publicKeyBlob = Blob(b64decode(PUBLIC_KEY))

        decryptKey = DecryptKey(privateKeyBlob)
        encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

        encodedPublic = publicKeyBlob
        derivedPublicKey = encryptKey.getKeyBits()

        self.assertTrue(encodedPublic.equals(derivedPublicKey))

        plainBlob = Blob(PLAINTEXT, False)
        encryptBlob = RsaAlgorithm.encrypt(
          encryptKey.getKeyBits(), plainBlob, encryptParams)
        receivedBlob = RsaAlgorithm.decrypt(
          decryptKey.getKeyBits(), encryptBlob, encryptParams)

        self.assertTrue(plainBlob.equals(receivedBlob))

        cipherBlob = Blob(CIPHERTEXT_OAEP, False)
        decryptedBlob = RsaAlgorithm.decrypt(
          decryptKey.getKeyBits(), cipherBlob, encryptParams)

        self.assertTrue(plainBlob.equals(decryptedBlob))

        # Now test RsaPkcs.
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaPkcs, 0)
        encryptBlob = RsaAlgorithm.encrypt(
          encryptKey.getKeyBits(), plainBlob, encryptParams)
        receivedBlob = RsaAlgorithm.decrypt(
          decryptKey.getKeyBits(), encryptBlob, encryptParams)

        self.assertTrue(plainBlob.equals(receivedBlob))

        cipherBlob = Blob(CIPHERTEXT_PKCS, False)
        decryptedBlob = RsaAlgorithm.decrypt(
          decryptKey.getKeyBits(), cipherBlob, encryptParams)

        self.assertTrue(plainBlob.equals(decryptedBlob))
コード例 #16
0
    def test_encryption_decryption(self):
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep, 0)

        privateKeyBlob = Blob(b64decode(PRIVATE_KEY))
        publicKeyBlob = Blob(b64decode(PUBLIC_KEY))

        decryptKey = DecryptKey(privateKeyBlob)
        encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

        encodedPublic = publicKeyBlob
        derivedPublicKey = encryptKey.getKeyBits()

        self.assertTrue(encodedPublic.equals(derivedPublicKey))

        plainBlob = Blob(PLAINTEXT, False)
        encryptBlob = RsaAlgorithm.encrypt(encryptKey.getKeyBits(), plainBlob,
                                           encryptParams)
        receivedBlob = RsaAlgorithm.decrypt(decryptKey.getKeyBits(),
                                            encryptBlob, encryptParams)

        self.assertTrue(plainBlob.equals(receivedBlob))

        cipherBlob = Blob(CIPHERTEXT_OAEP, False)
        decryptedBlob = RsaAlgorithm.decrypt(decryptKey.getKeyBits(),
                                             cipherBlob, encryptParams)

        self.assertTrue(plainBlob.equals(decryptedBlob))

        # Now test RsaPkcs.
        encryptParams = EncryptParams(EncryptAlgorithmType.RsaPkcs, 0)
        encryptBlob = RsaAlgorithm.encrypt(encryptKey.getKeyBits(), plainBlob,
                                           encryptParams)
        receivedBlob = RsaAlgorithm.decrypt(decryptKey.getKeyBits(),
                                            encryptBlob, encryptParams)

        self.assertTrue(plainBlob.equals(receivedBlob))

        cipherBlob = Blob(CIPHERTEXT_PKCS, False)
        decryptedBlob = RsaAlgorithm.decrypt(decryptKey.getKeyBits(),
                                             cipherBlob, encryptParams)

        self.assertTrue(plainBlob.equals(decryptedBlob))
コード例 #17
0
    def setUp(self):
        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db"
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db"
        try:
            os.remove(self.eKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db"
        try:
            os.remove(self.intervalDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db"
        try:
            os.remove(self.groupKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        params = RsaKeyParams()
        memberDecryptKey = RsaAlgorithm.generateKey(params)
        self.decryptKeyBlob = memberDecryptKey.getKeyBits()
        memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob)
        self.encryptKeyBlob = memberEncryptKey.getKeyBits()

        # Generate the certificate.
        self.certificate = IdentityCertificate()
        self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
        contentPublicKey = PublicKey(self.encryptKeyBlob)
        self.certificate.setPublicKeyInfo(contentPublicKey)
        self.certificate.setNotBefore(0)
        self.certificate.setNotAfter(0)
        self.certificate.encode()

        signatureInfoBlob = Blob(SIG_INFO, False)
        signatureValueBlob = Blob(SIG_VALUE, False)

        signature = TlvWireFormat.get().decodeSignatureInfoAndValue(
            signatureInfoBlob.buf(), signatureValueBlob.buf())
        self.certificate.setSignature(signature)

        self.certificate.wireEncode()

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        identityName = Name("TestGroupManager")
        self.keyChain.createIdentityAndCertificate(identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
コード例 #18
0
    def test_get_group_key(self):
        # Create the group manager.
        manager = GroupManager(
          Name("Alice"), Name("data_type"),
          Sqlite3GroupManagerDb(self.groupKeyDatabaseFilePath), 1024, 1,
          self.keyChain)
        self.setManager(manager)

        # Get the data list from the group manager.
        timePoint1 = Schedule.fromIsoString("20150825T093000")
        result = manager.getGroupKey(timePoint1)

        self.assertEqual(4, len(result))

        # The first data packet contains the group's encryption key (public key).
        data = result[0]
        self.assertEqual(
          "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
          data.getName().toUri())
        groupEKey = EncryptKey(data.getContent())

        # Get the second data packet and decrypt.
        data = result[1]
        self.assertEqual(
          "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberA/ksk-123",
          data.getName().toUri())

        ####################################################### Start decryption.
        dataContent = data.getContent()

        # Get the nonce key.
        # dataContent is a sequence of the two EncryptedContent.
        encryptedNonce = EncryptedContent()
        encryptedNonce.wireDecode(dataContent)
        self.assertEqual(0, encryptedNonce.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.RsaOaep, encryptedNonce.getAlgorithmType())

        decryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        blobNonce = encryptedNonce.getPayload()
        nonce = RsaAlgorithm.decrypt(self.decryptKeyBlob, blobNonce, decryptParams)

        # Get the payload.
        # Use the size of encryptedNonce to find the start of encryptedPayload.
        payloadContent = dataContent.buf()[encryptedNonce.wireEncode().size():]
        encryptedPayload = EncryptedContent()
        encryptedPayload.wireDecode(payloadContent)
        self.assertEqual(16, encryptedPayload.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.AesCbc, encryptedPayload.getAlgorithmType())

        decryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
        decryptParams.setInitialVector(encryptedPayload.getInitialVector())
        blobPayload = encryptedPayload.getPayload()
        largePayload = AesAlgorithm.decrypt(nonce, blobPayload, decryptParams)

        # Get the group D-KEY.
        groupDKey = DecryptKey(largePayload)

        ####################################################### End decryption.

        # Check the D-KEY.
        derivedGroupEKey = RsaAlgorithm.deriveEncryptKey(groupDKey.getKeyBits())
        self.assertTrue(groupEKey.getKeyBits().equals(derivedGroupEKey.getKeyBits()))

        # Check the third data packet.
        data = result[2]
        self.assertEqual(
          "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberB/ksk-123",
          data.getName().toUri())

        # Check the fourth data packet.
        data = result[3]
        self.assertEqual(
          "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberC/ksk-123",
          data.getName().toUri())

        # Check invalid time stamps for getting the group key.
        timePoint2 = Schedule.fromIsoString("20150826T083000")
        self.assertEqual(0, len(manager.getGroupKey(timePoint2)))

        timePoint3 = Schedule.fromIsoString("20150827T023000")
        self.assertEqual(0, len(manager.getGroupKey(timePoint3)))
コード例 #19
0
    def setUp(self):
        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db"
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db"
        try:
            os.remove(self.eKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db"
        try:
            os.remove(self.intervalDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db"
        try:
            os.remove(self.groupKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        params = RsaKeyParams()
        memberDecryptKey = RsaAlgorithm.generateKey(params)
        self.decryptKeyBlob = memberDecryptKey.getKeyBits()
        memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob)
        self.encryptKeyBlob = memberEncryptKey.getKeyBits()

        # Generate the certificate.
        self.certificate = IdentityCertificate()
        self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
        contentPublicKey = PublicKey(self.encryptKeyBlob)
        self.certificate.setPublicKeyInfo(contentPublicKey)
        self.certificate.setNotBefore(0)
        self.certificate.setNotAfter(0)
        self.certificate.encode()

        signatureInfoBlob = Blob(SIG_INFO, False)
        signatureValueBlob = Blob(SIG_VALUE, False)

        signature = TlvWireFormat.get().decodeSignatureInfoAndValue(
          signatureInfoBlob.buf(), signatureValueBlob.buf())
        self.certificate.setSignature(signature)

        self.certificate.wireEncode()

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())
        identityName = Name("TestGroupManager")
        self.keyChain.createIdentityAndCertificate(identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
コード例 #20
0
    def test_get_group_key(self):
        # Create the group manager.
        manager = GroupManager(
            Name("Alice"), Name("data_type"),
            Sqlite3GroupManagerDb(self.groupKeyDatabaseFilePath), 1024, 1,
            self.keyChain)
        self.setManager(manager)

        # Get the data list from the group manager.
        timePoint1 = Schedule.fromIsoString("20150825T093000")
        result = manager.getGroupKey(timePoint1)

        self.assertEqual(4, len(result))

        # The first data packet contains the group's encryption key (public key).
        data = result[0]
        self.assertEqual(
            "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
            data.getName().toUri())
        groupEKey = EncryptKey(data.getContent())

        # Get the second data packet and decrypt.
        data = result[1]
        self.assertEqual(
            "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberA/ksk-123",
            data.getName().toUri())

        ####################################################### Start decryption.
        dataContent = data.getContent()

        # Get the nonce key.
        # dataContent is a sequence of the two EncryptedContent.
        encryptedNonce = EncryptedContent()
        encryptedNonce.wireDecode(dataContent)
        self.assertEqual(0, encryptedNonce.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.RsaOaep,
                         encryptedNonce.getAlgorithmType())

        decryptParams = EncryptParams(EncryptAlgorithmType.RsaOaep)
        blobNonce = encryptedNonce.getPayload()
        nonce = RsaAlgorithm.decrypt(self.decryptKeyBlob, blobNonce,
                                     decryptParams)

        # Get the payload.
        # Use the size of encryptedNonce to find the start of encryptedPayload.
        payloadContent = dataContent.buf()[encryptedNonce.wireEncode().size():]
        encryptedPayload = EncryptedContent()
        encryptedPayload.wireDecode(payloadContent)
        self.assertEqual(16, encryptedPayload.getInitialVector().size())
        self.assertEqual(EncryptAlgorithmType.AesCbc,
                         encryptedPayload.getAlgorithmType())

        decryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
        decryptParams.setInitialVector(encryptedPayload.getInitialVector())
        blobPayload = encryptedPayload.getPayload()
        largePayload = AesAlgorithm.decrypt(nonce, blobPayload, decryptParams)

        # Get the group D-KEY.
        groupDKey = DecryptKey(largePayload)

        ####################################################### End decryption.

        # Check the D-KEY.
        derivedGroupEKey = RsaAlgorithm.deriveEncryptKey(
            groupDKey.getKeyBits())
        self.assertTrue(groupEKey.getKeyBits().equals(
            derivedGroupEKey.getKeyBits()))

        # Check the third data packet.
        data = result[2]
        self.assertEqual(
            "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberB/ksk-123",
            data.getName().toUri())

        # Check the fourth data packet.
        data = result[3]
        self.assertEqual(
            "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberC/ksk-123",
            data.getName().toUri())

        # Check invalid time stamps for getting the group key.
        timePoint2 = Schedule.fromIsoString("20150826T083000")
        self.assertEqual(0, len(manager.getGroupKey(timePoint2)))

        timePoint3 = Schedule.fromIsoString("20150827T023000")
        self.assertEqual(0, len(manager.getGroupKey(timePoint3)))
コード例 #21
0
    def test_database_functions(self):
        scheduleBlob = Blob(SCHEDULE, False)

        # Create a schedule.
        schedule = Schedule()
        schedule.wireDecode(scheduleBlob)

        # Create a member.
        params = RsaKeyParams()
        decryptKey = RsaAlgorithm.generateKey(params)
        encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())
        keyBlob = encryptKey.getKeyBits()

        name1 = Name("/ndn/BoyA/ksk-123")
        name2 = Name("/ndn/BoyB/ksk-1233")
        name3 = Name("/ndn/GirlC/ksk-123")
        name4 = Name("/ndn/GirlD/ksk-123")
        name5 = Name("/ndn/Hello/ksk-123")

        # Add schedules into the database.
        self.database.addSchedule("work-time", schedule)
        self.database.addSchedule("rest-time", schedule)
        self.database.addSchedule("play-time", schedule)
        self.database.addSchedule("boelter-time", schedule)

        # Throw an exception when adding a schedule with an existing name.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.addSchedule("boelter-time", schedule)

        # Add members into the database.
        self.database.addMember("work-time", name1, keyBlob)
        self.database.addMember("rest-time", name2, keyBlob)
        self.database.addMember("play-time", name3, keyBlob)
        self.database.addMember("play-time", name4, keyBlob)

        # Throw an exception when adding a member with a non-existing schedule name.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.addMember("false-time", name5, keyBlob)

        self.database.addMember("boelter-time", name5, keyBlob)

        # Throw an exception when adding a member having an existing identity.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.addMember("work-time", name5, keyBlob)

        # Test has functions.
        self.assertEqual(True, self.database.hasSchedule("work-time"))
        self.assertEqual(True, self.database.hasSchedule("rest-time"))
        self.assertEqual(True, self.database.hasSchedule("play-time"))
        self.assertEqual(False, self.database.hasSchedule("sleep-time"))
        self.assertEqual(False, self.database.hasSchedule(""))

        self.assertEqual(True, self.database.hasMember(Name("/ndn/BoyA")))
        self.assertEqual(True, self.database.hasMember(Name("/ndn/BoyB")))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/BoyC")))

        # Get a schedule.
        scheduleResult = self.database.getSchedule("work-time")
        self.assertTrue(scheduleResult.wireEncode().equals(scheduleBlob))

        scheduleResult = self.database.getSchedule("play-time")
        self.assertTrue(scheduleResult.wireEncode().equals(scheduleBlob))

        # Throw an exception when when there is no such schedule in the database.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.getSchedule("work-time-11")

        # List all schedule names.
        names = self.database.listAllScheduleNames()
        self.assertTrue("work-time" in names)
        self.assertTrue("play-time" in names)
        self.assertTrue("rest-time" in names)
        self.assertTrue(not ("sleep-time" in names))

        # List members of a schedule.
        memberMap = self.database.getScheduleMembers("play-time")
        self.assertTrue(len(memberMap) != 0)

        # When there's no such schedule, the return map's size should be 0.
        self.assertEquals(0, len(self.database.getScheduleMembers("sleep-time")))

        # List all members.
        members = self.database.listAllMembers()
        self.assertTrue(Name("/ndn/GirlC") in members)
        self.assertTrue(Name("/ndn/GirlD") in members)
        self.assertTrue(Name("/ndn/BoyA") in members)
        self.assertTrue(Name("/ndn/BoyB") in members)

        # Rename a schedule.
        self.assertEqual(True, self.database.hasSchedule("boelter-time"))
        self.database.renameSchedule("boelter-time", "rieber-time")
        self.assertEqual(False, self.database.hasSchedule("boelter-time"))
        self.assertEqual(True, self.database.hasSchedule("rieber-time"))
        self.assertEqual("rieber-time", self.database.getMemberSchedule(Name("/ndn/Hello")))

        # Update a schedule.
        newSchedule = Schedule()
        newSchedule.wireDecode(scheduleBlob)
        repetitiveInterval = RepetitiveInterval(
          Schedule.fromIsoString("20150825T000000"),
          Schedule.fromIsoString("20150921T000000"), 2, 10,
          5, RepetitiveInterval.RepeatUnit.DAY)
        newSchedule.addWhiteInterval(repetitiveInterval)
        self.database.updateSchedule("rieber-time", newSchedule)
        scheduleResult = self.database.getSchedule("rieber-time")
        self.assertTrue(not scheduleResult.wireEncode().equals(scheduleBlob))
        self.assertTrue(scheduleResult.wireEncode().equals(newSchedule.wireEncode()))

        # Add a new schedule when updating a non-existing schedule.
        self.assertEquals(False, self.database.hasSchedule("ralphs-time"))
        self.database.updateSchedule("ralphs-time", newSchedule)
        self.assertEquals(True, self.database.hasSchedule("ralphs-time"))

        # Update the schedule of a member.
        self.database.updateMemberSchedule(Name("/ndn/Hello"), "play-time")
        self.assertEqual("play-time", self.database.getMemberSchedule(Name("/ndn/Hello")))

        # Delete a member.
        self.assertEqual(True, self.database.hasMember(Name("/ndn/Hello")))
        self.database.deleteMember(Name("/ndn/Hello"))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/Hello")))

        # Delete a non-existing member.
        try:
            self.database.deleteMember(Name("/ndn/notExisting"))
        except Exception as ex:
            self.fail("Unexpected error deleting a non-existing member: " + repr(ex))

        # Delete a schedule. All the members using this schedule should be deleted.
        self.database.deleteSchedule("play-time")
        self.assertEqual(False, self.database.hasSchedule("play-time"))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/GirlC")))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/GirlD")))

        # Delete a non-existing schedule.
        try:
            self.database.deleteSchedule("not-existing-time")
        except Exception as ex:
            self.fail("Unexpected error deleting a non-existing schedule: " + repr(ex))
コード例 #22
0
ファイル: test_encryptor.py プロジェクト: ISHITADG/PyNDN2
    def test_content_asymmetric_encrypt_large(self):
        for input in encryptorRsaTestInputs:
            largeContent = Blob(bytearray([
                0x73, 0x5a, 0xbd, 0x47, 0x0c, 0xfe, 0xf8, 0x7d,
                0x2e, 0x17, 0xaa, 0x11, 0x6f, 0x23, 0xc5, 0x10,
                0x23, 0x36, 0x88, 0xc4, 0x2a, 0x0f, 0x9a, 0x72,
                0x54, 0x31, 0xa8, 0xb3, 0x51, 0x18, 0x9f, 0x0e,
                0x1b, 0x93, 0x62, 0xd9, 0xc4, 0xf5, 0xf4, 0x3d,
                0x61, 0x9a, 0xca, 0x05, 0x65, 0x6b, 0xc6, 0x41,
                0xf9, 0xd5, 0x1c, 0x67, 0xc1, 0xd0, 0xd5, 0x6f,
                0x7b, 0x70, 0xb8, 0x8f, 0xdb, 0x19, 0x68, 0x7c,
                0xe0, 0x2d, 0x04, 0x49, 0xa9, 0xa2, 0x77, 0x4e,
                0xfc, 0x60, 0x0d, 0x7c, 0x1b, 0x93, 0x6c, 0xd2,
                0x61, 0xc4, 0x6b, 0x01, 0xe9, 0x12, 0x28, 0x6d,
                0xf5, 0x78, 0xe9, 0x99, 0x0b, 0x9c, 0x4f, 0x90,
                0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f,
                0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48,
                0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5,
                0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde,
                0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9,
                0x22, 0xf1, 0x67, 0x76, 0x71, 0x0c, 0xff, 0x99,
                0x7b, 0x94, 0x9b, 0x24, 0x20, 0x80, 0xe3, 0xcc,
                0x06, 0x4a, 0xed, 0xdf, 0xec, 0x50, 0xd5, 0x87,
                0x3d, 0xa0, 0x7d, 0x9c, 0xe5, 0x13, 0x10, 0x98,
                0x14, 0xc3, 0x90, 0x10, 0xd9, 0x25, 0x9a, 0x59,
                0xe9, 0x37, 0x26, 0xfd, 0x87, 0xd7, 0xf4, 0xf9,
                0x11, 0x91, 0xad, 0x5c, 0x00, 0x95, 0xf5, 0x2b,
                0x37, 0xf7, 0x4e, 0xb4, 0x4b, 0x42, 0x7c, 0xb3,
                0xad, 0xd6, 0x33, 0x5f, 0x0b, 0x84, 0x57, 0x7f,
                0xa7, 0x07, 0x73, 0x37, 0x4b, 0xab, 0x2e, 0xfb,
                0xfe, 0x1e, 0xcb, 0xb6, 0x4a, 0xc1, 0x21, 0x5f,
                0xec, 0x92, 0xb7, 0xac, 0x97, 0x75, 0x20, 0xc9,
                0xd8, 0x9e, 0x93, 0xd5, 0x12, 0x7a, 0x64, 0xb9,
                0x4c, 0xed, 0x49, 0x87, 0x44, 0x5b, 0x4f, 0x90,
                0x34, 0x3e, 0x06, 0x92, 0x57, 0xe3, 0x7a, 0x8f,
                0x13, 0xc7, 0xf3, 0xfe, 0xf0, 0xe2, 0x59, 0x48,
                0x15, 0xb9, 0xdb, 0x77, 0x07, 0x1d, 0x6d, 0xb5,
                0x65, 0x17, 0xdf, 0x76, 0x6f, 0xb5, 0x43, 0xde,
                0x71, 0xac, 0xf1, 0x22, 0xbf, 0xb2, 0xe5, 0xd9
              ]), False)

            data = Data()
            rsaParams = RsaKeyParams(1024)

            keyName = Name("test")

            decryptKey = RsaAlgorithm.generateKey(rsaParams)
            encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())

            eKey = encryptKey.getKeyBits()
            dKey = decryptKey.getKeyBits()

            encryptParams = EncryptParams(input.type)
            Encryptor.encryptData(data, largeContent, keyName, eKey, encryptParams)

            self.assertTrue(data.getName().equals(Name("/FOR").append(keyName)),
                            input.testName)

            largeDataContent = data.getContent()

            # largeDataContent is a sequence of the two EncryptedContent.
            encryptedNonce = EncryptedContent()
            encryptedNonce.wireDecode(largeDataContent)
            self.assertTrue(keyName.equals(encryptedNonce.getKeyLocator().getKeyName()),
                            input.testName)
            self.assertEqual(encryptedNonce.getInitialVector().size(), 0,
                             input.testName)
            self.assertEqual(encryptedNonce.getAlgorithmType(), input.type,
                             input.testName)

            # Use the size of encryptedNonce to find the start of encryptedPayload.
            payloadContent = largeDataContent.buf()[encryptedNonce.wireEncode().size():]
            encryptedPayload = EncryptedContent()
            encryptedPayload.wireDecode(payloadContent)
            nonceKeyName = Name(keyName)
            nonceKeyName.append("nonce")
            self.assertTrue(nonceKeyName.equals(encryptedPayload.getKeyLocator().getKeyName()),
                            input.testName)
            self.assertEqual(encryptedPayload.getInitialVector().size(), 16,
                             input.testName)
            self.assertEqual(encryptedPayload.getAlgorithmType(), EncryptAlgorithmType.AesCbc,
                             input.testName)

            self.assertEqual(
              largeDataContent.size(),
              encryptedNonce.wireEncode().size() + encryptedPayload.wireEncode().size(),
              input.testName)

            blobNonce = encryptedNonce.getPayload()
            nonce = RsaAlgorithm.decrypt(dKey, blobNonce, encryptParams)

            encryptParams.setAlgorithmType(EncryptAlgorithmType.AesCbc)
            encryptParams.setInitialVector(encryptedPayload.getInitialVector())
            bufferPayload = encryptedPayload.getPayload()
            largePayload = AesAlgorithm.decrypt(nonce, bufferPayload, encryptParams)

            self.assertTrue(largeContent.equals(largePayload), input.testName)
コード例 #23
0
ファイル: test_group_manager_db.py プロジェクト: MAHIS/PyNDN2
    def test_database_functions(self):
        scheduleBlob = Blob(SCHEDULE, False)

        # Create a schedule.
        schedule = Schedule()
        schedule.wireDecode(scheduleBlob)

        # Create a member.
        params = RsaKeyParams()
        decryptKey = RsaAlgorithm.generateKey(params)
        encryptKey = RsaAlgorithm.deriveEncryptKey(decryptKey.getKeyBits())
        keyBlob = encryptKey.getKeyBits()

        name1 = Name("/ndn/BoyA/ksk-123")
        name2 = Name("/ndn/BoyB/ksk-1233")
        name3 = Name("/ndn/GirlC/ksk-123")
        name4 = Name("/ndn/GirlD/ksk-123")
        name5 = Name("/ndn/Hello/ksk-123")

        # Add schedules into the database.
        self.database.addSchedule("work-time", schedule)
        self.database.addSchedule("rest-time", schedule)
        self.database.addSchedule("play-time", schedule)
        self.database.addSchedule("boelter-time", schedule)

        # Throw an exception when adding a schedule with an existing name.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.addSchedule("boelter-time", schedule)

        # Add members into the database.
        self.database.addMember("work-time", name1, keyBlob)
        self.database.addMember("rest-time", name2, keyBlob)
        self.database.addMember("play-time", name3, keyBlob)
        self.database.addMember("play-time", name4, keyBlob)

        # Throw an exception when adding a member with a non-existing schedule name.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.addMember("false-time", name5, keyBlob)

        self.database.addMember("boelter-time", name5, keyBlob)

        # Throw an exception when adding a member having an existing identity.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.addMember("work-time", name5, keyBlob)

        # Test has functions.
        self.assertEqual(True, self.database.hasSchedule("work-time"))
        self.assertEqual(True, self.database.hasSchedule("rest-time"))
        self.assertEqual(True, self.database.hasSchedule("play-time"))
        self.assertEqual(False, self.database.hasSchedule("sleep-time"))
        self.assertEqual(False, self.database.hasSchedule(""))

        self.assertEqual(True, self.database.hasMember(Name("/ndn/BoyA")))
        self.assertEqual(True, self.database.hasMember(Name("/ndn/BoyB")))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/BoyC")))

        # Get a schedule.
        scheduleResult = self.database.getSchedule("work-time")
        self.assertTrue(scheduleResult.wireEncode().equals(scheduleBlob))

        scheduleResult = self.database.getSchedule("play-time")
        self.assertTrue(scheduleResult.wireEncode().equals(scheduleBlob))

        # Throw an exception when when there is no such schedule in the database.
        with self.assertRaises(GroupManagerDb.Error):
            self.database.getSchedule("work-time-11")

        # List all schedule names.
        names = self.database.listAllScheduleNames()
        self.assertTrue("work-time" in names)
        self.assertTrue("play-time" in names)
        self.assertTrue("rest-time" in names)
        self.assertTrue(not ("sleep-time" in names))

        # List members of a schedule.
        memberMap = self.database.getScheduleMembers("play-time")
        self.assertTrue(len(memberMap) != 0)

        # When there's no such schedule, the return map's size should be 0.
        self.assertEquals(0, len(self.database.getScheduleMembers("sleep-time")))

        # List all members.
        members = self.database.listAllMembers()
        self.assertTrue(Name("/ndn/GirlC") in members)
        self.assertTrue(Name("/ndn/GirlD") in members)
        self.assertTrue(Name("/ndn/BoyA") in members)
        self.assertTrue(Name("/ndn/BoyB") in members)

        # Rename a schedule.
        self.assertEqual(True, self.database.hasSchedule("boelter-time"))
        self.database.renameSchedule("boelter-time", "rieber-time")
        self.assertEqual(False, self.database.hasSchedule("boelter-time"))
        self.assertEqual(True, self.database.hasSchedule("rieber-time"))
        self.assertEqual("rieber-time", self.database.getMemberSchedule(Name("/ndn/Hello")))

        # Update a schedule.
        newSchedule = Schedule()
        newSchedule.wireDecode(scheduleBlob)
        repetitiveInterval = RepetitiveInterval(
          Schedule.fromIsoString("20150825T000000"),
          Schedule.fromIsoString("20150921T000000"), 2, 10,
          5, RepetitiveInterval.RepeatUnit.DAY)
        newSchedule.addWhiteInterval(repetitiveInterval)
        self.database.updateSchedule("rieber-time", newSchedule)
        scheduleResult = self.database.getSchedule("rieber-time")
        self.assertTrue(not scheduleResult.wireEncode().equals(scheduleBlob))
        self.assertTrue(scheduleResult.wireEncode().equals(newSchedule.wireEncode()))

        # Add a new schedule when updating a non-existing schedule.
        self.assertEquals(False, self.database.hasSchedule("ralphs-time"))
        self.database.updateSchedule("ralphs-time", newSchedule)
        self.assertEquals(True, self.database.hasSchedule("ralphs-time"))

        # Update the schedule of a member.
        self.database.updateMemberSchedule(Name("/ndn/Hello"), "play-time")
        self.assertEqual("play-time", self.database.getMemberSchedule(Name("/ndn/Hello")))

        # Delete a member.
        self.assertEqual(True, self.database.hasMember(Name("/ndn/Hello")))
        self.database.deleteMember(Name("/ndn/Hello"))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/Hello")))

        # Delete a non-existing member.
        try:
            self.database.deleteMember(Name("/ndn/notExisting"))
        except Exception as ex:
            self.fail("Unexpected error deleting a non-existing member: " + repr(ex))

        # Delete a schedule. All the members using this schedule should be deleted.
        self.database.deleteSchedule("play-time")
        self.assertEqual(False, self.database.hasSchedule("play-time"))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/GirlC")))
        self.assertEqual(False, self.database.hasMember(Name("/ndn/GirlD")))

        # Delete a non-existing schedule.
        try:
            self.database.deleteSchedule("not-existing-time")
        except Exception as ex:
            self.fail("Unexpected error deleting a non-existing schedule: " + repr(ex))