コード例 #1
0
def generate_p12(CN, pubCert):
    # PKCS #12 filename to save as
    p12_file = CN + '.pfx'
    # Open certificate and read certificate info
    with open(pubCert, 'rb') as publicCert:
        pemText = publicCert.read()
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, pemText)
    # Object representing PKCS #12
    p12 = crypto.PKCS12()
    # Set certificate in PKCS #12 structure
    p12.set_certificate(cert)
    # Dump PKCS #12 as string, set import password as 'password'
    p12Text = p12.export('password')
    # Write as binary to PKCS #12
    with open(p12_file, 'wb') as p12File:
        p12File.write(p12Text)
    return p12_file
コード例 #2
0
    def test_signature(self):
        pkcs12 = crypto.PKCS12()
        pkey = crypto.PKey()
        pkey.generate_key(crypto.TYPE_RSA, 512)
        x509 = crypto.X509()
        x509.set_pubkey(pkey)
        x509.set_serial_number(0)
        x509.get_subject().CN = "me"
        x509.set_issuer(x509.get_subject())
        x509.gmtime_adj_notBefore(0)
        x509.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
        x509.sign(pkey, 'md5')
        pkcs12.set_privatekey(pkey)
        pkcs12.set_certificate(x509)
        self.main_company.facturae_cert = base64.b64encode(
            pkcs12.export(passphrase='password'))
        self.main_company.facturae_cert_password = '******'
        self.main_company.partner_id.country_id = self.ref('base.es')
        self.wizard.with_context(
            active_ids=self.invoice.ids,
            active_model='account.invoice').create_facturae_file()
        generated_facturae = etree.fromstring(
            base64.b64decode(self.wizard.facturae))
        ns = 'http://www.w3.org/2000/09/xmldsig#'
        self.assertEqual(
            len(
                generated_facturae.xpath('//ds:Signature',
                                         namespaces={'ds': ns})), 1)

        node = generated_facturae.find(".//ds:Signature", {'ds': ns})
        ctx = xmlsig.SignatureContext()
        certificate = crypto.load_pkcs12(
            base64.b64decode(self.main_company.facturae_cert), 'password')
        certificate.set_ca_certificates(None)
        verification_error = False
        error_message = ''
        try:
            ctx.verify(node)
        except Exception as e:
            verification_error = True
            error_message = e.message
            pass
        self.assertEqual(
            verification_error, False,
            'Error found during verification of the signature of ' +
            'the invoice: %s' % error_message)
コード例 #3
0
def make_p12_with_ca_cert(given_ca_cert, given_passphrase):
    '''Given CA cert object and passphrase, create a PKCS container
        and return it as data.  Return None if something went wrong.'''
    common.logging_info("Generating PKCS12 store for given CA certificate.")
    p = crypto.PKCS12()
    try:
        p.set_ca_certificates([given_ca_cert])
    except crypto.Error:
        common.logging_error(
            "Could create a p12 object with given CA certificate.")
        return None
    try:
        p12_ca_data = p.export(passphrase=given_passphrase)
    except crypto.Error:
        common.logging_error("Could not export data from p12 object.")
        return None
    return p12_ca_data
コード例 #4
0
ファイル: barbican.py プロジェクト: wind-fire/octavia
    def store_cert(self, context, certificate, private_key, intermediates=None,
                   private_key_passphrase=None, expiration=None,
                   name="PKCS12 Certificate Bundle"):
        """Stores a certificate in the certificate manager.

        :param context: Oslo context of the request
        :param certificate: PEM encoded TLS certificate
        :param private_key: private key for the supplied certificate
        :param intermediates: ordered and concatenated intermediate certs
        :param private_key_passphrase: optional passphrase for the supplied key
        :param expiration: the expiration time of the cert in ISO 8601 format
        :param name: a friendly name for the cert

        :returns: the container_ref of the stored cert
        :raises Exception: if certificate storage fails
        """
        connection = self.auth.get_barbican_client(context.project_id)

        LOG.info("Storing certificate secret '%s' in Barbican.", name)
        p12 = crypto.PKCS12()
        p12.set_friendlyname(encodeutils.to_utf8(name))
        x509_cert = crypto.load_certificate(crypto.FILETYPE_PEM, certificate)
        p12.set_certificate(x509_cert)
        x509_pk = crypto.load_privatekey(crypto.FILETYPE_PEM, private_key)
        p12.set_privatekey(x509_pk)
        if intermediates:
            cert_ints = list(cert_parser.get_intermediates_pems(intermediates))
            x509_ints = [
                crypto.load_certificate(crypto.FILETYPE_PEM, ci)
                for ci in cert_ints]
            p12.set_ca_certificates(x509_ints)
        if private_key_passphrase:
            raise exceptions.CertificateStorageException(
                "Passphrase protected PKCS12 certificates are not supported.")

        try:
            certificate_secret = connection.secrets.create(
                payload=p12.export(),
                expiration=expiration,
                name=name
            )
            certificate_secret.store()
            return certificate_secret.secret_ref
        except Exception as e:
            with excutils.save_and_reraise_exception():
                LOG.error('Error storing certificate data: %s', str(e))
コード例 #5
0
    def _generate_certificate(self,
                              common_name: str,
                              p12path: str,
                              pempath: str = MainConfig.pemDir,
                              expiry_time_secs: int = 31536000) -> None:
        """
        Create a certificate and p12 file
        :param cn: Common Name for certificate
        :param pempath: String filepath for the pem file created
        :param p12path: String filepath for the p12 file created
        :param expiry_time_secs: length of time in seconds that the certificate is valid for, defaults to 1 year
        """
        if not os.path.exists(pempath):
            ca_key = crypto.load_privatekey(crypto.FILETYPE_PEM,
                                            open(self.cakeypath).read())
            ca_pem = crypto.load_certificate(crypto.FILETYPE_PEM,
                                             open(self.capempath, 'rb').read())
            serial_number = random.getrandbits(64)
            chain = (ca_pem, )
            cert = crypto.X509()
            cert.get_subject().CN = common_name
            cert.set_serial_number(serial_number)
            cert.gmtime_adj_notBefore(0)
            cert.gmtime_adj_notAfter(expiry_time_secs)
            cert.set_issuer(ca_pem.get_subject())
            cert.set_pubkey(self.key)
            cert.set_version(2)
            cert.sign(ca_key, "sha256")
            p12 = crypto.PKCS12()
            p12.set_privatekey(self.key)
            p12.set_certificate(cert)
            p12.set_ca_certificates(tuple(chain))
            p12data = p12.export(
                passphrase=bytes(self.CERTPWD, encoding='UTF-8'))
            with open(p12path, 'wb') as p12file:
                p12file.write(p12data)

            if os.path.exists(pempath):
                print("Certificate File Exists, aborting.")
            else:
                f = open(pempath, "wb")
                f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
                f.close()
        else:
            pass
コード例 #6
0
 def get_p12(self):
     """
     Because for signing the XML file is needed a PKCS #12 and
     the passphrase is not available in the AEAT certificate,
     create a new one and set the certificate and its private key
     from the stored files.
     :return: A PKCS #12 archive
     """
     self.ensure_one()
     with open(self.public_key, 'rb') as f_crt:
         cert = crypto.load_certificate(crypto.FILETYPE_PEM, f_crt.read())
     p12 = crypto.PKCS12()
     p12.set_certificate(cert)
     with open(self.private_key, 'rb') as f_pem:
         private_key = f_pem.read()
     p12.set_privatekey(
         crypto.load_privatekey(crypto.FILETYPE_PEM, private_key))
     return p12
コード例 #7
0
    def newCertificate(self, informations, name, email):
        """
        Tworzy nowy certyfikat wraz z parą kluczy.

        Args:
            information (dict): Słownik zawierający informacje o podmiocie.
                Musi zawierać wszystkie te klucze:
                    country, state, city, organization, unit, name
            password (str): Hasło chroniące klucz prywatny.
            name (str): Nazwa plików, do których zapisane zostaną dane.
            email (str): Adres e-mail użytkownika.

        Return:
            str, str: Ścieżka do pliku certyfikatu, ścieżka do pliku klucza

        Raises:
            ValueError: Jeśli informacje nie zawierają wszystkich kluczy
            IOError: Jeśli wystąpiły problemy z zapisem plików
        """
        certificate = self.__generateCertificate(informations, email)
        keys = self.__generateKeys()
        certificate.set_pubkey(keys)
        certificate.add_extensions([
            crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"),
            crypto.X509Extension(
                b"keyUsage", False,
                b"digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement"
            ),
            crypto.X509Extension(b"extendedKeyUsage", False,
                                 b"emailProtection, clientAuth"),
            crypto.X509Extension(b"subjectAltName", False,
                                 b"DNS:" + name.encode())
        ])

        certificate = self.__signCertificate(certificate)
        certificatePath = os.path.join(self.__configuration.certificatesDir,
                                       ".".join([name, "crt"]))
        keyPath = ".".join([name, "pfx"])
        self.__saveCertificate(certificatePath, certificate)
        p12 = crypto.PKCS12()
        p12.set_certificate(certificate)
        p12.set_privatekey(keys)
        open(keyPath, "wb").write(p12.export())
        return keyPath, certificatePath
コード例 #8
0
    def generate(self, module):
        """Generate PKCS#12 file archive."""

        self.pkcs12 = crypto.PKCS12()

        try:
            self.remove(module)
        except PkcsError as exc:
            module.fail_json(msg=to_native(exc))

        if self.ca_certificates:
            ca_certs = [
                crypto_utils.load_certificate(ca_cert)
                for ca_cert in self.ca_certificates
            ]
            self.pkcs12.set_ca_certificates(ca_certs)

        if self.certificate_path:
            self.pkcs12.set_certificate(
                crypto_utils.load_certificate(self.certificate_path))

        if self.friendly_name:
            self.pkcs12.set_friendlyname(to_bytes(self.friendly_name))

        if self.privatekey_path:
            try:
                self.pkcs12.set_privatekey(
                    crypto_utils.load_privatekey(self.privatekey_path,
                                                 self.privatekey_passphrase))
            except crypto_utils.OpenSSLBadPassphraseError as exc:
                raise PkcsError(exc)

        try:
            pkcs12_file = os.open(self.path,
                                  os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
                                  self.mode)
            os.write(
                pkcs12_file,
                self.pkcs12.export(self.passphrase, self.iter_size,
                                   self.maciter_size))
            os.close(pkcs12_file)
        except (IOError, OSError) as exc:
            self.remove(module)
            raise PkcsError(exc)
コード例 #9
0
    def _generate_certificate(self,
                              cn: str = "Server",
                              pempath: str = MainConfig.pemDir,
                              p12path: str = MainConfig.p12Dir) -> None:
        """
        Create a certificate and p12 file
        :param cn: Common Name for certificate
        :param pempath: String filepath for the pem file created
        :param p12path: String filepath for the p12 file created
        """
        if os.path.exists(pempath):
            print("Certificate File Exists, aborting.")
            return None
        cakey = crypto.load_privatekey(crypto.FILETYPE_PEM,
                                       open(self.cakeypath).read())
        capem = crypto.load_certificate(crypto.FILETYPE_PEM,
                                        open(self.capempath, 'rb').read())
        serialnumber = random.getrandbits(64)
        chain = (capem, )
        cert = crypto.X509()
        cert.get_subject().CN = cn
        cert.set_serial_number(serialnumber)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(315360000)
        cert.set_issuer(capem.get_subject())
        cert.set_pubkey(self.key)
        cert.set_version(2)
        cert.sign(cakey, "sha256")
        print('cert genned')
        p12 = crypto.PKCS12()
        p12.set_privatekey(self.key)
        p12.set_certificate(cert)
        p12.set_ca_certificates(tuple(chain))
        p12data = p12.export(passphrase=bytes(self.CERTPWD, encoding='UTF-8'))
        with open(p12path, 'wb') as p12file:
            p12file.write(p12data)

        if os.path.exists(pempath):
            print("Certificate File Exists, aborting.")
        else:
            f = open(pempath, "wb")
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
            f.close()
コード例 #10
0
ファイル: buildcert.py プロジェクト: hugo-cmac/MIETI
    def __create_signed_cert(self, identity):
        k = crypto.PKey()
        k.generate_key(crypto.TYPE_RSA, 2048)

        cert = crypto.X509()
        cert.set_version(2)
        cert.set_serial_number(random.randint(50000000, 100000000))

        cert.get_subject().CN = identity
        cert.set_issuer(self.ca_cert.get_subject())
        cert.set_pubkey(k)

        cert.add_extensions([
            crypto.X509Extension(b"basicConstraints", False, b"CA:FALSE"),
        ])

        cert.add_extensions([
            crypto.X509Extension(b"authorityKeyIdentifier",
                                 False,
                                 b"keyid",
                                 issuer=self.ca_cert),
            crypto.X509Extension(b"extendedKeyUsage", False, b"serverAuth"),
            crypto.X509Extension(b"keyUsage", True,
                                 b"digitalSignature, keyEncipherment"),
        ])

        cert.add_extensions([
            crypto.X509Extension(b"subjectKeyIdentifier",
                                 False,
                                 b"hash",
                                 subject=cert),
        ])

        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(24 * 60 * 60)

        cert.sign(self.ca_key, 'sha256')

        keystore = crypto.PKCS12()
        keystore.set_privatekey(k)
        keystore.set_certificate(cert)
        with open(identity + ".p12", "wb") as f:
            f.write(keystore.export(passphrase="1234", iter=2048, maciter=1))
コード例 #11
0
ファイル: castellan_mgr.py プロジェクト: syoder89/octavia
    def store_cert(self,
                   context,
                   certificate,
                   private_key,
                   intermediates=None,
                   private_key_passphrase=None,
                   expiration=None,
                   name="PKCS12 Certificate Bundle"):
        p12 = crypto.PKCS12()
        p12.set_certificate(certificate)
        p12.set_privatekey(private_key)
        if intermediates:
            p12.set_ca_certificates(intermediates)
        if private_key_passphrase:
            raise exceptions.CertificateStorageException(
                "Passphrases protected PKCS12 certificates are not supported.")

        p12_data = opaque_data.OpaqueData(p12.export(), name=name)
        self.manager.store(context, p12_data)
コード例 #12
0
    def _create_pkcs12_bin(self):
        """
        Helper function to create an encrypted pkcs12 binary for download

        :return: PKCS12 binary
        """
        certificate = self.get_tokeninfo("certificate")
        privatekey = self.get_tokeninfo("privatekey")
        pkcs12 = crypto.PKCS12()
        pkcs12.set_certificate(crypto.load_certificate(
            crypto.FILETYPE_PEM, certificate))
        pkcs12.set_privatekey(crypto.load_privatekey(crypto.FILETYPE_PEM,
                                                     privatekey))
        # TODO define a random passphrase and hand it to the user
        passphrase = self.token.get_pin()
        if passphrase == -1:
            passphrase = ""
        pkcs12_bin = pkcs12.export(passphrase=passphrase)
        return pkcs12_bin
コード例 #13
0
ファイル: certutils.py プロジェクト: isabella232/catapult-csm
def write_dummy_ca_cert(ca_cert_str, key_str, cert_path):
    """Writes four certificate files.

  For example, if cert_path is "mycert.pem":
      mycert.pem - CA plus private key
      mycert-cert.pem - CA in PEM format
      mycert-cert.cer - CA for Android
      mycert-cert.p12 - CA in PKCS12 format for Windows devices
  Args:
    cert_path: path string such as "mycert.pem"
    ca_cert_str: certificate string
    key_str: private key string
  """
    dirname = os.path.dirname(cert_path)
    if dirname and not os.path.exists(dirname):
        os.makedirs(dirname)

    root_path = os.path.splitext(cert_path)[0]
    ca_cert_path = root_path + '-cert.pem'
    android_cer_path = root_path + '-cert.cer'
    windows_p12_path = root_path + '-cert.p12'

    # Dump the CA plus private key
    with open(cert_path, 'w') as f:
        f.write(key_str)
        f.write(ca_cert_str)

    # Dump the certificate in PEM format
    with open(ca_cert_path, 'w') as f:
        f.write(ca_cert_str)

    # Create a .cer file with the same contents for Android
    with open(android_cer_path, 'w') as f:
        f.write(ca_cert_str)

    ca_cert = load_cert(ca_cert_str)
    key = load_privatekey(key_str)
    # Dump the certificate in PKCS12 format for Windows devices
    with open(windows_p12_path, 'w') as f:
        p12 = crypto.PKCS12()
        p12.set_certificate(ca_cert)
        p12.set_privatekey(key)
        f.write(p12.export())
コード例 #14
0
ファイル: misc.py プロジェクト: netosjb/l10n-brazil
def create_fake_certificate_file(valid, passwd, issuer, country, subject):
    """Creating a fake certificate

        TODO: Move this method to erpbrasil

    :param valid: True or False
    :param passwd: Some password
    :param issuer: Some string, like EMISSOR A TESTE
    :param country: Some country: BR
    :param subject: Some string: CERTIFICADO VALIDO TESTE
    :return: base64 file
    """
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    cert = crypto.X509()

    cert.get_issuer().C = country
    cert.get_issuer().CN = issuer

    cert.get_subject().C = country
    cert.get_subject().CN = subject

    cert.set_serial_number(2009)

    if valid:
        time_before = 0
        time_after = 365 * 24 * 60 * 60
    else:
        time_before = -1 * (365 * 24 * 60 * 60)
        time_after = 0

    cert.gmtime_adj_notBefore(time_before)
    cert.gmtime_adj_notAfter(time_after)
    cert.set_pubkey(key)
    cert.sign(key, "md5")

    p12 = crypto.PKCS12()
    p12.set_privatekey(key)
    p12.set_certificate(cert)

    return b64encode(p12.export(passwd))
コード例 #15
0
    def new_employee_cert(self, uid, lastname, firstname, email,
                          serial_number):

        subject = self.get_employee_name(uid, lastname, firstname, email)
        subject_key = self.generate_keys()
        cert = self.gen_unsigned_cert(self.get_ca_name(), subject,
                                      serial_number, subject_key, 1)
        cert.sign(self.ca_key, 'sha256')
        pkcs12 = crypto.PKCS12()
        pkcs12.set_certificate(cert)
        pkcs12.set_privatekey(subject_key)
        p12bytes = pkcs12.export()
        p12bytes_encrypted = pkcs12.export(
            passphrase=self.passphrase.encode('utf-8'))
        path = self.p12_folder + "/" + "uid" + str(uid) + "sn" + str(
            serial_number) + ".p12"
        file = open(path, "wb")
        file.write(p12bytes_encrypted)
        file.close()
        return p12bytes
コード例 #16
0
ファイル: server.py プロジェクト: j-d-r/UserCertServer
def gen_cert_p12(addr, username):
    """Generate a PKCS#12 certificate and RSA key."""
    private_key = rsa.generate_private_key(CERT_RSA_EXP, CERT_KEY_SIZE,
                                           bk.default_backend())
    cert = gen_cert(private_key.public_key(), username)

    p12 = c.PKCS12()
    p12.set_certificate(c.X509.from_cryptography(cert))
    p12.set_ca_certificates([
        c.X509.from_cryptography(p.cacert),
    ])
    p12.set_privatekey(c.PKey.from_cryptography_key(private_key))
    p12str = p12.export(passphrase=p.export_pass)

    with open(CA_LOGFILE, 'ab') as logf:
        logf.write(('{} {} {} PKCS12\n'.format(tm.time(), addr,
                                               username)).encode())
        logf.write(cert.public_bytes(sr.Encoding.PEM))

    return p12str
コード例 #17
0
    def generate(self, module):
        """Generate PKCS#12 file archive."""
        self.pkcs12 = crypto.PKCS12()

        if self.other_certificates:
            self.pkcs12.set_ca_certificates(self.other_certificates)

        if self.certificate_path:
            self.pkcs12.set_certificate(load_certificate(self.certificate_path))

        if self.friendly_name:
            self.pkcs12.set_friendlyname(to_bytes(self.friendly_name))

        if self.privatekey_path:
            try:
                self.pkcs12.set_privatekey(load_privatekey(self.privatekey_path, self.privatekey_passphrase))
            except OpenSSLBadPassphraseError as exc:
                raise PkcsError(exc)

        return self.pkcs12.export(self.passphrase, self.iter_size, self.maciter_size)
コード例 #18
0
    def gen_pfx(self, cert_name):
        if cert_name == "":
            raise Exception("Certificate name cannot be blank")

        # Load CA certificate
        ca_cert = self._load_cert_from_file(self.key_dir + '/ca.crt')

        # Load Certificate
        cert = self._load_cert_from_file(self.key_dir + '/' + cert_name + '.crt')

        # Load Private Key
        key = self._load_key_from_file(self.key_dir + '/' + cert_name + '.key')

        # Set up PKCS12 structure
        pkcs12 = crypto.PKCS12()
        pkcs12.set_ca_certificates([ca_cert])
        pkcs12.set_certificate(cert)
        pkcs12.set_privatekey(key)

        # Write PFX file
        self._write_pfx_to_file(pkcs12, self.key_dir + '/' + cert_name + '.pfx')
コード例 #19
0
def request_pkcs12(certpath, certpass, certname, datename):
    key_pem = open(certpath + certname + '.key', 'r').read()
    cert_pem = open(certpath + certname + '.cer', 'rb').read()
    ca_pem = open(certpath + 'ca.cer', 'rb').read()

    privkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
    cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_pem)
    ca = [crypto.load_certificate(crypto.FILETYPE_PEM, ca_pem)]

    p12 = crypto.PKCS12()
    p12.set_privatekey(privkey)
    p12.set_certificate(cert)
    p12.set_ca_certificates(ca)
    cert_p12 = p12.export(certpass.encode())

    with open(certpath + datename + '.p12', 'wb') as p12file:
        p12file.write(cert_p12)

    print(
        f'OPEN SSL Certificate {datename}.p12 successfully created and move to {certpath}'
    )
コード例 #20
0
    def _create_self_signed_cert(self,
                                 directory,
                                 email,
                                 common_name,
                                 cert_ttl,
                                 country='RU',
                                 state='Moscow',
                                 city='Moscow',
                                 organization='Nekrasovka',
                                 organizational_unit='Nekrasovka'):
        # create a key pair
        k = crypto.PKey()
        k.generate_key(crypto.TYPE_RSA, 1024)
        # create a self-signed cert

        cert = crypto.X509()
        cert.get_subject().C = country
        cert.get_subject().ST = state
        cert.get_subject().L = city
        cert.get_subject().O = organization
        cert.get_subject().OU = organizational_unit
        cert.get_subject().CN = common_name
        cert.set_serial_number(int(time.time()))
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(int(cert_ttl) * 24 * 60 * 60)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(k)
        cert.sign(k, 'sha1')
        open(self.cert_path,
             "wb+").write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
        open(self.private_key_path,
             "wb+").write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k))
        open(self.public_key_path,
             "wb+").write(crypto.dump_publickey(crypto.FILETYPE_PEM, k))

        p12 = crypto.PKCS12()
        p12.set_privatekey(k)
        p12.set_certificate(cert)

        open(self.pfx_path, 'wb+').write(p12.export())
コード例 #21
0
def generate(cn, passphrase=None):
    csrrequest = crypto.X509Req()
    csrrequest.get_subject().C = "US"
    csrrequest.get_subject().O = "eric.willisson.org"
    csrrequest.get_subject().CN = "Eric; Python"

    psec = crypto.PKey()
    psec.generate_key(crypto.TYPE_RSA, 2048)

    with open("from_python.key", "wb") as f:
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, psec))

    csrrequest.set_pubkey(psec)
    csrrequest.sign(psec, "sha1")

    with open("from_python.csr", "wb") as f:
        f.write(
            crypto.dump_certificate_request(crypto.FILETYPE_PEM, csrrequest))

    password = input("CA Password:"******"openssl", "x509", "-req", "-days", "365", "-in", "from_python.csr",
        "-CA", "CA.crt", "-CAkey", "CA.key", "-set_serial", "19", "-out",
        "from_python.crt", "-passin", "pass:"******"/home/eric/certs/CA.crt", "rb").read())
    cert = crypto.load_certificate(crypto.FILETYPE_PEM,
                                   open("from_python.crt", "rb").read())

    p12 = crypto.PKCS12()
    p12.set_privatekey(psec)
    p12.set_certificate(cert)
    p12.set_ca_certificates([ca_cert])
    open("user.pfx", "wb").write(p12.export())
コード例 #22
0
ファイル: importpfx.py プロジェクト: Kevin2305/certcrspfx
def generatePKCS12():
    cpath = input("------ Make PFX Page -------\n" \
                  "Certificate File Name or 'E' to exit: ")
    if str(cpath).lower().strip() == 'e':
        return "again"
    if not os.path.exists(cpath):
        print(cpath + " Not Found, aborting")
        sys.exit(1)
    kpath = input("Key File Name: ")
    if not os.path.exists(kpath):
        print(kpath + " Not Found, aborting")
        sys.exit(1)
    passcode = input("Passphrase for Private Key: ")
    if passcode == "":
        bpasscode = None
    else:
        bpasscode = passcode.encode("utf-8")
    print(bpasscode)
    filename = os.path.splitext(cpath)[0]
    pfxpath = os.path.join(os.getcwd(), filename + '_pfx.pfx')
    pkcs12 = crypto.PKCS12()
    with open(cpath, "rb") as f:
        cert = f.read()
    with open(kpath, "rb") as f:
        key = f.read()
    x509cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    try:
        x509key = crypto.load_privatekey(crypto.FILETYPE_PEM,
                                         key,
                                         passphrase=bpasscode)
    except:
        print("Passphrase Error")
        sys.exit(1)
    pkcs12.set_certificate(x509cert)
    pkcs12.set_privatekey(x509key)
    print("Generating...")
    with open(pfxpath, 'wb') as f:
        f.write(pkcs12.export())
        print("Success")
        print("PFX Stored Here : " + pfxpath)
コード例 #23
0
ファイル: panelLets.py プロジェクト: zhanglongfei/BaoTa
 def dump_pkcs12(self,
                 key_pem=None,
                 cert_pem=None,
                 ca_pem=None,
                 friendly_name=None):
     p12 = crypto.PKCS12()
     if cert_pem:
         ret = p12.set_certificate(
             crypto.load_certificate(crypto.FILETYPE_PEM,
                                     cert_pem.encode()))
         assert ret is None
     if key_pem:
         ret = p12.set_privatekey(
             crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem.encode()))
         assert ret is None
     if ca_pem:
         ret = p12.set_ca_certificates(
             (crypto.load_certificate(crypto.FILETYPE_PEM,
                                      ca_pem.encode()), ))
     if friendly_name:
         ret = p12.set_friendlyname(friendly_name.encode())
     return p12
コード例 #24
0
    def genUserCert(self, name, signas=None, outp=None, pkey=None):

        pkey, cert = self._genBasePkeyCert(name, pkey=pkey)

        cert.add_extensions([
            crypto.X509Extension(b'nsCertType', False, b'client'),
            crypto.X509Extension(b'keyUsage', False, b'digitalSignature'),
            crypto.X509Extension(b'extendedKeyUsage', False, b'clientAuth'),
            crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'),
        ])

        if signas is not None:
            self.signCertAs(cert, signas)
        else:
            self.selfSignCert(cert, pkey)

        if not pkey._only_public:
            keypath = self._savePkeyTo(pkey, 'users', '%s.key' % name)
            if outp is not None:
                outp.printf('key saved: %s' % (keypath,))

        crtpath = self._saveCertTo(cert, 'users', '%s.crt' % name)
        if outp is not None:
            outp.printf('cert saved: %s' % (crtpath,))

        ccert = crypto.PKCS12()
        ccert.set_friendlyname(name.encode('utf-8'))
        ccert.set_certificate(cert)
        ccert.set_privatekey(pkey)

        if signas:
            cacert = self.getCaCert(signas)
            ccert.set_ca_certificates([cacert])

        crtpath = self._saveP12To(ccert, 'users', '%s.p12' % name)
        if outp is not None:
            outp.printf('client cert saved: %s' % (crtpath,))

        return pkey, cert
コード例 #25
0
    def genClientCert(self, name, outp=None):
        '''
        Generates a user PKCS #12 archive.
        Please note that the resulting file will contain private key material.

        Args:
            name (str): The name of the user keypair.
            outp (synapse.lib.output.Output): The output buffer.

        Examples:
            Make the PKC12 object for user "myuser":

                myuserpkcs12 = cdir.genClientCert('myuser')

        Returns:
            OpenSSL.crypto.PKCS12: The PKCS #12 archive.
        '''
        ucert = self.getUserCert(name)
        if not ucert:
            raise s_exc.NoSuchFile(mesg='missing User cert', name=name)

        capath = self._getCaPath(ucert)
        cacert = self._loadCertPath(capath)
        if not cacert:
            raise s_exc.NoSuchFile(mesg='missing CA cert', path=capath)

        ukey = self.getUserKey(name)
        if not ukey:
            raise s_exc.NoSuchFile(mesg='missing User private key', name=name)

        ccert = crypto.PKCS12()
        ccert.set_friendlyname(name.encode('utf-8'))
        ccert.set_ca_certificates([cacert])
        ccert.set_certificate(ucert)
        ccert.set_privatekey(ukey)

        crtpath = self._saveP12To(ccert, 'users', '%s.p12' % name)
        if outp is not None:
            outp.printf('client cert saved: %s' % (crtpath, ))
コード例 #26
0
    def _create_certificate(self,
                            valid=True,
                            passwd=None,
                            issuer=None,
                            country=None,
                            subject=None):
        """Creating a fake certificate"""

        key = crypto.PKey()
        key.generate_key(crypto.TYPE_RSA, 2048)

        cert = crypto.X509()

        cert.get_issuer().C = country
        cert.get_issuer().CN = issuer

        cert.get_subject().C = country
        cert.get_subject().CN = subject

        cert.set_serial_number(2009)

        if valid:
            time_before = 0
            time_after = 365 * 24 * 60 * 60
        else:
            time_before = -1 * (365 * 24 * 60 * 60)
            time_after = 0

        cert.gmtime_adj_notBefore(time_before)
        cert.gmtime_adj_notAfter(time_after)
        cert.set_pubkey(key)
        cert.sign(key, 'md5')

        p12 = crypto.PKCS12()
        p12.set_privatekey(key)
        p12.set_certificate(cert)

        return b64encode(p12.export(passwd))
コード例 #27
0
    def export_pfx_cert(self, id_str, dir_path):
        """
        API to export a certificate in PFX format to given directory path

        Args:
            id_str (str): A user defined unique id string to identify the certificate
            dir_path (str): Valid directory path where the certificates are to be exported.

        Raises:
            edgectl.errors.EdgeValueError - Any input found to be invalid
            edgectl.errors.EdgeFileAccessError
        """
        if id_str not in self._cert_chain:
            msg = 'Invalid cert ID: {0}'.format(id_str)
            raise edgectl.errors.EdgeValueError(msg)

        try:
            cert_dict = self._cert_chain[id_str]
            cert_obj = cert_dict['cert']
            key_obj = cert_dict['key_pair']
            pfx = crypto.PKCS12()
            pfx.set_privatekey(key_obj)
            pfx.set_certificate(cert_obj)
            pfx_data = pfx.export('')
            prefix = id_str
            path = os.path.realpath(dir_path)
            path = os.path.join(path, prefix)
            cert_dir = os.path.join(path, 'cert')
            pfx_output_file_name = os.path.join(cert_dir, prefix + '.cert.pfx')
            logging.debug('Exporting PFX Certificate File: %s',
                          pfx_output_file_name)
            with open(pfx_output_file_name, 'wb') as pfx_file:
                pfx_file.write(pfx_data)
        except IOError as ex:
            msg = 'IO Error when exporting PFX cert ID: {0}.' \
                  ' Errno: {1} Error: {2}'.format(id_str, str(ex.errno), ex.strerror)
            logging.error(msg)
            raise edgectl.errors.EdgeFileAccessError(msg, pfx_output_file_name)
コード例 #28
0
    def savePKCS12(self,
                   path,
                   password=None,
                   chain=True,
                   root=False,
                   addkey=None):
        if addkey is None:
            addkey = self != self.parent.cacert

        p12 = crypto.PKCS12()
        p12.set_certificate(self.x509)
        p12.set_friendlyname(b(self.alias))
        if addkey:
            p12.set_privatekey(self.pkey)
        if chain:
            certs = []
            parent = self.parent
            while parent if root else parent.parent:
                certs.append(parent.cacert.x509)
                parent = parent.parent
            p12.set_ca_certificates(certs)
        write(path, p12.export(b(password or "password")))
        return self
コード例 #29
0
def export_pkcs12(cert: Union[bytes, crypto.X509],
                  key: Union[bytes, crypto.PKey],
                  passphrase: bytes = None) -> bytes:
    if not isinstance(cert, crypto.X509):
        # silly check
        if b'CERTIFICATE' not in cert:
            cert = (
                b'-----BEGIN CERTIFICATE-----\n'
                b'%s\n'
                b'-----END CERTIFICATE-----'
            ) % cert
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
    if not isinstance(key, crypto.PKey):
        if b'PRIVATE KEY' not in key:
            key = (
                b'-----BEGIN PRIVATE KEY-----\n'
                b'%s\n'
                b'-----END PRIVATE KEY-----'
            ) % key
        key = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
    p12 = crypto.PKCS12()
    p12.set_certificate(cert)
    p12.set_privatekey(key)
    return p12.export(passphrase)
コード例 #30
0
ファイル: utils.py プロジェクト: yucaizhx/cryptokit
def generate_pfx(certificate,
                 friendly_name,
                 private_key,
                 passphrase=None,
                 iterations=2048):
    """Generate pfx.

    :param obj certificate: certificate
    """
    if not isinstance(certificate, crypto.X509):
        certificate = crypto.X509().from_cryptography(certificate)

    if not isinstance(private_key, crypto.PKey):
        private_key = crypto.PKey().from_cryptography_key(private_key)

    if not isinstance(friendly_name, bytes):
        friendly_name = friendly_name.encode('utf-8')

    pkcs12 = crypto.PKCS12()
    pkcs12.set_certificate(certificate)
    pkcs12.set_friendlyname(friendly_name)
    pkcs12.set_privatekey(private_key)

    return pkcs12.export(passphrase=passphrase, iter=iterations, maciter=1)