예제 #1
0
    def getPublicKey(self, keyName):
        """
        Get the public key with the keyName.

        :param Name keyName: The name of public key.
        :return: The public key.
        :rtype: PublicKey
        """
        publicKey = self._getKey(keyName, KeyClass.PUBLIC)
        if publicKey == None:
            raise SecurityException("The requested public key [" +
                                    keyName.toUri() +
                                    "] does not exist in the OSX Keychain")

        exportedKey = None

        try:
            exportedKey = c_void_p()
            res = self._security.SecItemExport(publicKey,
                                               self._kSecFormatOpenSSL, 0,
                                               None, pointer(exportedKey))
            if res != None:
                raise SecurityException(
                    "Cannot export the requested public key from the OSX Keychain"
                )

            blob = self._CFDataToBlob(exportedKey)

            return PublicKey(blob)
        finally:
            if publicKey != None:
                cf.CFRelease(publicKey)
            if exportedKey != None:
                cf.CFRelease(exportedKey)
예제 #2
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
예제 #3
0
    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
예제 #4
0
    def getPublicKey(self, keyName):
        """
        Get the public key with the specified name.

        :param Name keyName: The name of the key.
        :return: The public key.
        :rtype: PublicKey
        """
        return PublicKey(self._identityStorage.getKey(keyName))
예제 #5
0
    def createIdentityAndCertificate(self, identityName, params):
        """
        Create an identity by creating a pair of Key-Signing-Key (KSK) for this
        identity and a self-signed certificate of the KSK. If a key pair or
        certificate for the identity already exists, use it.

        :param Name identityName: The name of the identity.
        :param KeyParams params: The key parameters if a key needs to be
          generated for the identity.
        :return: The name of the default certificate of the identity.
        :rtype: Name
        """
        self._identityStorage.addIdentity(identityName)

        generateKey = True
        try:
            keyName = self._identityStorage.getDefaultKeyNameForIdentity(
                identityName)
            key = PublicKey(self._identityStorage.getKey(keyName))
            if key.getKeyType() == params.getKeyType():
                # The key exists and has the same type, so don't need to generate one.
                generateKey = False
        except SecurityException:
            pass

        if generateKey:
            keyName = self._generateKeyPair(identityName, True, params)
            self._identityStorage.setDefaultKeyNameForIdentity(keyName)

        makeCert = True
        try:
            certName = self._identityStorage.getDefaultCertificateNameForKey(
                keyName)
            # The cert exists, so don't need to make it.
            makeCert = False
        except SecurityException:
            pass

        if makeCert:
            selfCert = self.selfSign(keyName)
            self.addCertificateAsIdentityDefault(selfCert)
            certName = selfCert.getName()

        return certName
예제 #6
0
    def createIdentityAndCertificate(self, identityName, params):
        """
        Create an identity by creating a pair of Key-Signing-Key (KSK) for this
        identity and a self-signed certificate of the KSK. If a key pair or
        certificate for the identity already exists, use it.

        :param Name identityName: The name of the identity.
        :param KeyParams params: The key parameters if a key needs to be
          generated for the identity.
        :return: The name of the default certificate of the identity.
        :rtype: Name
        """
        self._identityStorage.addIdentity(identityName)
        
        generateKey = True
        try:
            keyName = self._identityStorage.getDefaultKeyNameForIdentity(
              identityName)
            key = PublicKey(self._identityStorage.getKey(keyName))
            if key.getKeyType() == params.getKeyType():
                # The key exists and has the same type, so don't need to generate one.
                generateKey = False
        except SecurityException:
            pass

        if generateKey:
            keyName = self._generateKeyPair(identityName, True, params)
            self._identityStorage.setDefaultKeyNameForIdentity(
              keyName, identityName)

        makeCert = True
        try:
            certName = self._identityStorage.getDefaultCertificateNameForKey(keyName)
            # The cert exists, so don't need to make it.
            makeCert = False
        except SecurityException:
            pass

        if makeCert:
            selfCert = self.selfSign(keyName)
            self.addCertificateAsIdentityDefault(selfCert)
            certName = selfCert.getName()

        return certName
예제 #7
0
    def setUp(self):
        cert = Certificate()

        cert._notBefore = 1388100174000
        cert._notAfter = 1388100174000

        cert.addSubjectDescription(
            CertificateSubjectDescription(TEST_OID, "TEST NAME"))
        key = PublicKey(Blob(PUBLIC_KEY))

        cert._publicKey = key
        self.toyCert = cert
예제 #8
0
    def setUp(self):
        self.toyCertNotBefore = 1388100174000
        self.toyCertNotAfter = 1388100174000
        cert = Certificate()
        cert.setName(Name("/test/KEY/ksk-1457560485494/ID-CERT/%FD%00%00%01S%80H%E1%F3"))
        cert.setNotBefore(self.toyCertNotBefore)
        cert.setNotAfter(self.toyCertNotAfter)

        cert.addSubjectDescription(CertificateSubjectDescription(TEST_OID, "TEST NAME"))
        key = PublicKey(Blob(PUBLIC_KEY))

        cert.setPublicKeyInfo(key)
        self.toyCert = cert
예제 #9
0
    def test_generate_key(self):
        for dataSet in self.keyTestData:
            key = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            publicKeyBits = key.derivePublicKey()
            publicKey = PublicKey(publicKeyBits)

            data = Blob([0x01, 0x02, 0x03, 0x04])

            # Sign and verify.
            signature = key.sign(data.toBytes(), DigestAlgorithm.SHA256)

            result = VerificationHelpers.verifySignature(
                data, signature, publicKey)
            self.assertTrue(result)

            # Check that another generated private key is different.
            key2 = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            self.assertTrue(not key.toPkcs8().equals(key2.toPkcs8()))
예제 #10
0
    def test_generate_key(self):
        for dataSet in self.keyTestData:
            key = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            publicKeyBits = key.derivePublicKey()
            publicKey = PublicKey(publicKeyBits)

            data = Blob([0x01, 0x02, 0x03, 0x04])

            # Sign and verify.
            signature = key.sign(data.toBytes(), DigestAlgorithm.SHA256)

            # TODO: Move verify into PublicKey?
            if dataSet.keyParams.getKeyType() == KeyType.ECDSA:
                cryptoPublicKey = load_der_public_key(
                  publicKeyBits.toBytes(), backend = default_backend())
                verifier = cryptoPublicKey.verifier(
                  signature.toBytes(), ec.ECDSA(hashes.SHA256()))
                verifier.update(data.toBytes())
                try:
                    verifier.verify()
                    result = True
                except InvalidSignature:
                    result = False
            elif dataSet.keyParams.getKeyType() == KeyType.RSA:
                cryptoPublicKey = load_der_public_key(
                  publicKeyBits.toBytes(), backend = default_backend())
                verifier = cryptoPublicKey.verifier(
                  signature.toBytes(), padding.PKCS1v15(), hashes.SHA256())
                verifier.update(data.toBytes())
                try:
                    verifier.verify()
                    result = True
                except InvalidSignature:
                    result = False
            else:
                # We don't expect this.
                self.fail("Unrecognized key type")

            self.assertTrue(result)

            # Check that another generated private key is different.
            key2 = TpmPrivateKey.generatePrivateKey(dataSet.keyParams)
            self.assertTrue(not key.toPkcs8().equals(key2.toPkcs8()))
예제 #11
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)
예제 #12
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