Exemple #1
0
    def _generateCertificateForKey(self, keyName):
        # Let any raised SecurityExceptions bubble up.
        publicKeyBits = self._identityStorage.getKey(keyName)

        publicKey = PublicKey(publicKeyBits)

        timestamp = Common.getNowMilliseconds()

        # TODO: Specify where the 'KEY' component is inserted
        # to delegate responsibility for cert delivery.
        # cf: http://redmine.named-data.net/issues/1659
        certificateName = keyName.getPrefix(-1).append('KEY').append(
            keyName.get(-1))
        certificateName.append("ID-CERT").appendVersion(int(timestamp))

        certificate = IdentityCertificate()
        certificate.setName(certificateName)

        certificate.setNotBefore(timestamp)
        certificate.setNotAfter(
            (timestamp + 2 * 365 * 24 * 3600 * 1000))  # about 2 years.

        certificate.setPublicKeyInfo(publicKey)

        # ndnsec likes to put the key name in a subject description.
        sd = CertificateSubjectDescription("2.5.4.41", keyName.toUri())
        certificate.addSubjectDescription(sd)

        certificate.encode()

        return certificate
    def generateCertificateForKey(self, keyName):
        # let any raised SecurityExceptions bubble up
        publicKeyBits = self._identityStorage.getKey(keyName)
        publicKeyType = self._identityStorage.getKeyType(keyName)
    
        publicKey = PublicKey(publicKeyType, publicKeyBits)

        timestamp = Common.getNowMilliseconds()
    
        # TODO: specify where the 'KEY' component is inserted
        # to delegate responsibility for cert delivery
        certificateName = keyName.getPrefix(-1).append('KEY').append(keyName.get(-1))
        certificateName.append("ID-CERT").append(Name.Component(struct.pack(">Q", timestamp)))        

        certificate = IdentityCertificate(certificateName)


        certificate.setNotBefore(timestamp)
        certificate.setNotAfter((timestamp + 30*86400*1000)) # about a month

        certificate.setPublicKeyInfo(publicKey)

        # ndnsec likes to put the key name in a subject description
        sd = CertificateSubjectDescription("2.5.4.41", keyName.toUri())
        certificate.addSubjectDescription(sd)

        certificate.encode()

        return certificate
Exemple #3
0
    def _generateCertificateForKey(self, keyName):
        # Let any raised SecurityExceptions bubble up.
        publicKeyBits = self._identityStorage.getKey(keyName)

        publicKey = PublicKey(publicKeyBits)

        timestamp = Common.getNowMilliseconds()

        # TODO: Specify where the 'KEY' component is inserted
        # to delegate responsibility for cert delivery.
        # cf: http://redmine.named-data.net/issues/1659
        certificateName = keyName.getPrefix(-1).append('KEY').append(keyName.get(-1))
        certificateName.append("ID-CERT").appendVersion(int(timestamp))

        certificate = IdentityCertificate()
        certificate.setName(certificateName)

        certificate.setNotBefore(timestamp)
        certificate.setNotAfter((timestamp + 2*365*24*3600*1000)) # about 2 years.

        certificate.setPublicKeyInfo(publicKey)

        # ndnsec likes to put the key name in a subject description.
        sd = CertificateSubjectDescription("2.5.4.41", keyName.toUri())
        certificate.addSubjectDescription(sd)

        certificate.encode()

        return certificate
    def generateCertificateForKey(self, keyName):
        # let any raised SecurityExceptions bubble up
        publicKeyBits = self._identityStorage.getKey(keyName)
        publicKeyType = self._identityStorage.getKeyType(keyName)

        publicKey = PublicKey(publicKeyType, publicKeyBits)

        timestamp = Common.getNowMilliseconds()

        # TODO: specify where the 'KEY' component is inserted
        # to delegate responsibility for cert delivery
        certificateName = keyName.getPrefix(-1).append('KEY').append(
            keyName.get(-1))
        certificateName.append("ID-CERT").append(
            Name.Component(struct.pack(">Q", timestamp)))

        certificate = IdentityCertificate(certificateName)

        certificate.setNotBefore(timestamp)
        certificate.setNotAfter(
            (timestamp + 30 * 86400 * 1000))  # about a month

        certificate.setPublicKeyInfo(publicKey)

        # ndnsec likes to put the key name in a subject description
        sd = CertificateSubjectDescription("2.5.4.41", keyName.toUri())
        certificate.addSubjectDescription(sd)

        certificate.encode()

        return certificate
Exemple #5
0
class TestGroupManager(ut.TestCase):
    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)

    def tearDown(self):
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            pass
        try:
            os.remove(self.eKeyDatabaseFilePath)
        except OSError:
            pass
        try:
            os.remove(self.intervalDatabaseFilePath)
        except OSError:
            pass
        try:
            os.remove(self.groupKeyDatabaseFilePath)
        except OSError:
            pass

    def setManager(self, manager):
        # Set up the first schedule.
        schedule1 = Schedule()
        interval11 = RepetitiveInterval(
            Schedule.fromIsoString("20150825T000000"),
            Schedule.fromIsoString("20150827T000000"), 5, 10, 2,
            RepetitiveInterval.RepeatUnit.DAY)
        interval12 = RepetitiveInterval(
            Schedule.fromIsoString("20150825T000000"),
            Schedule.fromIsoString("20150827T000000"), 6, 8, 1,
            RepetitiveInterval.RepeatUnit.DAY)
        interval13 = RepetitiveInterval(
            Schedule.fromIsoString("20150827T000000"),
            Schedule.fromIsoString("20150827T000000"), 7, 8)
        schedule1.addWhiteInterval(interval11)
        schedule1.addWhiteInterval(interval12)
        schedule1.addBlackInterval(interval13)

        # Set up the second schedule.
        schedule2 = Schedule()
        interval21 = RepetitiveInterval(
            Schedule.fromIsoString("20150825T000000"),
            Schedule.fromIsoString("20150827T000000"), 9, 12, 1,
            RepetitiveInterval.RepeatUnit.DAY)
        interval22 = RepetitiveInterval(
            Schedule.fromIsoString("20150827T000000"),
            Schedule.fromIsoString("20150827T000000"), 6, 8)
        interval23 = RepetitiveInterval(
            Schedule.fromIsoString("20150827T000000"),
            Schedule.fromIsoString("20150827T000000"), 2, 4)
        schedule2.addWhiteInterval(interval21)
        schedule2.addWhiteInterval(interval22)
        schedule2.addBlackInterval(interval23)

        # Add them to the group manager database.
        manager.addSchedule("schedule1", schedule1)
        manager.addSchedule("schedule2", schedule2)

        # Make some adaptions to certificate.
        dataBlob = self.certificate.wireEncode()

        memberA = Data()
        memberA.wireDecode(dataBlob, TlvWireFormat.get())
        memberA.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
        memberB = Data()
        memberB.wireDecode(dataBlob, TlvWireFormat.get())
        memberB.setName(Name("/ndn/memberB/KEY/ksk-123/ID-CERT/123"))
        memberC = Data()
        memberC.wireDecode(dataBlob, TlvWireFormat.get())
        memberC.setName(Name("/ndn/memberC/KEY/ksk-123/ID-CERT/123"))

        # Add the members to the database.
        manager.addMember("schedule1", memberA)
        manager.addMember("schedule1", memberB)
        manager.addMember("schedule2", memberC)

    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))

    def test_create_e_key_data(self):
        # Create the group manager.
        manager = GroupManager(
            Name("Alice"), Name("data_type"),
            Sqlite3GroupManagerDb(self.eKeyDatabaseFilePath), 1024, 1,
            self.keyChain)
        self.setManager(manager)

        data = manager._createEKeyData("20150825T090000", "20150825T110000",
                                       self.encryptKeyBlob)
        self.assertEqual(
            "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T110000",
            data.getName().toUri())

        contentBlob = data.getContent()
        self.assertTrue(self.encryptKeyBlob.equals(contentBlob))

    def test_calculate_interval(self):
        # Create the group manager.
        manager = GroupManager(
            Name("Alice"), Name("data_type"),
            Sqlite3GroupManagerDb(self.intervalDatabaseFilePath), 1024, 1,
            self.keyChain)
        self.setManager(manager)

        memberKeys = {}

        timePoint1 = Schedule.fromIsoString("20150825T093000")
        result = manager._calculateInterval(timePoint1, memberKeys)
        self.assertEqual("20150825T090000",
                         Schedule.toIsoString(result.getStartTime()))
        self.assertEqual("20150825T100000",
                         Schedule.toIsoString(result.getEndTime()))

        timePoint2 = Schedule.fromIsoString("20150827T073000")
        result = manager._calculateInterval(timePoint2, memberKeys)
        self.assertEqual("20150827T070000",
                         Schedule.toIsoString(result.getStartTime()))
        self.assertEqual("20150827T080000",
                         Schedule.toIsoString(result.getEndTime()))

        timePoint3 = Schedule.fromIsoString("20150827T043000")
        result = manager._calculateInterval(timePoint3, memberKeys)
        self.assertEqual(False, result.isValid())

        timePoint4 = Schedule.fromIsoString("20150827T053000")
        result = manager._calculateInterval(timePoint4, memberKeys)
        self.assertEqual("20150827T050000",
                         Schedule.toIsoString(result.getStartTime()))
        self.assertEqual("20150827T060000",
                         Schedule.toIsoString(result.getEndTime()))

    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)))

    def test_get_group_key_without_regeneration(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).
        data1 = result[0]
        self.assertEqual(
            "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
            data1.getName().toUri())
        groupEKey1 = EncryptKey(data1.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())

        # Add new members to the database.
        dataBlob = self.certificate.wireEncode()
        memberD = Data()
        memberD.wireDecode(dataBlob)
        memberD.setName(Name("/ndn/memberD/KEY/ksk-123/ID-CERT/123"))
        manager.addMember("schedule1", memberD)

        result2 = manager.getGroupKey(timePoint1, False)
        self.assertEqual(5, len(result2))

        # Check that the new EKey is the same as the previous one.
        data2 = result2[0]
        self.assertEqual(
            "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
            data2.getName().toUri())
        groupEKey2 = EncryptKey(data2.getContent())
        self.assertTrue(groupEKey1.getKeyBits().equals(
            groupEKey2.getKeyBits()))

        # Check the second data packet.
        data2 = result2[1]
        self.assertEqual(
            "/Alice/READ/data_type/D-KEY/20150825T090000/20150825T100000/FOR/ndn/memberA/ksk-123",
            data2.getName().toUri())
Exemple #6
0
    def prepareUnsignedIdentityCertificate(self,
                                           keyName,
                                           publicKey,
                                           signingIdentity,
                                           notBefore,
                                           notAfter,
                                           subjectDescription=None,
                                           certPrefix=None):
        """
        Prepare an unsigned identity certificate.

        :param Name keyName: The key name, e.g., `/{identity_name}/ksk-123456`.
        :param PublicKey publicKey: (optional) The public key to sign. If
          ommited, use the keyName to get the public key from the identity
          storage.
        :param Name signingIdentity: The signing identity.
        :param float notBefore: See IdentityCertificate.
        :param float notAfter: See IdentityCertificate.
        :param Array<CertificateSubjectDescription> subjectDescription: A list
          of CertificateSubjectDescription. See IdentityCertificate. If None or
          empty, this adds a an ATTRIBUTE_NAME based on the keyName.
        :param Name certPrefix: (optional) The prefix before the `KEY`
          component. If None, this infers the certificate name according to the
          relation between the signingIdentity and the subject identity. If the
          signingIdentity is a prefix of the subject identity, `KEY` will be
          inserted after the signingIdentity, otherwise `KEY` is inserted after
          subject identity (i.e., before `ksk-...`).
        :return: The unsigned IdentityCertificate, or None if the inputs are
          invalid.
        :rtype: IdentityCertificate
        """
        if not isinstance(publicKey, PublicKey):
            # The publicKey was omitted. Shift arguments.
            certPrefix = subjectDescription
            subjectDescription = notAfter
            notAfter = notBefore
            notBefore = signingIdentity
            signingIdentity = publicKey

            publicKey = PublicKey(self._identityStorage.getKey(keyName))

        if keyName.size() < 1:
            return None

        tempKeyIdPrefix = keyName.get(-1).toEscapedString()
        if len(tempKeyIdPrefix) < 4:
            return None
        keyIdPrefix = tempKeyIdPrefix[0:4]
        if keyIdPrefix != "ksk-" and keyIdPrefix != "dsk-":
            return None

        certificate = IdentityCertificate()
        certName = Name()

        if certPrefix == None:
            # No certificate prefix hint, so infer the prefix.
            if signingIdentity.match(keyName):
                certName.append(signingIdentity) \
                    .append("KEY") \
                    .append(keyName.getSubName(signingIdentity.size())) \
                    .append("ID-CERT") \
                    .appendVersion(int(Common.getNowMilliseconds()))
            else:
                certName.append(keyName.getPrefix(-1)) \
                    .append("KEY") \
                    .append(keyName.get(-1)) \
                    .append("ID-CERT") \
                    .appendVersion(int(Common.getNowMilliseconds()))
        else:
            # A cert prefix hint is supplied, so determine the cert name.
            if certPrefix.match(keyName) and not certPrefix.equals(keyName):
                certName.append(certPrefix) \
                    .append("KEY") \
                    .append(keyName.getSubName(certPrefix.size())) \
                    .append("ID-CERT") \
                    .appendVersion(int(Common.getNowMilliseconds()))
            else:
                return None

        certificate.setName(certName)
        certificate.setNotBefore(notBefore)
        certificate.setNotAfter(notAfter)
        certificate.setPublicKeyInfo(publicKey)

        if subjectDescription == None or len(subjectDescription) == 0:
            certificate.addSubjectDescription(
                CertificateSubjectDescription("2.5.4.41",
                                              keyName.getPrefix(-1).toUri()))
        else:
            for i in range(len(subjectDescription)):
                certificate.addSubjectDescription(subjectDescription[i])

        try:
            certificate.encode()
        except Exception as ex:
            raise SecurityException("DerEncodingException: " + str(ex))

        return certificate
Exemple #7
0
    def prepareUnsignedIdentityCertificate(self, keyName, publicKey,
          signingIdentity, notBefore, notAfter, subjectDescription = None,
          certPrefix = None):
        """
        Prepare an unsigned identity certificate.

        :param Name keyName: The key name, e.g., `/{identity_name}/ksk-123456`.
        :param PublicKey publicKey: (optional) The public key to sign. If
          ommited, use the keyName to get the public key from the identity
          storage.
        :param Name signingIdentity: The signing identity.
        :param float notBefore: See IdentityCertificate.
        :param float notAfter: See IdentityCertificate.
        :param Array<CertificateSubjectDescription> subjectDescription: A list
          of CertificateSubjectDescription. See IdentityCertificate. If None or
          empty, this adds a an ATTRIBUTE_NAME based on the keyName.
        :param Name certPrefix: (optional) The prefix before the `KEY`
          component. If None, this infers the certificate name according to the
          relation between the signingIdentity and the subject identity. If the
          signingIdentity is a prefix of the subject identity, `KEY` will be
          inserted after the signingIdentity, otherwise `KEY` is inserted after
          subject identity (i.e., before `ksk-...`).
        :return: The unsigned IdentityCertificate, or None if the inputs are
          invalid.
        :rtype: IdentityCertificate
        """
        if not isinstance(publicKey, PublicKey):
            # The publicKey was omitted. Shift arguments.
            certPrefix = subjectDescription
            subjectDescription = notAfter
            notAfter = notBefore
            notBefore = signingIdentity
            signingIdentity = publicKey

            publicKey = PublicKey(self._identityStorage.getKey(keyName))

        if keyName.size() < 1:
            return None

        tempKeyIdPrefix = keyName.get(-1).toEscapedString()
        if len(tempKeyIdPrefix) < 4:
            return None
        keyIdPrefix = tempKeyIdPrefix[0:4]
        if keyIdPrefix != "ksk-" and keyIdPrefix != "dsk-":
            return None

        certificate = IdentityCertificate()
        certName = Name()

        if certPrefix == None:
            # No certificate prefix hint, so infer the prefix.
            if signingIdentity.match(keyName):
                certName.append(signingIdentity) \
                    .append("KEY") \
                    .append(keyName.getSubName(signingIdentity.size())) \
                    .append("ID-CERT") \
                    .appendVersion(int(Common.getNowMilliseconds()))
            else:
                certName.append(keyName.getPrefix(-1)) \
                    .append("KEY") \
                    .append(keyName.get(-1)) \
                    .append("ID-CERT") \
                    .appendVersion(int(Common.getNowMilliseconds()))
        else:
            # A cert prefix hint is supplied, so determine the cert name.
            if certPrefix.match(keyName) and not certPrefix.equals(keyName):
                certName.append(certPrefix) \
                    .append("KEY") \
                    .append(keyName.getSubName(certPrefix.size())) \
                    .append("ID-CERT") \
                    .appendVersion(int(Common.getNowMilliseconds()))
            else:
                return None

        certificate.setName(certName)
        certificate.setNotBefore(notBefore)
        certificate.setNotAfter(notAfter)
        certificate.setPublicKeyInfo(publicKey)

        if subjectDescription == None or len(subjectDescription) == 0:
            certificate.addSubjectDescription(CertificateSubjectDescription(
              "2.5.4.41", keyName.getPrefix(-1).toUri()))
        else:
            for i in range(len(subjectDescription)):
                certificate.addSubjectDescription(subjectDescription[i])

        try:
            certificate.encode()
        except Exception as ex:
            raise SecurityException("DerEncodingException: " + str(ex))

        return certificate
class TestGroupManager(ut.TestCase):
    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)

    def tearDown(self):
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            pass
        try:
            os.remove(self.eKeyDatabaseFilePath)
        except OSError:
            pass
        try:
            os.remove(self.intervalDatabaseFilePath)
        except OSError:
            pass
        try:
            os.remove(self.groupKeyDatabaseFilePath)
        except OSError:
            pass

    def setManager(self, manager):
        # Set up the first schedule.
        schedule1 = Schedule()
        interval11 = RepetitiveInterval(
          Schedule.fromIsoString("20150825T000000"),
          Schedule.fromIsoString("20150827T000000"), 5, 10, 2,
          RepetitiveInterval.RepeatUnit.DAY)
        interval12 = RepetitiveInterval(
          Schedule.fromIsoString("20150825T000000"),
          Schedule.fromIsoString("20150827T000000"), 6, 8, 1,
          RepetitiveInterval.RepeatUnit.DAY)
        interval13 = RepetitiveInterval(
          Schedule.fromIsoString("20150827T000000"),
          Schedule.fromIsoString("20150827T000000"), 7, 8)
        schedule1.addWhiteInterval(interval11)
        schedule1.addWhiteInterval(interval12)
        schedule1.addBlackInterval(interval13)

        # Set up the second schedule.
        schedule2 = Schedule()
        interval21 = RepetitiveInterval(
          Schedule.fromIsoString("20150825T000000"),
          Schedule.fromIsoString("20150827T000000"), 9, 12, 1,
          RepetitiveInterval.RepeatUnit.DAY)
        interval22 = RepetitiveInterval(
          Schedule.fromIsoString("20150827T000000"),
          Schedule.fromIsoString("20150827T000000"), 6, 8)
        interval23 = RepetitiveInterval(
          Schedule.fromIsoString("20150827T000000"),
          Schedule.fromIsoString("20150827T000000"), 2, 4)
        schedule2.addWhiteInterval(interval21)
        schedule2.addWhiteInterval(interval22)
        schedule2.addBlackInterval(interval23)

        # Add them to the group manager database.
        manager.addSchedule("schedule1", schedule1)
        manager.addSchedule("schedule2", schedule2)

        # Make some adaptions to certificate.
        dataBlob = self.certificate.wireEncode()

        memberA = Data()
        memberA.wireDecode(dataBlob, TlvWireFormat.get())
        memberA.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
        memberB = Data()
        memberB.wireDecode(dataBlob, TlvWireFormat.get())
        memberB.setName(Name("/ndn/memberB/KEY/ksk-123/ID-CERT/123"))
        memberC = Data()
        memberC.wireDecode(dataBlob, TlvWireFormat.get())
        memberC.setName(Name("/ndn/memberC/KEY/ksk-123/ID-CERT/123"))

        # Add the members to the database.
        manager.addMember("schedule1", memberA)
        manager.addMember("schedule1", memberB)
        manager.addMember("schedule2", memberC)

    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))

    def test_create_e_key_data(self):
        # Create the group manager.
        manager = GroupManager(
          Name("Alice"), Name("data_type"),
          Sqlite3GroupManagerDb(self.eKeyDatabaseFilePath), 1024, 1,
          self.keyChain)
        self.setManager(manager)

        data = manager._createEKeyData(
          "20150825T090000", "20150825T110000", self.encryptKeyBlob)
        self.assertEqual("/Alice/READ/data_type/E-KEY/20150825T090000/20150825T110000",
                         data.getName().toUri())

        contentBlob = data.getContent()
        self.assertTrue(self.encryptKeyBlob.equals(contentBlob))

    def test_calculate_interval(self):
        # Create the group manager.
        manager = GroupManager(
          Name("Alice"), Name("data_type"),
          Sqlite3GroupManagerDb(self.intervalDatabaseFilePath), 1024, 1,
          self.keyChain)
        self.setManager(manager)

        memberKeys = {}

        timePoint1 = Schedule.fromIsoString("20150825T093000")
        result = manager._calculateInterval(timePoint1, memberKeys)
        self.assertEqual("20150825T090000", Schedule.toIsoString(result.getStartTime()))
        self.assertEqual("20150825T100000", Schedule.toIsoString(result.getEndTime()))

        timePoint2 = Schedule.fromIsoString("20150827T073000")
        result = manager._calculateInterval(timePoint2, memberKeys)
        self.assertEqual("20150827T070000", Schedule.toIsoString(result.getStartTime()))
        self.assertEqual("20150827T080000", Schedule.toIsoString(result.getEndTime()))

        timePoint3 = Schedule.fromIsoString("20150827T043000")
        result = manager._calculateInterval(timePoint3, memberKeys)
        self.assertEqual(False, result.isValid())

        timePoint4 = Schedule.fromIsoString("20150827T053000")
        result = manager._calculateInterval(timePoint4, memberKeys)
        self.assertEqual("20150827T050000", Schedule.toIsoString(result.getStartTime()))
        self.assertEqual("20150827T060000", Schedule.toIsoString(result.getEndTime()))

    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)))

    def test_get_group_key_without_regeneration(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).
        data1 = result[0]
        self.assertEqual(
          "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
          data1.getName().toUri())
        groupEKey1 = EncryptKey(data1.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())

        # Add new members to the database.
        dataBlob = self.certificate.wireEncode()
        memberD = Data()
        memberD.wireDecode(dataBlob)
        memberD.setName(Name("/ndn/memberD/KEY/ksk-123/ID-CERT/123"))
        manager.addMember("schedule1", memberD)

        result2 = manager.getGroupKey(timePoint1, False)
        self.assertEqual(5, len(result2))

        # Check that the new EKey is the same as the previous one.
        data2 = result2[0]
        self.assertEqual(
          "/Alice/READ/data_type/E-KEY/20150825T090000/20150825T100000",
           data2.getName().toUri())
        groupEKey2 = EncryptKey(data2.getContent())
        self.assertTrue(groupEKey1.getKeyBits().equals(groupEKey2.getKeyBits()));

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