def test_deserialize_key(self):
     with open(self.key_file_path, "rb") as template_key_file:
         key = ssl_serializer.deserialize_key(template_key_file.read())
     self.assertEqual(
         self.template_key.private_bytes(Encoding.PEM,
                                         PrivateFormat.TraditionalOpenSSL,
                                         NoEncryption()),
         key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL,
                           NoEncryption()))
Esempio n. 2
0
 def test_store_key(self):
     key_name = "ref_key"
     key: ec.EllipticCurvePrivateKeyWithSerialization = ec.generate_private_key(
         ec.SECP384R1(), backends.default_backend()
     )
     self.file_path = os.path.join(self.ssl_folder_path, ssl_certificate_factory.KEY_FILE_FORMAT.format(key_name))
     ssl_certificate_factory.store_key(key, self.ssl_folder_path, key_name, self._stream_factory)
     ref_key = serialization.load_pem_private_key(self.stream_mock.data, None, backends.default_backend())
     self.assertEqual(
         key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()),
         ref_key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption())
     )
Esempio n. 3
0
 def test_fetch_key(self):
     key_name = "temp_key_file"
     key_file = NamedTemporaryFile()
     key = ssl_certificate_factory.generate_key()
     self.file_path = os.path.join(self.ssl_folder_path, ssl_certificate_factory.KEY_FILE_FORMAT.format(key_name))
     ssl_certificate_factory.store_key(key, self.ssl_folder_path, key_name, self._stream_factory)
     key_file.write(self.stream_mock.data)
     key_file.seek(0)
     ref_key = ssl_certificate_factory.fetch_key(url_helper.url_join("file:", key_file.name))
     self.assertEqual(
         key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()),
         ref_key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption())
     )
Esempio n. 4
0
    def to_cose_key(
        k: Union[Ed448PrivateKey, Ed448PublicKey, Ed25519PrivateKey,
                 Ed25519PublicKey, X448PrivateKey, X448PublicKey,
                 X25519PrivateKey, X25519PublicKey, ]
    ) -> Dict[int, Any]:
        cose_key: Dict[int, Any] = {}

        cose_key[1] = COSE_KEY_TYPES["OKP"]
        cose_key[-1] = 6  # Ed25519
        if isinstance(k, (Ed25519PublicKey, Ed25519PrivateKey)):
            cose_key[-1] = 6  # Ed25519
            if isinstance(k, Ed25519PublicKey):
                cose_key[-2] = k.public_bytes(Encoding.Raw, PublicFormat.Raw)
            else:
                cose_key[-2] = k.public_key().public_bytes(
                    Encoding.Raw, PublicFormat.Raw)
                cose_key[-4] = k.private_bytes(Encoding.Raw, PrivateFormat.Raw,
                                               NoEncryption())
        elif isinstance(k, (Ed448PublicKey, Ed448PrivateKey)):
            cose_key[-1] = 7  # Ed448
            if isinstance(k, Ed448PublicKey):
                cose_key[-2] = k.public_bytes(Encoding.Raw, PublicFormat.Raw)
            else:
                cose_key[-2] = k.public_key().public_bytes(
                    Encoding.Raw, PublicFormat.Raw)
                cose_key[-4] = k.private_bytes(Encoding.Raw, PrivateFormat.Raw,
                                               NoEncryption())
        elif isinstance(k, (X25519PublicKey, X25519PrivateKey)):
            cose_key[-1] = 4  # X25519
            if isinstance(k, X25519PublicKey):
                cose_key[-2] = k.public_bytes(Encoding.Raw, PublicFormat.Raw)
            else:
                cose_key[-2] = k.public_key().public_bytes(
                    Encoding.Raw, PublicFormat.Raw)
                cose_key[-4] = k.private_bytes(Encoding.Raw, PrivateFormat.Raw,
                                               NoEncryption())
        elif isinstance(k, (X448PublicKey, X448PrivateKey)):
            cose_key[-1] = 5  # X448
            if isinstance(k, X448PublicKey):
                cose_key[-2] = k.public_bytes(Encoding.Raw, PublicFormat.Raw)
            else:
                cose_key[-2] = k.public_key().public_bytes(
                    Encoding.Raw, PublicFormat.Raw)
                cose_key[-4] = k.private_bytes(Encoding.Raw, PrivateFormat.Raw,
                                               NoEncryption())
        else:
            raise ValueError("Unsupported or unknown key for OKP.")
        return cose_key
Esempio n. 5
0
def generate_keys():
    folder = os.path.dirname(__file__)

    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend(),
    )
    with open(os.path.join(folder, 'localhost.key'), "wb") as f:
        f.write(
            key.private_bytes(
                encoding=Encoding.PEM,
                format=PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=NoEncryption(),
            ))

    subject = issuer = Name([
        NameAttribute(NameOID.COUNTRY_NAME, "IE"),
        NameAttribute(NameOID.ORGANIZATION_NAME, "Scrapy"),
        NameAttribute(NameOID.COMMON_NAME, "localhost"),
    ])
    cert = (CertificateBuilder().subject_name(subject).issuer_name(
        issuer).public_key(key.public_key()).serial_number(
            random_serial_number()).not_valid_before(
                datetime.utcnow()).not_valid_after(
                    datetime.utcnow() + timedelta(days=10)).add_extension(
                        SubjectAlternativeName([DNSName("localhost")]),
                        critical=False,
                    ).sign(key, SHA256(), default_backend()))
    with open(os.path.join(folder, 'localhost.crt'), "wb") as f:
        f.write(cert.public_bytes(Encoding.PEM))
Esempio n. 6
0
def get_prv_key_from_safe_bag(id_name):
    """
    Export the safebag with password 1234 using ndnsec-export command line tool.
    The function then parse the exported safe bag and return the private key bytes.

    :param id_name: the NDN identity name
    """
    p = subprocess.run(['ndnsec-export', id_name, '-P', '1234'],
                       stdout=subprocess.PIPE)
    wire = base64.b64decode(p.stdout)
    logging.debug('result from ndnsec-export')
    logging.debug(wire)
    wire = parse_and_check_tl(wire, SecurityV2TypeNumber.SAFE_BAG)
    bag = SafeBag.parse(wire)
    # Don't use unwrap because the key returned is still in DER format
    #key = unwrap(bytes(bag.encrypted_key_bag), '1234')[1]
    privateKey = serialization.load_der_private_key(bytes(
        bag.encrypted_key_bag),
                                                    password=b'1234',
                                                    backend=default_backend())
    ecc_key = ECC.import_key(
        privateKey.private_bytes(Encoding.DER, PrivateFormat.PKCS8,
                                 NoEncryption()))
    logging.debug("pub key: ")
    logging.debug(ecc_key.pointQ.xy)
    logging.debug("prv key: ")
    logging.debug(ecc_key.d)
    cert_prv_key = ecc_key.d.to_bytes()
    logging.info("Private KEY: ")
    logging.info(cert_prv_key)
    return cert_prv_key
Esempio n. 7
0
def generate_key():
    key = ec.generate_private_key(ec.SECP256R1(), default_backend())
    key_pem = key.private_bytes(
        encoding=Encoding.PEM,
        format=PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=NoEncryption())
    return crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
    def generate_private_key(self):
        """ Generate a private key for ECDSA and RSA algorithm clients """
        for client in self:
            algorithm_prefix = client.jwt_algorithm[:2]

            if algorithm_prefix == 'ES':
                key = ec.generate_private_key(
                    curve=ec.SECT283R1,
                    backend=default_backend(),
                )
            elif algorithm_prefix in ('RS', 'PS'):
                key = rsa.generate_private_key(
                    public_exponent=65537,
                    key_size=2048,
                    backend=default_backend(),
                )
            else:
                raise exceptions.UserError(
                    _('You can only generate private keys for asymetric '
                      'algorithms!'))
            client.jwt_private_key = key.private_bytes(
                encoding=Encoding.PEM,
                format=PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=NoEncryption(),
            )
Esempio n. 9
0
def generate_key_pair(size=2048, public_exponent=65537, as_string=True):
    """
    Generate a public/private key pair.

    :param size: Optional. Describes how many bits long the key should be, larger keys provide more security,
        currently 1024 and below are considered breakable, and 2048 or 4096 are reasonable default
        key sizes for new keys. Defaults to 2048.
    :param public_exponent: Optional. Indicates what one mathematical property of the key generation will be.
        65537 is the default and should almost always be used.
    :param as_string: Optional. If True, return tuple of strings. If false, return tuple of RSA key objects.
        Defaults to True.
    :return: (PrivateKey<string>, PublicKey<string>)
    :return: (
        `RSAPrivateKey <https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey>`_,
        `RSAPublicKey <https://cryptography.io/en/latest/hazmat/primitives/asymmetric/rsa/#cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey>`_)
    """
    private = rsa.generate_private_key(public_exponent=public_exponent,
                                       key_size=size,
                                       backend=default_backend())
    public = private.public_key()

    if not as_string:
        return private, public

    pem_private = private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8,
                                        NoEncryption()).decode(ENCODING)
    pem_public = public.public_bytes(
        Encoding.PEM, PublicFormat.SubjectPublicKeyInfo).decode(ENCODING)
    return pem_private, pem_public
Esempio n. 10
0
def copy_cert(cert, data, key_path, csr_path):
    key_dest = os.path.join(args.dest, data['key_filename'])
    csr_dest = os.path.join(args.dest, data['csr_filename'])
    pub_dest = os.path.join(args.dest, data['pub_filename'])
    key_der_dest = os.path.join(args.dest, data['key_der_filename'])
    pub_der_dest = os.path.join(args.dest, data['pub_der_filename'])

    shutil.copy(key_path, key_dest)
    shutil.copy(csr_path, csr_dest)
    with open(pub_dest, 'w') as stream:
        stream.write(cert.pub)

    with open(key_dest, 'rb') as stream:
        priv_key = stream.read()
    priv_key = load_pem_private_key(priv_key, None, default_backend())
    key_der = priv_key.private_bytes(encoding=Encoding.DER,
                                     format=PrivateFormat.PKCS8,
                                     encryption_algorithm=NoEncryption())
    with open(key_der_dest, 'wb') as stream:
        stream.write(key_der)
    with open(pub_der_dest, 'wb') as stream:
        stream.write(cert.dump_certificate(Encoding.DER))

    data['crl'] = cert.ca.crl_url
    data['subject'] = cert.distinguishedName()
    data['parsed_cert'] = cert

    update_cert_data(cert, data)
Esempio n. 11
0
def bootstrap():
    global trust_anchor, signer
    import_safebag("sec/server.safebag", "1234")
    import_cert("sec/server.ndncert")

    with open("sec/server.safebag", "r") as safebag:
        wire = safebag.read()
        wire = base64.b64decode(wire)
        wire = parse_and_check_tl(wire, SecurityV2TypeNumber.SAFE_BAG)
        bag = SafeBag.parse(wire)
        testbed_signed = CertificateV2Value.parse(bag.certificate_v2)
        server_key_name = Name.to_str(testbed_signed.name[:-2])
        privateKey = serialization.load_der_private_key(
            bytes(bag.encrypted_key_bag),
            password=b'1234',
            backend=default_backend())
        server_prv_key = privateKey.private_bytes(Encoding.DER,
                                                  PrivateFormat.PKCS8,
                                                  NoEncryption())
        signer = Sha256WithEcdsaSigner(server_key_name, server_prv_key)

    with open("sec/testbed.anchor", "r") as ndncert:
        wire = ndncert.read()
        wire = base64.b64decode(wire)
        trust_anchor = parse_certificate(wire)
Esempio n. 12
0
    def to_pem(self) -> bytes:
        "return private key's serialized (PEM) form"

        pem_data = self.pk.private_bytes(
            encoding=Encoding.PEM, format=PrivateFormat.PKCS8, encryption_algorithm=NoEncryption()
        )
        return pem_data
Esempio n. 13
0
 def private_key_pem(self):
     """`Blob`: The PEM-encoded private key for this CA. Use this to sign
     other certificates from this CA."""
     return Blob(
         self._private_key.private_bytes(Encoding.PEM,
                                         PrivateFormat.TraditionalOpenSSL,
                                         NoEncryption()))
Esempio n. 14
0
    def secret_as_pem(self):
        """
        Write out the private key as a PEM format

        :return: Pem Encoded private key
        """
        return self._private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())
Esempio n. 15
0
 def dumps_private_key(self):
     obj = self.dumps_public_key(self.private_key.public_key())
     d_bytes = self.private_key.private_bytes(Encoding.Raw,
                                              PrivateFormat.Raw,
                                              NoEncryption())
     obj['d'] = to_unicode(urlsafe_b64encode(d_bytes))
     return obj
Esempio n. 16
0
def generateAndSaveKey (flag):

    # 1. Gerar a Chave Privada e Pública.
    rsaPrivateKey = rsa.generate_private_key(
        public_exponent=65537,    
        key_size=2048,    
        backend=default_backend()
    )
    rsaPublicKey = rsaPrivateKey.public_key()

    # 2. Salvar a Chave Privada e Pública, consoante a flag.

    # Criação dos bytes serializados da Chave RSA Privada.
    privateBytes = rsaPrivateKey.private_bytes(
        encoding=Encoding.PEM,
        format=PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=NoEncryption()
    )

    # Criação dos bytes serializados da Chave RSA Pública.
    publicBytes = rsaPublicKey.public_bytes(encoding=Encoding.PEM,
        format=PublicFormat.SubjectPublicKeyInfo)

    # Guardar no ficheiro a Chave Privada.
    if(flag==0): nomeFicheiro = "serverRSA.private"
    else: nomeFicheiro = "clientRSA.private"
    with open(nomeFicheiro, "wb") as privateKeyFile:
        privateKeyFile.write(privateBytes)

    # Guardar no ficheiro a Chave Pública.
    if(flag==0): nomeFicheiro = "serverRSA.public"
    else: nomeFicheiro = "clientRSA.public"
    with open(nomeFicheiro, "wb") as publicKeyFile:
        publicKeyFile.write(publicBytes)
Esempio n. 17
0
def generate_csr(domains, key_path, csr_path, key_type=RSA_KEY_TYPE):
    """
    Generate a private key, and a CSR for the given domains using this key.
    :param domains: the domain names to include in the CSR
    :type domains: `list` of `str`
    :param str key_path: path to the private key that will be generated
    :param str csr_path: path to the CSR that will be generated
    :param str key_type: type of the key (misc.RSA_KEY_TYPE or misc.ECDSA_KEY_TYPE)
    """
    if key_type == RSA_KEY_TYPE:
        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)
    elif key_type == ECDSA_KEY_TYPE:
        key = ec.generate_private_key(ec.SECP384R1(), default_backend())
        key = key.private_bytes(encoding=Encoding.PEM,
                                format=PrivateFormat.TraditionalOpenSSL,
                                encryption_algorithm=NoEncryption())
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
    else:
        raise ValueError('Invalid key type: {0}'.format(key_type))

    key_bytes = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
    with open(key_path, 'wb') as file:
        file.write(key_bytes)

    csr_bytes = crypto_util.make_csr(key_bytes, domains)
    with open(csr_path, 'wb') as file:
        file.write(csr_bytes)
Esempio n. 18
0
def load_pkcs12_certificate(certificate_data, password):
    # type: (bytes, Optional[bytes]) -> _Cert
    from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, pkcs12, PrivateFormat

    try:
        private_key, cert, additional_certs = pkcs12.load_key_and_certificates(
            certificate_data, password, backend=default_backend()
        )
    except ValueError as ex:
        # mentioning PEM here because we raise this error when certificate_data is garbage
        six.raise_from(ValueError("Failed to deserialize certificate in PEM or PKCS12 format"), ex)
    if not private_key:
        raise ValueError("The certificate must include its private key")
    if not cert:
        raise ValueError("Failed to deserialize certificate in PEM or PKCS12 format")

    # This serializes the private key without any encryption it may have had. Doing so doesn't violate security
    # boundaries because this representation of the key is kept in memory. We already have the key and its
    # password, if any, in memory.
    key_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())
    pem_sections = [key_bytes] + [c.public_bytes(Encoding.PEM) for c in [cert] + additional_certs]
    pem_bytes = b"".join(pem_sections)

    fingerprint = cert.fingerprint(hashes.SHA1())  # nosec

    return _Cert(pem_bytes, private_key, fingerprint)
Esempio n. 19
0
def write_ca(cert, data, password=None):
    key_dest = os.path.join(args.dest, data['key_filename'])
    pub_dest = os.path.join(args.dest, data['pub_filename'])
    key_der_dest = os.path.join(args.dest, data['key_der_filename'])
    pub_der_dest = os.path.join(args.dest, data['pub_der_filename'])

    # write files to dest
    shutil.copy(ca_storage.path(cert.private_key_path), key_dest)
    with open(pub_dest, 'w') as stream:
        stream.write(cert.pub)

    if password is None:
        encryption = NoEncryption()
    else:
        encryption = BestAvailableEncryption(password)

    key_der = cert.key(password=password).private_bytes(
        encoding=Encoding.DER, format=PrivateFormat.PKCS8, encryption_algorithm=encryption)
    with open(key_der_dest, 'wb') as stream:
        stream.write(key_der)
    with open(pub_der_dest, 'wb') as stream:
        stream.write(cert.dump_certificate(Encoding.DER))

    # These keys are only present in CAs:
    data['issuer_url'] = ca.issuer_url
    data['crl_url'] = ca.crl_url
    data['ca_crl_url'] = '%s%s' % (testserver, reverse('django_ca:ca-crl', kwargs={'serial': ca.serial}))
    data['ocsp_url'] = '%s%s' % (testserver, reverse('django_ca:ocsp-cert-post',
                                                     kwargs={'serial': ca.serial}))

    # Update common data for CAs and certs
    update_cert_data(cert, data)
Esempio n. 20
0
    def generate_ssh_keys(cls,
                          size=4096,
                          passphrase=None,
                          private_format=PrivateFormat.PKCS8,
                          public_format=PublicFormat.OpenSSH,
                          private_encoding=Encoding.PEM,
                          public_encoding=Encoding.OpenSSH):
        """Generates a public and private rsa ssh key

        Returns an SSHKeyResponse objects which has both the public and private
        key as attributes

        :param int size: RSA modulus length (must be a multiple of 256)
                             and >= 1024
        :param str passphrase: The pass phrase to derive the encryption key
                                from
        """
        encryption = (BestAvailableEncryption(passphrase)
                      if passphrase else NoEncryption())
        key = rsa.generate_private_key(backend=default_backend(),
                                       public_exponent=65537,
                                       key_size=size)

        return SSHKey(public_key=key.public_key().public_bytes(
            public_encoding, public_format),
                      private_key=key.private_bytes(Encoding.PEM,
                                                    private_format,
                                                    encryption))
Esempio n. 21
0
def sns_privatekey():
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=1024,  # 1024 shouldn't be used, but for tests it's fine.
        backend=default_backend(),
    )
    return key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())
Esempio n. 22
0
def private_key_to_raw(private_key):
    private_key_pkcs8 = private_key.private_bytes(Encoding.DER,
                                                  PrivateFormat.PKCS8,
                                                  NoEncryption())
    # Key is serialized in the PKCS8 format, but we need the raw key bytestring
    # The raw key is found from byte 36 to 68 in the formatted key.
    return private_key_pkcs8[PRIVATE_BYTES_START:PRIVATE_BYTES_END]
Esempio n. 23
0
    def _save(
            cls, key: PrivateKey, cert: x509.Certificate, directory: str,
            name: str, key_format: Encoding
    ) -> ((str, bytes), (str, bytes), (str, bytes)):

        private_file = f'{name}.{key_format.name.lower()}'
        private_path = join(directory, private_file)
        private_bytes = key.private_bytes(key_format, PrivateFormat.PKCS8,
                                          NoEncryption())

        public_file = f'{name}.pub.{key_format.name.lower()}'
        public_path = join(directory, public_file)
        public_bytes = cert.public_key().public_bytes(key_format,
                                                      PublicFormat.PKCS1)

        cert_file = f'{name}.cert.{key_format.name.lower()}'
        cert_path = join(directory, cert_file)
        cert_bytes = cert.public_bytes(key_format)

        serialized = ((private_path, private_bytes),
                      (public_path, public_bytes), (cert_path, cert_bytes))

        for file_path, file_bytes in serialized:
            with open(file_path, 'wb') as out:
                out.write(file_bytes)

        return serialized
Esempio n. 24
0
    def as_bytes(self, encoding=None, is_private=False, password=None):
        """Export key into PEM/DER format bytes.

        :param encoding: "PEM" or "DER"
        :param is_private: export private key or public key
        :param password: encrypt private key with password
        :return: bytes
        """

        if encoding is None or encoding == 'PEM':
            encoding = Encoding.PEM
        elif encoding == 'DER':
            encoding = Encoding.DER
        else:
            raise ValueError('Invalid encoding: {!r}'.format(encoding))

        raw_key = self.as_key(is_private)
        if is_private:
            if not raw_key:
                raise ValueError('This is a public key')
            if password is None:
                encryption_algorithm = NoEncryption()
            else:
                encryption_algorithm = BestAvailableEncryption(
                    to_bytes(password))
            return raw_key.private_bytes(
                encoding=encoding,
                format=PrivateFormat.PKCS8,
                encryption_algorithm=encryption_algorithm,
            )
        return raw_key.public_bytes(
            encoding=encoding,
            format=PublicFormat.SubjectPublicKeyInfo,
        )
Esempio n. 25
0
def copy_cert(cert, data, key_path, csr_path):
    key_dest = os.path.join(args.dest, data["key_filename"])
    csr_dest = os.path.join(args.dest, data["csr_filename"])
    pub_dest = os.path.join(args.dest, data["pub_filename"])
    key_der_dest = os.path.join(args.dest, data["key_der_filename"])
    pub_der_dest = os.path.join(args.dest, data["pub_der_filename"])

    shutil.copy(key_path, key_dest)
    shutil.copy(csr_path, csr_dest)
    with open(pub_dest, "w") as stream:
        stream.write(cert.pub.pem)

    with open(key_dest, "rb") as stream:
        priv_key = stream.read()
    priv_key = load_pem_private_key(priv_key, None, default_backend())
    key_der = priv_key.private_bytes(encoding=Encoding.DER,
                                     format=PrivateFormat.PKCS8,
                                     encryption_algorithm=NoEncryption())
    with open(key_der_dest, "wb") as stream:
        stream.write(key_der)
    with open(pub_der_dest, "wb") as stream:
        stream.write(cert.pub.der)

    data["crl"] = cert.ca.crl_url
    data["subject"] = cert.distinguished_name
    data["parsed_cert"] = cert

    update_cert_data(cert, data)
Esempio n. 26
0
def export_key(key, encoding=None, is_private=False, password=None):
    if encoding is None or encoding == 'PEM':
        encoding = Encoding.PEM
    elif encoding == 'DER':
        encoding = Encoding.DER
    else:
        raise ValueError('Invalid encoding: {!r}'.format(encoding))

    if is_private:
        if key.key_type == 'private':
            if password is None:
                encryption_algorithm = NoEncryption()
            else:
                encryption_algorithm = BestAvailableEncryption(
                    to_bytes(password))
            return key.raw_key.private_bytes(
                encoding=encoding,
                format=PrivateFormat.PKCS8,
                encryption_algorithm=encryption_algorithm,
            )
        raise ValueError('This is a public key')

    if key.key_type == 'private':
        raw_key = key.raw_key.public_key()
    else:
        raw_key = key.raw_key

    return raw_key.public_bytes(
        encoding=encoding,
        format=PublicFormat.SubjectPublicKeyInfo,
    )
Esempio n. 27
0
    def cryptography_create_pkcs12_bundle(self,
                                          keystore_p12_path,
                                          key_format='PEM',
                                          cert_format='PEM'):
        if key_format == 'PEM':
            key_loader = load_pem_private_key
        else:
            key_loader = load_der_private_key

        if cert_format == 'PEM':
            cert_loader = load_pem_x509_certificate
        else:
            cert_loader = load_der_x509_certificate

        try:
            with open(self.private_key_path, 'rb') as key_file:
                private_key = key_loader(key_file.read(),
                                         password=to_bytes(self.keypass),
                                         backend=backend)
        except TypeError:
            # Re-attempt with no password to match existing behavior
            try:
                with open(self.private_key_path, 'rb') as key_file:
                    private_key = key_loader(key_file.read(),
                                             password=None,
                                             backend=backend)
            except (OSError, TypeError, ValueError, UnsupportedAlgorithm) as e:
                self.module.fail_json(
                    msg=
                    "The following error occurred while loading the provided private_key: %s"
                    % to_native(e))
        except (OSError, ValueError, UnsupportedAlgorithm) as e:
            self.module.fail_json(
                msg=
                "The following error occurred while loading the provided private_key: %s"
                % to_native(e))
        try:
            with open(self.certificate_path, 'rb') as cert_file:
                cert = cert_loader(cert_file.read(), backend=backend)
        except (OSError, ValueError, UnsupportedAlgorithm) as e:
            self.module.fail_json(
                msg=
                "The following error occurred while loading the provided certificate: %s"
                % to_native(e))

        if self.password:
            encryption = BestAvailableEncryption(to_bytes(self.password))
        else:
            encryption = NoEncryption()

        pkcs12_bundle = serialize_key_and_certificates(
            name=to_bytes(self.name),
            key=private_key,
            cert=cert,
            cas=None,
            encryption_algorithm=encryption)

        with open(keystore_p12_path, 'wb') as p12_file:
            p12_file.write(pkcs12_bundle)
Esempio n. 28
0
    def write_key(self, fn):
        from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption

        data = self.key.private_bytes(encoding=Encoding.PEM,
                                      format=PrivateFormat.TraditionalOpenSSL,
                                      encryption_algorithm=NoEncryption())
        with open(fn, 'w') as f:
            f.write(data)
Esempio n. 29
0
    def generate_private_key(self, key_type='ec256'):
        """
        Generates a new RSA or EC private key.\n
        - :param `key_type` [`str`]: the requested `private_key` type. Options are: [`ec256`, `ec384`, `rsa2048`,
        `rsa4096`]\n
        - :return [`bytes`]: the encoded private key PEM data string. This method will update the `private_key` property
         of the object with the same value.\n
        - :raises `InvalidKeyType`: when an unknown/unsupported `key_type` is requested\n\n

        ## Example\n
        ```python
        >>> client.generate_private_key(key_type="ec384")
        b'-----BEGIN EC PRIVATE KEY-----\\nMIGkAgEBBDAZRFNLcQdVJmLh42p8F4D92...'
        ```
        """
        # Generate a EC256 private key
        if key_type == 'ec256':
            key = ec.generate_private_key(ec.SECP256R1(), default_backend())
            self.private_key = key.private_bytes(
                encoding=Encoding.PEM,
                format=PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=NoEncryption())
        # Generate a EC384 private key
        elif key_type == 'ec384':
            key = ec.generate_private_key(ec.SECP384R1(), default_backend())
            self.private_key = key.private_bytes(
                encoding=Encoding.PEM,
                format=PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=NoEncryption()
            )
        # Generate a RSA2048 private key
        elif key_type == 'rsa2048':
            key = OpenSSL.crypto.PKey()
            key.generate_key(OpenSSL.crypto.TYPE_RSA, 2048)
            self.private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
        # Generate a RSA4096 private key
        elif key_type == 'rsa4096':
            key = OpenSSL.crypto.PKey()
            key.generate_key(OpenSSL.crypto.TYPE_RSA, 4096)
            self.private_key = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, key)
        # Otherwise, the requested key type is not supported. Throw an error
        else:
            options = ['ec256', 'ec384', 'rsa2048', 'rsa4096']
            msg = "Invalid private key rtype '{key_type}'. Options {options}".format(key_type=key_type, options=options)
            raise errors.InvalidKeyType(msg)
        return self.private_key
Esempio n. 30
0
def key_to_pem(key, password=None):
    """Serialize key in PEM format, optionally encrypted.
    """
    if password:
        enc = BestAvailableEncryption(as_bytes(password))
    else:
        enc = NoEncryption()
    return key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, enc)