Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
    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)
Exemplo n.º 3
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()))
Exemplo n.º 4
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()))
Exemplo n.º 5
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())
Exemplo n.º 6
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()))
Exemplo n.º 7
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())
Exemplo n.º 8
0
    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)
Exemplo n.º 10
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
Exemplo n.º 11
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