Example #1
0
    def derivePublicKey(key):
        """
        Use the macOS Keychain key to derive the public key.

        :param c_void_p key: The macOS Keychain private key.
        :return: The public key encoding Blob.
        :rtype: Blob
        """
        osx = Osx.get()
        exportedKey = None

        try:
            exportedKey = c_void_p()
            res = osx._security.SecItemExport(key, osx._kSecFormatOpenSSL, 0,
                                              None, pointer(exportedKey))
            if res != None:
                # TODO: check for errSecAuthFailed
                raise TpmBackEndOsx.Error("Failed to export the private key")

            privateKey = TpmPrivateKey()
            privateKey.loadPkcs1(TpmBackEndOsx._CFDataToBlob(exportedKey))
            return privateKey.derivePublicKey()
        finally:
            if exportedKey != None:
                cf.CFRelease(exportedKey)
    def sign(self, data, keyName, digestAlgorithm = DigestAlgorithm.SHA256):
        """
        Fetch the private key for keyName and sign the data, returning a
        signature Blob.

        :param data: Pointer the input byte buffer to sign.
        :type data: An array type with int elements
        :param Name keyName: The name of the signing key.
        :param digestAlgorithm: (optional) the digest algorithm. If omitted,
          use DigestAlgorithm.SHA256.
        :type digestAlgorithm: int from DigestAlgorithm
        :return: The signature Blob.
        :rtype: Blob
        """
        keyURI = keyName.toUri()

        if not self.doesKeyExist(keyName, KeyClass.PRIVATE):
            raise SecurityException(
              "FilePrivateKeyStorage.sign: private key doesn't exist")

        # Read the private key.
        base64Content = None
        with open(self.nameTransform(keyURI, ".pri")) as keyFile:
            base64Content = keyFile.read()
        pkcs8Der = base64.b64decode(base64Content)

        privateKey = TpmPrivateKey()
        try:
            privateKey.loadPkcs8(pkcs8Der)
            return privateKey.sign(Blob(data, False).toBytes(), digestAlgorithm)
        except Exception as ex:
            raise SecurityException("Error in sign: " + str(ex))
    def _doImportKey(self, keyName, pkcs8, password):
        """
        A protected method to import an encoded private key with name keyName in
          PKCS #8 format, possibly passwprd-encrypted.

        :param Name keyName: The name of the key to use in the TPM.
        :param pkcs8: The input byte buffer. If the password is supplied, this
          is a PKCS #8 EncryptedPrivateKeyInfo. If the password is none, this is
          an unencrypted PKCS #8 PrivateKeyInfo.
        :type pkcs8: an array which implements the buffer protocol
        :param password: The password for decrypting the private key. If the
          password is supplied, use it to decrypt the PKCS #8
          EncryptedPrivateKeyInfo. If the password is None, import an
          unencrypted PKCS #8 PrivateKeyInfo.
        :type password: an array which implements the buffer protocol
        :raises TpmBackEnd.Error: For an error importing the key.
        """
        try:
            if password != None:
                raise TpmBackEnd.Error(
                    "Private key password-encryption is not implemented")
            else:
                key = TpmPrivateKey()
                key.loadPkcs8(pkcs8)
                # Copy the Name.
                self._keys[Name(keyName)] = key
        except TpmPrivateKey.Error as ex:
            raise TpmBackEnd.Error("Cannot import private key: " + str(ex))
Example #4
0
    def _doImportKey(self, keyName, pkcs8, password):
        """
        A protected method to import an encoded private key with name keyName in
          PKCS #8 format, possibly password-encrypted.

        :param Name keyName: The name of the key to use in the TPM.
        :param pkcs8: The input byte buffer. If the password is supplied, this
          is a PKCS #8 EncryptedPrivateKeyInfo. If the password is none, this is
          an unencrypted PKCS #8 PrivateKeyInfo.
        :type pkcs8: an array which implements the buffer protocol
        :param password: The password for decrypting the private key, which
          should have characters in the range of 1 to 127. If the password is
          supplied, use it to decrypt the PKCS #8 EncryptedPrivateKeyInfo. If
          the password is None, import an unencrypted PKCS #8 PrivateKeyInfo.
        :type password: an array which implements the buffer protocol
        :raises TpmBackEnd.Error: For an error importing the key.
        """
        try:
            key = TpmPrivateKey()
            if password != None:
                key.loadEncryptedPkcs8(pkcs8, password)
            else:
                key.loadPkcs8(pkcs8)
        except TpmPrivateKey.Error as ex:
            raise TpmBackEnd.Error("Cannot import private key: " + str(ex))

        self._saveKey(keyName, key)
    def sign(self, data, keyName, digestAlgorithm=DigestAlgorithm.SHA256):
        """
        Fetch the private key for keyName and sign the data, returning a
        signature Blob.

        :param data: Pointer the input byte buffer to sign.
        :type data: An array type with int elements
        :param Name keyName: The name of the signing key.
        :param digestAlgorithm: (optional) the digest algorithm. If omitted,
          use DigestAlgorithm.SHA256.
        :type digestAlgorithm: int from DigestAlgorithm
        :return: The signature Blob.
        :rtype: Blob
        """
        keyURI = keyName.toUri()

        if not self.doesKeyExist(keyName, KeyClass.PRIVATE):
            raise SecurityException(
                "FilePrivateKeyStorage.sign: private key doesn't exist")

        # Read the private key.
        base64Content = None
        with open(self.nameTransform(keyURI, ".pri")) as keyFile:
            base64Content = keyFile.read()
        pkcs8Der = base64.b64decode(base64Content)

        privateKey = TpmPrivateKey()
        try:
            privateKey.loadPkcs8(pkcs8Der)
            return privateKey.sign(
                Blob(data, False).toBytes(), digestAlgorithm)
        except Exception as ex:
            raise SecurityException("Error in sign: " + str(ex))
Example #6
0
    def _loadKey(self, keyName):
        """
        Load the private key with name keyName from the key file directory.

        :param Name keyName: The name of the key.
        :return: The key loaded into a TpmPrivateKey.
        :rtype: TpmPrivateKey
        """
        key = TpmPrivateKey()
        base64Content = None
        try:
            with open(self._toFilePath(keyName)) as keyFile:
                base64Content = keyFile.read()
        except Exception as ex:
            raise TpmBackEndFile.Error(
              "Error reading private key file: " + str(ex))

        pkcs = base64.b64decode(base64Content)

        try:
            key.loadPkcs1(pkcs, None)
        except Exception as ex:
            raise TpmBackEndFile.Error(
              "Error decoding private key file: " + str(ex))

        return key
Example #7
0
    def _loadKey(self, keyName):
        """
        Load the private key with name keyName from the key file directory.

        :param Name keyName: The name of the key.
        :return: The key loaded into a TpmPrivateKey.
        :rtype: TpmPrivateKey
        """
        key = TpmPrivateKey()
        base64Content = None
        try:
            with open(self._toFilePath(keyName)) as keyFile:
                base64Content = keyFile.read()
        except Exception as ex:
            raise TpmBackEndFile.Error("Error reading private key file: " +
                                       str(ex))

        pkcs = base64.b64decode(base64Content)

        try:
            key.loadPkcs1(pkcs, None)
        except Exception as ex:
            raise TpmBackEndFile.Error("Error decoding private key file: " +
                                       str(ex))

        return key
Example #8
0
    def test_rsa_decryption(self):
        dataSet = self.rsaKeyTestData

        pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
        key = TpmPrivateKey()
        key.loadPkcs8(pkcs8)

        plainText = Blob([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])

        cipherTextBase64 = (
            "i2XNpZ2JbLa4JmBTdDrGmsd4/0C+p+BSCpW3MuPBNe5uChQ0eRO1dvjTnEqwSECY\n"
            +
            "38en9JZwcyb0It/TSFNXHlq+Z1ZpffnjIJxQR9HcgwvwQJh6WRH0vu38tvGkGuNv\n"
            +
            "60Rdn85hqSy1CikmXCeWXL9yCqeqcP21R94G/T3FuA+c1FtFko8KOzCwvrTXMO6n\n"
            +
            "5PNsqlLXabSGr+jz4EwOsSCgPkiDf9U6tXoSPRA2/YvqFQdaiUXIVlomESvaqqZ8\n"
            +
            "FxPs2BON0lobM8gT+xdzbRKofp+rNjNK+5uWyeOnXJwzCszh17cdJl2BH1dZwaVD\n"
            + "PmTiSdeDQXZ94U5boDQ4Aw==\n")

        cipherText = base64.b64decode(cipherTextBase64)

        decryptedText = key.decrypt(cipherText)

        self.assertTrue(decryptedText.equals(plainText))
Example #9
0
    def derivePublicKey(key):
        """
        Use the macOS Keychain key to derive the public key.

        :param c_void_p key: The macOS Keychain private key.
        :return: The public key encoding Blob.
        :rtype: Blob
        """
        osx = Osx.get()
        exportedKey = None

        try:
            exportedKey = c_void_p()
            res = osx._security.SecItemExport(
              key, osx._kSecFormatOpenSSL, 0, None, pointer(exportedKey))
            if res != None:
                # TODO: check for errSecAuthFailed
                raise TpmBackEndOsx.Error(
                  "Failed to export the private key")

            privateKey = TpmPrivateKey()
            privateKey.loadPkcs1(TpmBackEndOsx._CFDataToBlob(exportedKey))
            return privateKey.derivePublicKey()
        finally:
            if exportedKey != None:
                cf.CFRelease(exportedKey)
Example #10
0
    def test_derive_public_key(self):
        for dataSet in self.keyTestData:
            pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
            key =  TpmPrivateKey()
            key.loadPkcs8(pkcs8)

            # Derive the public key and compare.
            publicKeyBits = key.derivePublicKey()
            expected = base64.b64decode(dataSet.publicKeyEncoding)
            self.assertTrue(publicKeyBits.equals(Blob(expected)))
Example #11
0
    def test_derive_public_key(self):
        for dataSet in self.keyTestData:
            pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
            key = TpmPrivateKey()
            key.loadPkcs8(pkcs8)

            # Derive the public key and compare.
            publicKeyBits = key.derivePublicKey()
            expected = base64.b64decode(dataSet.publicKeyEncoding)
            self.assertTrue(publicKeyBits.equals(Blob(expected)))
Example #12
0
    def deriveEncryptKey(keyBits):
        """
        Derive a new encrypt key from the given decrypt key value.

        :param Blob keyBits: The key value of the decrypt key (PKCS8-encoded
          private key).
        :return: The new encrypt key (DER-encoded public key).
        :rtype: EncryptKey
        """
        privateKey = TpmPrivateKey()
        privateKey.loadPkcs8(keyBits.toBytes())
        return EncryptKey(privateKey.derivePublicKey())
Example #13
0
    def deriveEncryptKey(keyBits):
        """
        Derive a new encrypt key from the given decrypt key value.

        :param Blob keyBits: The key value of the decrypt key (PKCS8-encoded
          private key).
        :return: The new encrypt key (DER-encoded public key).
        :rtype: EncryptKey
        """
        privateKey = TpmPrivateKey()
        privateKey.loadPkcs8(keyBits.toBytes())
        return EncryptKey(privateKey.derivePublicKey())
Example #14
0
    def decrypt(keyBits, encryptedData, params):
        """
        Decrypt the encryptedData using the keyBits according the encrypt params.

        :param Blob keyBits: The key value (PKCS8-encoded private key).
        :param Blob encryptedData: The data to decrypt.
        :param EncryptParams params: This decrypts according to
          params.getAlgorithmType().
        :return: The decrypted data.
        :rtype: Blob
        """
        privateKey = TpmPrivateKey()
        privateKey.loadPkcs8(keyBits.toBytes())
        return privateKey.decrypt(
          encryptedData.toBytes(), params.getAlgorithmType())
Example #15
0
    def decrypt(keyBits, encryptedData, params):
        """
        Decrypt the encryptedData using the keyBits according the encrypt params.

        :param Blob keyBits: The key value (PKCS8-encoded private key).
        :param Blob encryptedData: The data to decrypt.
        :param EncryptParams params: This decrypts according to
          params.getAlgorithmType().
        :return: The decrypted data.
        :rtype: Blob
        """
        privateKey = TpmPrivateKey()
        privateKey.loadPkcs8(keyBits.toBytes())
        return privateKey.decrypt(encryptedData.toBytes(),
                                  params.getAlgorithmType())
    def generateKeyPair(self, keyName, params):
        """
        Generate a pair of asymmetric keys.

        :param Name keyName: The name of the key pair.
        :param KeyParams params: The parameters of the key.
        """
        if self.doesKeyExist(keyName, KeyClass.PUBLIC):
            raise SecurityException("Public key already exists")
        if self.doesKeyExist(keyName, KeyClass.PRIVATE):
            raise SecurityException("Private key already exists")

        try:
            privateKey = TpmPrivateKey.generatePrivateKey(params)
            privateKeyDer = privateKey.toPkcs8().toBytes()
            publicKeyDer = privateKey.derivePublicKey().toBytes()
        except Exception as ex:
            raise SecurityException("Error in generatePrivateKey: " + str(ex))

        keyUri = keyName.toUri()
        keyFilePathNoExtension = self.maintainMapping(keyUri)
        publicKeyFilePath = keyFilePathNoExtension + ".pub"
        privateKeyFilePath = keyFilePathNoExtension + ".pri"

        with open(publicKeyFilePath, 'w') as keyFile:
            keyFile.write(Common.base64Encode(publicKeyDer, True))
        with open(privateKeyFilePath, 'w') as keyFile:
            keyFile.write(Common.base64Encode(privateKeyDer, True))

        os.chmod(publicKeyFilePath, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        os.chmod(privateKeyFilePath, stat.S_IRUSR)
    def generateKeyPair(self, keyName, params):
        """
        Generate a pair of asymmetric keys.

        :param Name keyName: The name of the key pair.
        :param KeyParams params: The parameters of the key.
        """
        if self.doesKeyExist(keyName, KeyClass.PUBLIC):
            raise SecurityException("Public key already exists")
        if self.doesKeyExist(keyName, KeyClass.PRIVATE):
            raise SecurityException("Private key already exists")

        try:
            privateKey = TpmPrivateKey.generatePrivateKey(params)
            privateKeyDer = privateKey.toPkcs8().toBytes()
            publicKeyDer = privateKey.derivePublicKey().toBytes()
        except Exception as ex:
            raise SecurityException("Error in generatePrivateKey: " + str(ex))

        keyUri = keyName.toUri()
        keyFilePathNoExtension = self.maintainMapping(keyUri)
        publicKeyFilePath = keyFilePathNoExtension + ".pub"
        privateKeyFilePath = keyFilePathNoExtension + ".pri"

        with open(publicKeyFilePath, 'w') as keyFile:
            keyFile.write(Common.base64Encode(publicKeyDer, True))
        with open(privateKeyFilePath, 'w') as keyFile:
            keyFile.write(Common.base64Encode(privateKeyDer, True))

        os.chmod(publicKeyFilePath,  stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
        os.chmod(privateKeyFilePath, stat.S_IRUSR)
    def setPrivateKeyForKeyName(self, keyName, keyType, privateKeyDer):
        """
        Set the private key for the keyName.

        :param Name keyName: The key name.
        :param keyType: The KeyType, such as KeyType.RSA.
        :type keyType: an int from KeyType
        :param privateKeyDer: The private key DER byte array.
        :type privateKeyDer: str, or an array type with int elements which is
          converted to str
        """
        privateKey = TpmPrivateKey()
        try:
            privateKey.loadPkcs8(privateKeyDer, keyType)
        except Exception as ex:
            raise SecurityException("Error in loadPkcs8: " + str(ex))
        self._privateKeyStore[keyName.toUri()] = privateKey
    def setPrivateKeyForKeyName(self, keyName, keyType, privateKeyDer):
        """
        Set the private key for the keyName.

        :param Name keyName: The key name.
        :param keyType: The KeyType, such as KeyType.RSA.
        :type keyType: an int from KeyType
        :param privateKeyDer: The private key DER byte array.
        :type privateKeyDer: str, or an array type with int elements which is
          converted to str
        """
        privateKey = TpmPrivateKey()
        try:
            privateKey.loadPkcs8(privateKeyDer, keyType)
        except Exception as ex:
            raise SecurityException("Error in loadPkcs8: " + str(ex))
        self._privateKeyStore[keyName.toUri()] = privateKey
Example #20
0
    def test_save_load(self):
        for dataSet in self.keyTestData:
            # Load the key in PKCS #1 format.
            pkcs1 = base64.b64decode(dataSet.privateKeyPkcs1)
            key1 = TpmPrivateKey()
            key1.loadPkcs1(pkcs1)

            # Save the key in PKCS #1 format.
            savedPkcs1Key = key1.toPkcs1()
            self.assertTrue(savedPkcs1Key.equals(Blob(pkcs1)))

            pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
            key8 = TpmPrivateKey()
            key8.loadPkcs8(pkcs8)

            # Save the key in PKCS #8 format.
            savedPkcs8Key = key8.toPkcs8()
            self.assertTrue(savedPkcs8Key.equals(Blob(pkcs8)))
Example #21
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()))
Example #22
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()))
    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()))
Example #24
0
    def generateKey(params):
        """
        Generate a new random decrypt key for RSA based on the given params.

        :param RsaKeyParams params: The key params with the key size (in bits).
        :return: The new decrypt key (PKCS8-encoded private key).
        :rtype: DecryptKey
        """
        privateKey = TpmPrivateKey.generatePrivateKey(params)
        return DecryptKey(privateKey.toPkcs8())
Example #25
0
    def generateKey(params):
        """
        Generate a new random decrypt key for RSA based on the given params.

        :param RsaKeyParams params: The key params with the key size (in bits).
        :return: The new decrypt key (PKCS8-encoded private key).
        :rtype: DecryptKey
        """
        privateKey = TpmPrivateKey.generatePrivateKey(params)
        return DecryptKey(privateKey.toPkcs8())
Example #26
0
    def test_rsa_decryption(self):
        dataSet = self.rsaKeyTestData

        pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
        key =  TpmPrivateKey()
        key.loadPkcs8(pkcs8)

        plainText = Blob([0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07])

        cipherTextBase64 = (
          "i2XNpZ2JbLa4JmBTdDrGmsd4/0C+p+BSCpW3MuPBNe5uChQ0eRO1dvjTnEqwSECY\n" +
          "38en9JZwcyb0It/TSFNXHlq+Z1ZpffnjIJxQR9HcgwvwQJh6WRH0vu38tvGkGuNv\n" +
          "60Rdn85hqSy1CikmXCeWXL9yCqeqcP21R94G/T3FuA+c1FtFko8KOzCwvrTXMO6n\n" +
          "5PNsqlLXabSGr+jz4EwOsSCgPkiDf9U6tXoSPRA2/YvqFQdaiUXIVlomESvaqqZ8\n" +
          "FxPs2BON0lobM8gT+xdzbRKofp+rNjNK+5uWyeOnXJwzCszh17cdJl2BH1dZwaVD\n" +
          "PmTiSdeDQXZ94U5boDQ4Aw==\n")

        cipherText = base64.b64decode(cipherTextBase64)

        decryptedText = key.decrypt(cipherText)

        self.assertTrue(decryptedText.equals(plainText))
    def generateKeyPair(self, keyName, params):
        """
        Generate a pair of asymmetric keys.

        :param Name keyName: The name of the key pair.
        :param KeyParams params: The parameters of the key.
        """
        privateKey = None
        try:
            privateKey = TpmPrivateKey.generatePrivateKey(params)
        except Exception as ex:
            raise SecurityException("Error in generatePrivateKey: " + str(ex))

        publicKeyDer = None
        try:
            publicKeyDer = privateKey.derivePublicKey()
        except Exception as ex:
            raise SecurityException("Error in derivePublicKey: " + str(ex))

        self._privateKeyStore[keyName.toUri()] = privateKey
        self._publicKeyStore[keyName.toUri()] = PublicKey(publicKeyDer)
    def generateKeyPair(self, keyName, params):
        """
        Generate a pair of asymmetric keys.

        :param Name keyName: The name of the key pair.
        :param KeyParams params: The parameters of the key.
        """
        privateKey = None
        try:
            privateKey = TpmPrivateKey.generatePrivateKey(params)
        except Exception as ex:
            raise SecurityException("Error in generatePrivateKey: " + str(ex))

        publicKeyDer = None
        try:
            publicKeyDer = privateKey.derivePublicKey()
        except Exception as ex:
            raise SecurityException("Error in derivePublicKey: " + str(ex))

        self._privateKeyStore[keyName.toUri()] = privateKey
        self._publicKeyStore[keyName.toUri()] = PublicKey(publicKeyDer)
Example #29
0
    def _doCreateKey(self, identityName, params):
        """
        Create a key for identityName according to params. The created key is
        named as: /<identityName>/[keyId]/KEY . The key name is set in the
        returned TpmKeyHandle.

        :param Name identityName: The name if the identity.
        :param KeyParams params: The KeyParams for creating the key.
        :return: The handle of the created key.
        :rtype: TpmKeyHandle
        :raises TpmBackEnd.Error: If the key cannot be created.
        """
        try:
            key = TpmPrivateKey.generatePrivateKey(params)
        except Exception as ex:
            raise TpmBackEndFile.Error(
              "Error in TpmPrivateKey.generatePrivateKey: " + str(ex))
        keyHandle = TpmKeyHandleMemory(key)

        TpmBackEnd.setKeyName(keyHandle, identityName, params)

        self._saveKey(keyHandle.getKeyName(), key)
        return keyHandle
Example #30
0
    def _doCreateKey(self, identityName, params):
        """
        Create a key for identityName according to params. The created key is
        named as: /<identityName>/[keyId]/KEY . The key name is set in the
        returned TpmKeyHandle.

        :param Name identityName: The name if the identity.
        :param KeyParams params: The KeyParams for creating the key.
        :return: The handle of the created key.
        :rtype: TpmKeyHandle
        :raises TpmBackEnd.Error: If the key cannot be created.
        """
        try:
            key = TpmPrivateKey.generatePrivateKey(params)
        except Exception as ex:
            raise TpmBackEndFile.Error(
                "Error in TpmPrivateKey.generatePrivateKey: " + str(ex))
        keyHandle = TpmKeyHandleMemory(key)

        TpmBackEnd.setKeyName(keyHandle, identityName, params)

        self._saveKey(keyHandle.getKeyName(), key)
        return keyHandle
Example #31
0
    def test_import_export(self):
        privateKeyPkcs1Base64 = (
          "MIIEpAIBAAKCAQEAw0WM1/WhAxyLtEqsiAJgWDZWuzkYpeYVdeeZcqRZzzfRgBQT\n" +
          "sNozS5t4HnwTZhwwXbH7k3QN0kRTV826Xobws3iigohnM9yTK+KKiayPhIAm/+5H\n" +
          "GT6SgFJhYhqo1/upWdueojil6RP4/AgavHhopxlAVbk6G9VdVnlQcQ5Zv0OcGi73\n" +
          "c+EnYD/YgURYGSngUi/Ynsh779p2U69/te9gZwIL5PuE9BiO6I39cL9z7EK1SfZh\n" +
          "OWvDe/qH7YhD/BHwcWit8FjRww1glwRVTJsA9rH58ynaAix0tcR/nBMRLUX+e3rU\n" +
          "RHg6UbSjJbdb9qmKM1fTGHKUzL/5pMG6uBU0ywIDAQABAoIBADQkckOIl4IZMUTn\n" +
          "W8LFv6xOdkJwMKC8G6bsPRFbyY+HvC2TLt7epSvfS+f4AcYWaOPcDu2E49vt2sNr\n" +
          "cASly8hgwiRRAB3dHH9vcsboiTo8bi2RFvMqvjv9w3tK2yMxVDtmZamzrrnaV3YV\n" +
          "Q+5nyKo2F/PMDjQ4eUAKDOzjhBuKHsZBTFnA1MFNI+UKj5X4Yp64DFmKlxTX/U2b\n" +
          "wzVywo5hzx2Uhw51jmoLls4YUvMJXD0wW5ZtYRuPogXvXb/of9ef/20/wU11WFKg\n" +
          "Xb4gfR8zUXaXS1sXcnVm3+24vIs9dApUwykuoyjOqxWqcHRec2QT2FxVGkFEraze\n" +
          "CPa4rMECgYEA5Y8CywomIcTgerFGFCeMHJr8nQGqY2V/owFb3k9maczPnC9p4a9R\n" +
          "c5szLxA9FMYFxurQZMBWSEG2JS1HR2mnjigx8UKjYML/A+rvvjZOMe4M6Sy2ggh4\n" +
          "SkLZKpWTzjTe07ByM/j5v/SjNZhWAG7sw4/LmPGRQkwJv+KZhGojuOkCgYEA2cOF\n" +
          "T6cJRv6kvzTz9S0COZOVm+euJh/BXp7oAsAmbNfOpckPMzqHXy8/wpdKl6AAcB57\n" +
          "OuztlNfV1D7qvbz7JuRlYwQ0cEfBgbZPcz1p18HHDXhwn57ZPb8G33Yh9Omg0HNA\n" +
          "Imb4LsVuSqxA6NwSj7cpRekgTedrhLFPJ+Ydb5MCgYEAsM3Q7OjILcIg0t6uht9e\n" +
          "vrlwTsz1mtCV2co2I6crzdj9HeI2vqf1KAElDt6G7PUHhglcr/yjd8uEqmWRPKNX\n" +
          "ddnnfVZB10jYeP/93pac6z/Zmc3iU4yKeUe7U10ZFf0KkiiYDQd59CpLef/2XScS\n" +
          "HB0oRofnxRQjfjLc4muNT+ECgYEAlcDk06MOOTly+F8lCc1bA1dgAmgwFd2usDBd\n" +
          "Y07a3e0HGnGLN3Kfl7C5i0tZq64HvxLnMd2vgLVxQlXGPpdQrC1TH+XLXg+qnlZO\n" +
          "ivSH7i0/gx75bHvj75eH1XK65V8pDVDEoSPottllAIs21CxLw3N1ObOZWJm2EfmR\n" +
          "cuHICmsCgYAtFJ1idqMoHxES3mlRpf2JxyQudP3SCm2WpGmqVzhRYInqeatY5sUd\n" +
          "lPLHm/p77RT7EyxQHTlwn8FJPuM/4ZH1rQd/vB+Y8qAtYJCexDMsbvLW+Js+VOvk\n" +
          "jweEC0nrcL31j9mF0vz5E6tfRu4hhJ6L4yfWs0gSejskeVB/w8QY4g==\n")

        for tpm in self.backEndList:
            if tpm is self.backEndOsx:
                # TODO: Implement TpmBackEndOsx import/export.
                continue

            keyName = Name("/Test/KeyName/KEY/1")
            tpm.deleteKey(keyName)
            self.assertEquals(False, tpm.hasKey(keyName))

            privateKey = TpmPrivateKey()
            privateKeyPkcs1Encoding = Blob(base64.b64decode(privateKeyPkcs1Base64))
            privateKey.loadPkcs1(privateKeyPkcs1Encoding.buf())

            password = Blob("password").toBytes()
            encryptedPkcs8 = privateKey.toEncryptedPkcs8(password)

            tpm.importKey(keyName, encryptedPkcs8.buf(), password)
            self.assertEquals(True, tpm.hasKey(keyName))
            try:
                # Can't import the same keyName again.
                tpm.importKey(keyName, encryptedPkcs8.buf(), password)
                self.fail("Did not throw the expected exception")
            except TpmBackEnd.Error:
                pass
            else:
                self.fail("Did not throw the expected exception")

            exportedKey = tpm.exportKey(keyName, password)
            self.assertEquals(True, tpm.hasKey(keyName))

            privateKey2 = TpmPrivateKey()
            privateKey2.loadEncryptedPkcs8(exportedKey.buf(), password)
            privateKey2Pkcs1Encoding = privateKey2.toPkcs1()
            self.assertTrue(privateKeyPkcs1Encoding.equals(privateKey2Pkcs1Encoding))

            tpm.deleteKey(keyName)
            self.assertEquals(False, tpm.hasKey(keyName))
            try:
                tpm.exportKey(keyName, password)
                self.fail("Did not throw the expected exception")
            except TpmBackEnd.Error:
                pass
            else:
                self.fail("Did not throw the expected exception")
Example #32
0
    def test_import_export(self):
        privateKeyPkcs1Base64 = (
          "MIIEpAIBAAKCAQEAw0WM1/WhAxyLtEqsiAJgWDZWuzkYpeYVdeeZcqRZzzfRgBQT\n" +
          "sNozS5t4HnwTZhwwXbH7k3QN0kRTV826Xobws3iigohnM9yTK+KKiayPhIAm/+5H\n" +
          "GT6SgFJhYhqo1/upWdueojil6RP4/AgavHhopxlAVbk6G9VdVnlQcQ5Zv0OcGi73\n" +
          "c+EnYD/YgURYGSngUi/Ynsh779p2U69/te9gZwIL5PuE9BiO6I39cL9z7EK1SfZh\n" +
          "OWvDe/qH7YhD/BHwcWit8FjRww1glwRVTJsA9rH58ynaAix0tcR/nBMRLUX+e3rU\n" +
          "RHg6UbSjJbdb9qmKM1fTGHKUzL/5pMG6uBU0ywIDAQABAoIBADQkckOIl4IZMUTn\n" +
          "W8LFv6xOdkJwMKC8G6bsPRFbyY+HvC2TLt7epSvfS+f4AcYWaOPcDu2E49vt2sNr\n" +
          "cASly8hgwiRRAB3dHH9vcsboiTo8bi2RFvMqvjv9w3tK2yMxVDtmZamzrrnaV3YV\n" +
          "Q+5nyKo2F/PMDjQ4eUAKDOzjhBuKHsZBTFnA1MFNI+UKj5X4Yp64DFmKlxTX/U2b\n" +
          "wzVywo5hzx2Uhw51jmoLls4YUvMJXD0wW5ZtYRuPogXvXb/of9ef/20/wU11WFKg\n" +
          "Xb4gfR8zUXaXS1sXcnVm3+24vIs9dApUwykuoyjOqxWqcHRec2QT2FxVGkFEraze\n" +
          "CPa4rMECgYEA5Y8CywomIcTgerFGFCeMHJr8nQGqY2V/owFb3k9maczPnC9p4a9R\n" +
          "c5szLxA9FMYFxurQZMBWSEG2JS1HR2mnjigx8UKjYML/A+rvvjZOMe4M6Sy2ggh4\n" +
          "SkLZKpWTzjTe07ByM/j5v/SjNZhWAG7sw4/LmPGRQkwJv+KZhGojuOkCgYEA2cOF\n" +
          "T6cJRv6kvzTz9S0COZOVm+euJh/BXp7oAsAmbNfOpckPMzqHXy8/wpdKl6AAcB57\n" +
          "OuztlNfV1D7qvbz7JuRlYwQ0cEfBgbZPcz1p18HHDXhwn57ZPb8G33Yh9Omg0HNA\n" +
          "Imb4LsVuSqxA6NwSj7cpRekgTedrhLFPJ+Ydb5MCgYEAsM3Q7OjILcIg0t6uht9e\n" +
          "vrlwTsz1mtCV2co2I6crzdj9HeI2vqf1KAElDt6G7PUHhglcr/yjd8uEqmWRPKNX\n" +
          "ddnnfVZB10jYeP/93pac6z/Zmc3iU4yKeUe7U10ZFf0KkiiYDQd59CpLef/2XScS\n" +
          "HB0oRofnxRQjfjLc4muNT+ECgYEAlcDk06MOOTly+F8lCc1bA1dgAmgwFd2usDBd\n" +
          "Y07a3e0HGnGLN3Kfl7C5i0tZq64HvxLnMd2vgLVxQlXGPpdQrC1TH+XLXg+qnlZO\n" +
          "ivSH7i0/gx75bHvj75eH1XK65V8pDVDEoSPottllAIs21CxLw3N1ObOZWJm2EfmR\n" +
          "cuHICmsCgYAtFJ1idqMoHxES3mlRpf2JxyQudP3SCm2WpGmqVzhRYInqeatY5sUd\n" +
          "lPLHm/p77RT7EyxQHTlwn8FJPuM/4ZH1rQd/vB+Y8qAtYJCexDMsbvLW+Js+VOvk\n" +
          "jweEC0nrcL31j9mF0vz5E6tfRu4hhJ6L4yfWs0gSejskeVB/w8QY4g==\n")

        for tpm in self.backEndList:
            if tpm is self.backEndOsx:
                # TODO: Implement TpmBackEndOsx import/export.
                continue

            keyName = Name("/Test/KeyName/KEY/1")
            tpm.deleteKey(keyName)
            self.assertEqual(False, tpm.hasKey(keyName))

            privateKey = TpmPrivateKey()
            privateKeyPkcs1Encoding = Blob(base64.b64decode(privateKeyPkcs1Base64))
            privateKey.loadPkcs1(privateKeyPkcs1Encoding.buf())

            password = Blob("password").toBytes()
            encryptedPkcs8 = privateKey.toEncryptedPkcs8(password)

            tpm.importKey(keyName, encryptedPkcs8.buf(), password)
            self.assertEqual(True, tpm.hasKey(keyName))
            try:
                # Can't import the same keyName again.
                tpm.importKey(keyName, encryptedPkcs8.buf(), password)
                self.fail("Did not throw the expected exception")
            except TpmBackEnd.Error:
                pass
            else:
                self.fail("Did not throw the expected exception")

            exportedKey = tpm.exportKey(keyName, password)
            self.assertEqual(True, tpm.hasKey(keyName))

            privateKey2 = TpmPrivateKey()
            privateKey2.loadEncryptedPkcs8(exportedKey.buf(), password)
            privateKey2Pkcs1Encoding = privateKey2.toPkcs1()
            self.assertTrue(privateKeyPkcs1Encoding.equals(privateKey2Pkcs1Encoding))

            tpm.deleteKey(keyName)
            self.assertEqual(False, tpm.hasKey(keyName))
            try:
                tpm.exportKey(keyName, password)
                self.fail("Did not throw the expected exception")
            except TpmBackEnd.Error:
                pass
            else:
                self.fail("Did not throw the expected exception")
Example #33
0
    def test_save_load(self):
        for dataSet in self.keyTestData:
            # Load the key in PKCS #1 format.
            pkcs1 = base64.b64decode(dataSet.privateKeyPkcs1)
            key1 =  TpmPrivateKey()
            key1.loadPkcs1(pkcs1)

            # Save the key in PKCS #1 format.
            savedPkcs1Key = key1.toPkcs1()
            self.assertTrue(savedPkcs1Key.equals(Blob(pkcs1)))

            # Load the key in unencrypted PKCS #8 format.
            pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
            key8 =  TpmPrivateKey()
            key8.loadPkcs8(pkcs8)

            # Save the key in unencrypted PKCS #8 format.
            savedPkcs8Key = key8.toPkcs8()
            self.assertTrue(savedPkcs8Key.equals(Blob(pkcs8)))

            password = Blob("password").toBytes()

            # Load the key in encrypted PKCS #8 format.
            encryptedPkcs8 = base64.b64decode(dataSet.privateKeyPkcs8)
            encryptedKey8 =  TpmPrivateKey()
            encryptedKey8.loadEncryptedPkcs8(encryptedPkcs8, password)

            # Save the key in encrypted PKCS #8 format and resave as unencrypted.
            savedEncryptedPkcs8Key = encryptedKey8.toEncryptedPkcs8(password)
            key8 =  TpmPrivateKey()
            key8.loadEncryptedPkcs8(savedEncryptedPkcs8Key, password)
            resavedPkcs8Key = key8.toPkcs8()
            self.assertTrue(resavedPkcs8Key.equals(Blob(pkcs8)))
Example #34
0
    def test_save_load(self):
        for dataSet in self.keyTestData:
            # Load the key in PKCS #1 format.
            pkcs1 = base64.b64decode(dataSet.privateKeyPkcs1)
            key1 = TpmPrivateKey()
            key1.loadPkcs1(pkcs1)

            # Save the key in PKCS #1 format.
            savedPkcs1Key = key1.toPkcs1()
            self.assertTrue(savedPkcs1Key.equals(Blob(pkcs1)))

            # Load the key in unencrypted PKCS #8 format.
            pkcs8 = base64.b64decode(dataSet.privateKeyPkcs8Unencrypted)
            key8 = TpmPrivateKey()
            key8.loadPkcs8(pkcs8)

            # Save the key in unencrypted PKCS #8 format.
            savedPkcs8Key = key8.toPkcs8()
            self.assertTrue(savedPkcs8Key.equals(Blob(pkcs8)))

            password = Blob("password").toBytes()

            # Load the key in encrypted PKCS #8 format.
            encryptedPkcs8 = base64.b64decode(dataSet.privateKeyPkcs8)
            encryptedKey8 = TpmPrivateKey()
            encryptedKey8.loadEncryptedPkcs8(encryptedPkcs8, password)

            # Save the key in encrypted PKCS #8 format and resave as unencrypted.
            savedEncryptedPkcs8Key = encryptedKey8.toEncryptedPkcs8(password)
            key8 = TpmPrivateKey()
            key8.loadEncryptedPkcs8(savedEncryptedPkcs8Key, password)
            resavedPkcs8Key = key8.toPkcs8()
            self.assertTrue(resavedPkcs8Key.equals(Blob(pkcs8)))