Ejemplo 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)
Ejemplo 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)
Ejemplo n.º 3
0
    def __str__(self):
        s = "Certificate name:\n"
        s += "  " + self.getName().toUri() + "\n"
        s += "Validity:\n"

        dateFormat = "%Y%m%dT%H%M%S"
        notBeforeStr = Common.datetimeFromTimestamp(
            self.getNotBefore()).strftime(dateFormat)
        notAfterStr = Common.datetimeFromTimestamp(
            self.getNotAfter()).strftime(dateFormat)

        s += "  NotBefore: " + notBeforeStr + "\n"
        s += "  NotAfter: " + notAfterStr + "\n"
        for sd in self._subjectDescriptionList:
            s += "Subject Description:\n"
            s += "  " + str(
                sd.getOid()) + ": " + sd.getValue().toRawStr() + "\n"

        s += "Public key bits:\n"
        s += Common.base64Encode(self.getPublicKeyDer().toBytes(), True)

        if len(self._extensionList) > 0:
            s += "Extensions:\n"
            for ext in self._extensionList:
                s += "  OID: " + ext.getOid() + "\n"
                s += "  Is critical: " + ('Y'
                                          if ext.isCritical() else 'N') + "\n"

                s += "  Value: " + str(ext.getValue()).encode('hex') + "\n"

        return s
Ejemplo n.º 4
0
    def __str__(self):
        s = "Certificate name:\n"
        s += "  "+self.getName().toUri()+"\n"
        s += "Validity:\n"

        dateFormat = "%Y%m%dT%H%M%S"
        notBeforeStr = Common.datetimeFromTimestamp(self.getNotBefore()).strftime(dateFormat)
        notAfterStr = Common.datetimeFromTimestamp(self.getNotAfter()).strftime(dateFormat)

        s += "  NotBefore: " + notBeforeStr+"\n"
        s += "  NotAfter: " + notAfterStr + "\n"
        for sd in self._subjectDescriptionList:
            s += "Subject Description:\n"
            s += "  " + str(sd.getOid()) + ": " + sd.getValue().toRawStr() + "\n"

        s += "Public key bits:\n"
        s += Common.base64Encode(self.getPublicKeyDer().toBytes(), True)

        if len(self._extensionList) > 0:
            s += "Extensions:\n"
            for ext in self._extensionList:
                s += "  OID: "+ext.getOid()+"\n"
                s += "  Is critical: " + ('Y' if ext.isCritical() else 'N') + "\n"

                s += "  Value: " + str(ext.getValue()).encode('hex') + "\n"

        return s
Ejemplo n.º 5
0
    def __str__(self):
        """
        Get a string representation of this certificate.

        :return: The string representation.
        :rtype: str
        """
        result = ""
        result += "Certificate name:\n"
        result += "  " + self.getName().toUri() + "\n"
        result += "Validity:\n"
        result += "  NotBefore: " + Schedule.toIsoString(
          self.getValidityPeriod().getNotBefore()) + "\n"
        result += "  NotAfter: " + Schedule.toIsoString(
          self.getValidityPeriod().getNotAfter()) + "\n"

        # TODO: Print the extension.

        result += "Public key bits:\n"
        try:
            result += Common.base64Encode(self.getPublicKey().toBytes(), True)
        except:
            # No public key.
            pass

        result += "Signature Information:\n"
        result += "  Signature Type: "
        if isinstance(self.getSignature(), Sha256WithEcdsaSignature):
            result += "SignatureSha256WithEcdsa\n"
        elif isinstance(self.getSignature(), Sha256WithRsaSignature):
            result += "SignatureSha256WithRsa\n"
        else:
            result += "<unknown>\n"

        if KeyLocator.canGetFromSignature(self.getSignature()):
            result += "  Key Locator: "
            keyLocator = KeyLocator.getFromSignature(self.getSignature())
            if keyLocator.getType() == KeyLocatorType.KEYNAME:
                if keyLocator.getKeyName().equals(self.getKeyName()):
                    result += "Self-Signed "

                result += "Name=" + keyLocator.getKeyName().toUri() + "\n"
            else:
                result += "<no KeyLocator key name>\n"

        return result
Ejemplo n.º 6
0
    def __str__(self):
        """
        Get a string representation of this certificate.

        :return: The string representation.
        :rtype: str
        """
        result = ""
        result += "Certificate name:\n"
        result += "  " + self.getName().toUri() + "\n"
        result += "Validity:\n"
        result += "  NotBefore: " + Schedule.toIsoString(
            self.getValidityPeriod().getNotBefore()) + "\n"
        result += "  NotAfter: " + Schedule.toIsoString(
            self.getValidityPeriod().getNotAfter()) + "\n"

        # TODO: Print the extension.

        result += "Public key bits:\n"
        try:
            result += Common.base64Encode(self.getPublicKey().toBytes(), True)
        except:
            # No public key.
            pass

        result += "Signature Information:\n"
        result += "  Signature Type: "
        if type(self.getSignature()) is Sha256WithEcdsaSignature:
            result += "SignatureSha256WithEcdsa\n"
        elif type(self.getSignature()) is Sha256WithRsaSignature:
            result += "SignatureSha256WithRsa\n"
        else:
            result += "<unknown>\n"

        if KeyLocator.canGetFromSignature(self.getSignature()):
            result += "  Key Locator: "
            keyLocator = KeyLocator.getFromSignature(self.getSignature())
            if keyLocator.getType() == KeyLocatorType.KEYNAME:
                if keyLocator.getKeyName().equals(self.getKeyName()):
                    result += "Self-Signed "

                result += "Name=" + keyLocator.getKeyName().toUri() + "\n"
            else:
                result += "<no KeyLocator key name>\n"

        return result
Ejemplo n.º 7
0
    def nameTransform(self, keyName, extension):
        """
        Create a file path from keyName and the extension

        :param str keyName: The key name URI.
        :param str extension: The desired file name extension, e.g. ".pri".
        :return: The file path.
        :rtype: str
        """
        sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend())
        sha256.update(Blob(keyName, False).toBytes())
        hash = sha256.finalize()

        digest = Common.base64Encode(hash)
        digest = digest.strip()
        digest = digest.replace('/', '%')

        return os.path.join(self._keyStorePath, digest + extension)
Ejemplo n.º 8
0
    def nameTransform(self, keyName, extension):
        """
        Create a file path from keyName and the extension

        :param str keyName: The key name URI.
        :param str extension: The desired file name extension, e.g. ".pri".
        :return: The file path.
        :rtype: str
        """
        sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend())
        sha256.update(Blob(keyName, False).toBytes())
        hash = sha256.finalize()

        digest = Common.base64Encode(hash)
        digest = digest.strip()
        digest = digest.replace('/', '%')

        return os.path.join(self._keyStorePath, digest + extension)
    def saveCertificateToFile(self, data, filePath):
        """
        :param Data data: The certificate to save.
        :param str filePath: The file path, which should be writable.
        :return: True if successful.
        :rtype: bool
        """
        self._certificateFiles.add(filePath)

        try:
            encoding = data.wireEncode()
            encodedCertificate = Common.base64Encode(encoding.toBytes(), True)

            with open(filePath, 'w') as keyFile:
                keyFile.write(encodedCertificate)

            return True
        except Exception:
            return False
    def saveCertificateToFile(self, data, filePath):
        """
        :param Data data: The certificate to save.
        :param str filePath: The file path, which should be writable.
        :return: True if successful.
        :rtype: bool
        """
        self._certificateFiles.add(filePath)

        try:
            encoding = data.wireEncode()
            encodedCertificate = Common.base64Encode(encoding.toBytes(), True)

            with open(filePath, 'w') as keyFile:
                keyFile.write(encodedCertificate)

            return True
        except Exception:
            return False
Ejemplo n.º 11
0
    def _saveKey(self, keyName, key):
        """
        Save the private key using keyName into the key file directory.

        :param Name keyName: The name of the key.
        :param TpmPrivateKey key: The private key to save.
        """
        filePath = self._toFilePath(keyName)
        try:
            base64 = Common.base64Encode(key.toPkcs1().toBytes(), True)
        except Exception as ex:
            raise TpmBackEndFile.Error("Error encoding private key file: " +
                                       str(ex))

        try:
            with open(filePath, 'w') as keyFile:
                keyFile.write(base64)
        except Exception as ex:
            raise TpmBackEndFile.Error("Error writing private key file: " +
                                       str(ex))
Ejemplo n.º 12
0
    def _saveKey(self, keyName, key):
        """
        Save the private key using keyName into the key file directory.

        :param Name keyName: The name of the key.
        :param TpmPrivateKey key: The private key to save.
        """
        filePath = self._toFilePath(keyName)
        try:
            base64 = Common.base64Encode(key.toPkcs1().toBytes(), True)
        except Exception as ex:
            raise TpmBackEndFile.Error(
              "Error encoding private key file: " + str(ex))

        try:
            with open(filePath, 'w') as keyFile:
                keyFile.write(base64)
        except Exception as ex:
            raise TpmBackEndFile.Error(
              "Error writing private key file: " + str(ex))