コード例 #1
0
 def check_create_complete(self, cookie):
     if not cookie:
         raise Exception('No CA and no instructions for building one either')
     else:
         pkcs12 = crypto.load_pkcs12(base64.b64decode(cookie), "")
         logger.debug(pkcs12.get_certificate().get_subject() == crypto.load_pkcs12(base64.b64decode(self.myAttributes['ServerPKCS12'])).get_certificate().get_subject())
         return pkcs12.get_certificate().get_subject() == crypto.load_pkcs12(base64.b64decode(self.myAttributes['ServerPKCS12'])).get_certificate().get_subject()
コード例 #2
0
ファイル: admin.py プロジェクト: gao7ios/G7Platform
    def save(self, commit=True):

        p12file = self.cleaned_data.get("p12file")
        p12password = self.cleaned_data.get("p12password")
        useSandbox = self.cleaned_data.get("use_sandbox")
        if useSandbox == None:
            useSandbox = True
        pushProfile = super(G7PushProfileCreationForm, self).save(commit=commit)
        if p12file != None:
            fileContent = p12file.file.read()
            if isinstance(p12file.file, InMemoryUploadedFile):
                fileContent = p12file.file.getvalue()
            if p12password != None and p12password != "":
                p12 = crypto.load_pkcs12(fileContent, p12password)
            else:
                p12 = crypto.load_pkcs12(fileContent)

            privateIdentifier = str(uuid.uuid3(uuid.uuid4(),str(time.time())).hex)
            publicIdentifier = str(uuid.uuid3(uuid.uuid4(),str(time.time())).hex)
            pushProfile.identifier = str(uuid.uuid3(uuid.uuid4(),str(time.time())).hex)
            pushProfile.private_pem_file.save(privateIdentifier,ContentFile(crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())))
            pushProfile.public_pem_file.save(publicIdentifier,ContentFile(crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())))
            pushProfile.useSandbox = useSandbox
        if commit:
            pushProfile.save()

        return pushProfile
コード例 #3
0
def createSignature(hash, signingCertificatePkcs12, signingCertificatePassword):
    # see also in AM: src/crypto-lib/signature.cpp / Signature::create()

    s = SMIME.SMIME()

    # M2Crypto has no support for PKCS#12, so we have to use pyopenssl here
    # to load the .p12. Since the internal structures are incompatible, we
    # have to export from pyopenssl and import to M2Crypto via PEM BIOs.
    pkcs12 = load_pkcs12(signingCertificatePkcs12, signingCertificatePassword)
    signKey = BIO.MemoryBuffer(dump_privatekey(FILETYPE_PEM, pkcs12.get_privatekey()))
    signCert = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, pkcs12.get_certificate()))
    caCerts = X509.X509_Stack()
    if pkcs12.get_ca_certificates():
        for cert in pkcs12.get_ca_certificates():
            bio = BIO.MemoryBuffer(dump_certificate(FILETYPE_PEM, cert))
            caCerts.push(X509.load_cert_bio(bio, X509.FORMAT_PEM))

    bioHash = BIO.MemoryBuffer(hash)

    s.load_key_bio(signKey, signCert)
    s.set_x509_stack(caCerts)
    signature = s.sign(bioHash, SMIME.PKCS7_DETACHED + SMIME.PKCS7_BINARY)
    bioSignature = BIO.MemoryBuffer()
    signature.write(bioSignature)

    data = bioSignature.read_all()
    return data
コード例 #4
0
ファイル: signer.py プロジェクト: zongxiao/unionpay
 def loadPKCS12(filepath, password):
     '''
     @filepath: the pfx file path
     @password: the password of pfx file
     '''
     f = open(filepath, 'rb').read()
     return crypto.load_pkcs12(f, password)
コード例 #5
0
ファイル: certutils.py プロジェクト: hackedbellini/stoq
    def get_certs(self):
        """Get the certificate and its key in a temporary file.

        This will separate the certificate and the key in temporary files.
        The path to those files will be yielded in the context, and then
        removed from the file system.

        Note that this only works for PKCS12 since there's no way to extract
        the private key from a PKCS11 token.

        :returns: (cert_file_path, key_file_path)
        """
        # This is not supported for PKCS11 yet (and maybe it will never be)
        assert self._cert_type == Certificate.TYPE_PKCS12

        with open(cert_path[self._cert_type], 'rb') as f:
            pkcs12 = crypto.load_pkcs12(f.read(), self._get_password())

        with tempfile.NamedTemporaryFile(delete=False) as cert_file:
            cert_file.write(crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                    pkcs12.get_certificate()))
        with tempfile.NamedTemporaryFile(delete=False) as key_file:
            key_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                                  pkcs12.get_privatekey()))

        yield (cert_file.name, key_file.name)

        os.unlink(cert_file.name)
        os.unlink(key_file.name)
コード例 #6
0
def assina_xml(xml_string, pfx_certificate, password):

    pkcs12 = crypto.load_pkcs12(open(pfx_certificate, 'rb').read(), password)
    cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate())
    key_str = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())

    signer = signxml.XMLSigner(
        method=signxml.methods.enveloped, signature_algorithm="rsa-sha1",
        digest_algorithm='sha1',
        c14n_algorithm='http://www.w3.org/TR/2001/REC-xml-c14n-20010315')

    root = ElementTree.fromstring(xml_string.encode())
    objeto_xml = objectify.fromstring(xml_string.encode())

    chave_acesso = objeto_xml.infNFe.attrib.get('Id')

    signed_root = signer.sign(
        data=root,
        key=key_str,
        cert=cert_str,
        reference_uri=('#%s' % chave_acesso))

    signed_xml = ElementTree.tostring(signed_root).decode()
    signed_xml = signed_xml.replace('ds:', '').replace(':ds', '').replace('ns0:', '').replace(':ns0', '').replace(
        ':ns1', '').replace('ns1:', '')
    return signed_xml
コード例 #7
0
ファイル: certificado.py プロジェクト: ElissandroMendes/PyNFe
 def separar_arquivo(self, senha, caminho=False):
     """Separa o arquivo de certificado em dois: de chave e de certificado,
     e retorna a string. Se caminho for True grava na pasta temporaria e retorna
     o caminho dos arquivos, apos o uso devem ser excluidos com o metodo excluir."""
     
     # Carrega o arquivo .pfx, erro pode ocorrer se a senha estiver errada ou formato invalido.
     pkcs12 = crypto.load_pkcs12(open(self.caminho_arquivo, "rb").read(), senha)
     
     if caminho:
         cert = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate())
         chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
         # cria arquivos temporarios
         with tempfile.NamedTemporaryFile(delete=False) as arqcert:
             arqcert.write(cert)
         with tempfile.NamedTemporaryFile(delete=False) as arqchave:
             arqchave.write(chave)
         self.arquivos_temp.append(arqchave.name)
         self.arquivos_temp.append(arqcert.name)
         return arqchave.name, arqcert.name
     else:
         # Certificado
         cert = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate()).decode('utf-8')
         cert = cert.replace('\n', '')
         cert = cert.replace('-----BEGIN CERTIFICATE-----', '')
         cert = cert.replace('-----END CERTIFICATE-----', '')
         
         # Chave, string decodificada da chave privada
         chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
         
         return chave, cert
コード例 #8
0
ファイル: settings_window.py プロジェクト: akubera/AliMaster
        def on_password(pas):
            password_prompt.destroy()
            password = pas.get().encode()

            try:
                p12 = crypto.load_pkcs12(open(cerfile, 'rb').read(), password)
            except crypto.Error as e:
                print(e)
                print(e.args[0])
                # for x in dir(e):
                # print(x, e.__getattribute__(x))
                messagebox.showerror("Bad Password",
                                     "Error reading file:\n %s" % e)
                return

            certificate = p12.get_certificate()
            pkey = p12.get_privatekey()

            owner = certificate.get_subject().get_components()[-1]
            print(owner)
            outdir = path.dirname(cerfile)
            msg = "Generate certificate and key for\n%s\n in \
                   directory\n%s?" % (owner[1].decode(), outdir)
            agree = messagebox.askyesno("Generate Files", msg)

            if not agree:
                return

            pemtype = crypto.FILETYPE_PEM

            with open(path.join(outdir, 'usacert.pem'), 'wb') as cert:
                cert.write(crypto.dump_certificate(pemtype, certificate))

            with open(path.join(outdir, 'usakey.pem'), 'wb') as key:
                key.write(crypto.dump_privatekey(pemtype, pkey))
コード例 #9
0
ファイル: client.py プロジェクト: Wursthupe/pki15ca
 def dataReceived(self, data):
     print "Server said:", data
     data_json = json.loads(data)
     print "JSON: ", data_json
     
     cert_data = data_json["certdata"]
     f = open("test_client.pfx","w") #opens file with name of "test.txt"
     f.write(cert_data)
     f.close()
     
     # load certificate data and print something
     pkcs12 = crypto.load_pkcs12(data)
     x509 = pkcs12.get_certificate()
     
     subject = x509.get_subject()
     
     # list of (name, value) tuples
     subComponents = subject.get_components()
     for (name, value) in subComponents:
         print name + " is " + value
         
     #print subject
     #print subject.der()
     
     self.transport.loseConnection()
コード例 #10
0
def extract_pem_certificate():

    path_file = sys.argv[1]
    password = sys.argv[2]

    try:
        certificate = open(path_file, "r").read()
    except IOError:
        print u"Não foi possível encontrar o arquivo."
        return False

    try:
        cert = crypto.load_pkcs12(certificate, password)
    except crypto.Error:
        print u"Senha incorreta para o certificado."
        return False

    private_key = cert.get_privatekey()
    x509 = cert.get_certificate()
    cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM, x509)
    key_pem = crypto.dump_privatekey(crypto.FILETYPE_PEM, private_key)

    generate_pem_file(cert_pem, "certificate.pem")
    generate_pem_file(key_pem, "private_key.pem")

    print "Certificado e chave privada extraídos com Sucesso."
    return True
コード例 #11
0
def convert_p12_to_pem(p12file):
    from OpenSSL import crypto

    with open(p12file, "rb") as f:
        p12 = crypto.load_pkcs12(f.read(), "notasecret")

    return crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
コード例 #12
0
ファイル: signurl.py プロジェクト: mengyazhu96/gsutil
def _ReadKeystore(ks_contents, passwd):
  ks = load_pkcs12(ks_contents, passwd)
  client_email = (ks.get_certificate()
                  .get_subject()
                  .CN.replace('.apps.googleusercontent.com',
                              '@developer.gserviceaccount.com'))

  return ks.get_privatekey(), client_email
コード例 #13
0
    def _load_p12(self, p12_password):
        """
        Load .p12 cert to memory

        :param p12_password: (string) password for the .p12 file
        :return: None
        """
        self.p12 = crypto.load_pkcs12(buffer=file(self.p12_path, 'rb').read(), passphrase=p12_password)
        self._store_temp_files()
コード例 #14
0
ファイル: certificado.py プロジェクト: Anferi/PySPED
    def assina_texto(self, texto):
        #
        # Carrega o arquivo do certificado
        #
        pkcs12 = crypto.load_pkcs12(open(self.arquivo, 'rb').read(), self.senha)

        assinatura = crypto.sign(pkcs12.get_privatekey(), texto, 'sha1')

        return base64.encode(assinatura)
コード例 #15
0
ファイル: views.py プロジェクト: stfluckly29/Django-Angular
    def add_cert(self, request, pk=None):
        app = self.get_object()
        cert_file = request.FILES.get('cert_file', False)
        cert_type = request.DATA.get('cert_type', False)
        pwd = request.DATA.get('password', '')
        file_name = _get_random_name()
        if not cert_file:
            return Response({'errors': 'certificate file should be provided.'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            temp_str = cert_file.read()
            p12 = crypto.load_pkcs12(temp_str, pwd)
            cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_certificate())
            key_str = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey())
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_str)
            details = {}
            for key, val in cert.get_subject().get_components():
                details[key] = val
            bundle_name = details['UID']
            expiry_date = datetime.strptime(cert.get_notAfter(), '%Y%m%d%H%M%Sz')
            expiry_date = expiry_date.strftime('%b %d %H:%M:%S %Y GMT')
        except Exception as e:
            print str(e)
            return Response({"errors": 'Certificate is invalid. Double check that you input correct password.'},
                            status=status.HTTP_400_BAD_REQUEST)
        if cert_type == 'product':
            if Certificate.objects.filter(app=app, cert_type=True).count() > 0:
                return Response({'errors': 'Product certification file is already exist.'},
                                status=status.HTTP_400_BAD_REQUEST)
            if 'Production' not in details['CN']:
                return Response({'errors': 'This is not production certificate.'}, status=status.HTTP_400_BAD_REQUEST)
        elif cert_type == 'develop':
            if Certificate.objects.filter(app=app, cert_type=False).count() > 0:
                return Response({'errors': 'Development certification file is already existed.'},
                                status=status.HTTP_400_BAD_REQUEST)
            if 'Development' not in details['CN']:
                return Response({'errors': 'This is not development certificate.'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response({'errors': 'Certificate type is missed.'}, status=status.HTTP_400_BAD_REQUEST)

        path = os.path.join(settings.BASE_DIR, 'certs/', file_name)
        path_cert = os.path.join(settings.BASE_DIR, 'certs/', file_name+'_cert.pem')
        path_key = os.path.join(settings.BASE_DIR, 'certs/', file_name+'_key.pem')
        with open(path, 'wb+') as temp_file:
            for chunk in cert_file.chunks():
                temp_file.write(chunk)

        with open(path_cert, 'wb+') as temp_file:
            temp_file.write(cert_str)

        with open(path_key, 'wb+') as temp_file:
            temp_file.write(key_str)

        cert = Certificate(cert_type=(cert_type == 'product'), file_name=file_name, app=app, name=cert_file.name,
                           expiry_date=expiry_date, bundle_identifier=bundle_name)
        cert.save()

        return Response({'cert': CertificateSerializer(cert).data})
コード例 #16
0
    def __init__(self, der_location):
	self.isPrivate = True
	self.keydata = open(der_location).read()

	try:
            self.cert = crypto.load_pkcs12(self.keydata, "").get_certificate()
        except crypto.Error:
            self.isPrivate = False
            self.cert = crypto.load_certificate( crypto.FILETYPE_ASN1, self.keydata)
コード例 #17
0
ファイル: __init__.py プロジェクト: MichiganLabs/flask-gsa
    def init_app(self, app):
        certfile = app.config[self.key_prefix + '_PK_FILE']
        pk_password = app.config[self.key_prefix + '_PK_PASSWORD']
        email = app.config[self.key_prefix + '_EMAIL']
        with open(certfile, 'rb') as fp:
            private_key = fp.read()

        # Try to read certificate. If password is wrong, the app will fail to
        # start up.
        load_pkcs12(private_key, pk_password).get_certificate()

        state = _GSAState(private_key, pk_password, email)

        if not hasattr(app, 'extensions'):  # pragma: no cover, old flask
            app.extensions = {}
        if 'gsa' not in app.extensions:
            app.extensions['gsa'] = {}
        app.extensions['gsa'][self] = state
コード例 #18
0
ファイル: certificado.py プロジェクト: Anferi/PySPED
    def prepara_certificado_arquivo_pfx(self):
        # Lendo o arquivo pfx no formato pkcs12 como binário
        pkcs12 = crypto.load_pkcs12(open(self.arquivo, 'rb').read(), self.senha)

        # Retorna a string decodificada da chave privada
        self.chave = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())

        # Retorna a string decodificada do certificado
        self.prepara_certificado_txt(crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate()))
コード例 #19
0
def extract_cert_and_key_from_pfx(pfx, password):
    pfx = crypto.load_pkcs12(pfx, password)
    # PEM formatted private key
    key = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                 pfx.get_privatekey())
    # PEM formatted certificate
    cert = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                   pfx.get_certificate())
    return cert, key
コード例 #20
0
ファイル: __init__.py プロジェクト: danimaribeiro/PyTrustNFe
def sign_tag(certificado, **kwargs):
    pkcs12 = crypto.load_pkcs12(certificado.pfx, certificado.password)
    key = pkcs12.get_privatekey()
    if 'nfse' in kwargs:
        for item in kwargs['nfse']['lista_rps']:
            signed = crypto.sign(key, item['assinatura'], 'SHA1')
            item['assinatura'] = b64encode(signed)
    if 'cancelamento' in kwargs:
        signed = crypto.sign(key, kwargs['cancelamento']['assinatura'], 'SHA1')
        kwargs['cancelamento']['assinatura'] = b64encode(signed)
コード例 #21
0
ファイル: letsencrypt.py プロジェクト: Igorshp/letsencrypt.py
def gen_signature(key, payload, protected):
    message =  "{}.{}".format(encode_dict(protected),encode_dict(payload))
    key = load_key(key_filename)
    if key.startswith('-----BEGIN '):
        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
    else:
        pkey = crypto.load_pkcs12(key).get_privatekey()
    print pkey
    sign = OpenSSL.crypto.sign(pkey, message, "sha256") 
    return _b64(sign)
コード例 #22
0
def get_certificate_from_publish_settings(publish_settings_path, path_to_write_certificate, subscription_id=None):
    '''
    Writes a certificate file to the specified location.  This can then be used 
    to instantiate ServiceManagementService.  Returns the subscription ID.

    publish_settings_path: 
        Path to subscription file downloaded from 
        http://go.microsoft.com/fwlink/?LinkID=301775
    path_to_write_certificate:
        Path to write the certificate file.
    subscription_id:
        (optional)  Provide a subscription id here if you wish to use a 
        specific subscription under the publish settings file.
    '''
    import base64

    try:
        from xml.etree import cElementTree as ET
    except ImportError:
        from xml.etree import ElementTree as ET

    try:
        import OpenSSL.crypto as crypto
    except:
        raise Exception("pyopenssl is required to use get_certificate_from_publish_settings")

    _validate_not_none('publish_settings_path', publish_settings_path)
    _validate_not_none('path_to_write_certificate', path_to_write_certificate)

    # parse the publishsettings file and find the ManagementCertificate Entry
    tree = ET.parse(publish_settings_path)
    subscriptions = tree.getroot().findall("./PublishProfile/Subscription")
    
    # Default to the first subscription in the file if they don't specify
    # or get the matching subscription or return none.
    if subscription_id:
        subscription = next((s for s in subscriptions if s.get('Id').lower() == subscription_id.lower()), None)
    else:
        subscription = subscriptions[0]

    # validate that subscription was found
    if subscription is None:
        raise ValueError("The provided subscription_id '{}' was not found in the publish settings file provided at '{}'".format(subscription_id, publish_settings_path))

    cert_string = _decode_base64_to_bytes(subscription.get('ManagementCertificate'))

    # Load the string in pkcs12 format.  Don't provide a password as it isn't encrypted.
    cert = crypto.load_pkcs12(cert_string, b'') 

    # Write the data out as a PEM format to a random location in temp for use under this run.
    with open(path_to_write_certificate, 'wb') as f:
        f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert.get_certificate()))
        f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, cert.get_privatekey()))

    return subscription.get('Id')
コード例 #23
0
ファイル: jddefray.py プロジェクト: hereischen/jdpay
    def openssl_load_pkcs12_certs(self, cert_path, passphrase):
        with open(cert_path, 'rb') as f:
            c = f.read()
        pkcs7 = load_pkcs12(c, passphrase)
        # type_ 是 FILETYPE_PEM 或者 FILETYPE_ASN1 (for DER)
        type_ = FILETYPE_PEM
        p7_certificate = dump_certificate(type_, pkcs7.get_certificate())
        p7_private_key = dump_privatekey(type_, pkcs7.get_privatekey())
        # get CSR fields
        # csr_fields = pkcs7.get_certificate().get_subject().get_components()

        return p7_certificate, p7_private_key
コード例 #24
0
    def test_x509_der(self):
        p12 = load_pkcs12(self.pkcs12_data, self.pkcs12_password_bytes)
        cert_bytes = p12.get_certificate().to_cryptography().public_bytes(Encoding.DER)
        pk_bytes = p12.get_privatekey().to_cryptography_key().private_bytes(Encoding.DER, PrivateFormat.PKCS8, NoEncryption())
        adapter = X509Adapter(max_retries=3, cert_bytes=cert_bytes, pk_bytes=pk_bytes, encoding=Encoding.DER)
        self.session.mount('https://', adapter)
        recorder = get_betamax(self.session)
        with recorder.use_cassette('test_x509_adapter_der'):
            r = self.session.get('https://pkiprojecttest01.dev.labs.internal/', verify=False)

        assert r.status_code == 200
        assert r.text
コード例 #25
0
ファイル: certificado.py プロジェクト: Anferi/PySPED
    def verifica_assinatura_texto(self, texto, assinatura):
        #
        # Carrega o arquivo do certificado
        #
        pkcs12 = crypto.load_pkcs12(open(self.arquivo, 'rb').read(), self.senha)

        try:
            crypto.verify(pkcs12.get_certificate(), assinatura, texto, 'sha1')
        except:
            return False

        return True
コード例 #26
0
ファイル: ssl.py プロジェクト: jputrino/f5-common-python
        def from_PKCS12_data(self, pkcs12_data=None, import_passphrase=None):
            if len(pkcs12_data):
                if not import_passphrase:
                    raise Exception("PKCS12 requires a import password.")

                try:
                    pkcspackage = crypto.load_pkcs12(  # @UndefinedVariable
                        pkcs12_data,
                        import_passphrase
                    )
                except crypto.Error as error:  # @UndefinedVariable
                    if "mac verify failure" in error.message[0]:
                        raise Exception(
                            "import passphrase for PKCS12 was incorrect"
                        )
                    else:
                        raise
                x509cert = pkcspackage.get_certificate()
                tm = list(
                    time.strptime(
                        x509cert.get_notAfter()[:8], "%Y%m%d"
                    )
                )[:6]
                tm.append(0)
                tm.append(None)

                self.subject_cn = \
                    x509cert.get_subject().__getattribute__('CN')
                self.serial_number = int(x509cert.get_serial_number())
                self.certificate_data = \
                    crypto.dump_certificate(  # @UndefinedVariable
                        crypto.FILETYPE_PEM,  # @UndefinedVariable
                        x509cert
                    )
                self.expiration_date = datetime(*tm).date()
                self.issuer_cn = \
                    x509cert.get_issuer().__getattribute__('CN')
                self.version = int(x509cert.get_version())

                private_key = pkcspackage.get_privatekey()
                self.key_data = crypto.dump_privatekey(  # @UndefinedVariable
                    crypto.FILETYPE_PEM,  # @UndefinedVariable
                    private_key
                )
                self.bit_length = int(private_key.bits())
                self.key_passphrase_required = False
                self.key_passphrase = None

                if not self.certificate_id:
                    self.id_from_subject_cn()

            else:
                raise Exception("PKCS12 data must not be None")
コード例 #27
0
ファイル: xmlutils.py プロジェクト: hackedbellini/stoq
    def _get_key_cert(self, cert, password):
        with open(cert, 'rb') as f:
            pkcs12 = crypto.load_pkcs12(f.read(), str(password))

        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                             pkcs12.get_privatekey())
        key = load_pem_private_key(private_key, password=None, backend=default_backend())

        cert = crypto.dump_certificate(crypto.FILETYPE_PEM, pkcs12.get_certificate())
        cert = b'\n'.join(cert.split(b'\n')[1:-2])

        return key, cert
コード例 #28
0
def load_certificate(cert_file):
    from OpenSSL import crypto, SSL
    p12 = crypto.load_pkcs12(file(cert_file, 'rb').read())

    class CtxFactory(ssl.ClientContextFactory):
        def getContext(self):
            self.method = SSL.SSLv23_METHOD
            ctx = ssl.ClientContextFactory.getContext(self)
            ctx.use_certificate(p12.get_certificate())
            ctx.use_privatekey(p12.get_privatekey())
            return ctx

    return CtxFactory
コード例 #29
0
ファイル: convert_key.py プロジェクト: fragaria/gapi
def _main():
    if len(sys.argv) < 2:
        _usage()
        sys.exit(1)
    archive = load_pkcs12(open(sys.argv[1], 'rb').read(), 'notasecret')
    key = archive.get_privatekey()
    pem = dump_privatekey(FILETYPE_PEM, key)
    if len(sys.argv) > 2:
        f = open(sys.argv[2], 'wb')
        f.write(pem)
        f.close()
    else:
        print pem
コード例 #30
0
def converte_pfx_pem(caminho, senha):
    if not os.path.isfile(caminho):
        raise Exception('Certificado não existe')
    stream = open(caminho, 'rb').read()
    try:
        certificado = crypto.load_pkcs12(stream, senha)
        
        privada = crypto.dump_privatekey(crypto.FILETYPE_PEM, certificado.get_privatekey())    
        certificado = crypto.dump_certificate(crypto.FILETYPE_PEM, certificado.get_certificate())
    except Exception as e:
        if len(e.message) == 1 and len(e.message[0])==3 and e.message[0][2] == 'mac verify failure':
            raise Exception('Senha inválida')        
        raise
    return privada, certificado
コード例 #31
0
    def load_cert_pk12(self, filecontent):
        try:
            p12 = crypto.load_pkcs12(filecontent, self.dec_pass)
        except:
            raise UserError('Error al abrir la firma, posiblmente ha ingresado\
 mal la clave de la firma o el archivo no es compatible.')

        cert = p12.get_certificate()
        privky = p12.get_privatekey()
        cacert = p12.get_ca_certificates()
        issuer = cert.get_issuer()
        subject = cert.get_subject()

        self.not_before = datetime.strptime(
            cert.get_notBefore().decode("utf-8"), '%Y%m%d%H%M%SZ')
        self.not_after = datetime.strptime(cert.get_notAfter().decode("utf-8"),
                                           '%Y%m%d%H%M%SZ')

        # self.final_date =
        self.subject_c = subject.C
        self.subject_title = subject.title
        self.subject_common_name = subject.CN
        self.subject_serial_number = subject.serialNumber
        self.subject_email_address = subject.emailAddress

        self.issuer_country = issuer.C
        self.issuer_organization = issuer.O
        self.issuer_common_name = issuer.CN
        self.issuer_serial_number = issuer.serialNumber
        self.issuer_email_address = issuer.emailAddress

        self.cert_serial_number = cert.get_serial_number()
        self.cert_signature_algor = cert.get_signature_algorithm()
        self.cert_version = cert.get_version()
        self.cert_hash = cert.subject_name_hash()

        # data privada
        self.private_key_bits = privky.bits()
        self.private_key_check = privky.check()
        self.private_key_type = privky.type()
        # self.cacert = cacert

        certificate = p12.get_certificate()
        private_key = p12.get_privatekey()

        self.priv_key = crypto.dump_privatekey(type_, private_key)
        self.cert = crypto.dump_certificate(type_, certificate)

        self.dec_pass = False
コード例 #32
0
ファイル: sri_xades_type.py プロジェクト: hc-mic29/odoolec
    def action_validate_and_load(self):
        filecontent = base64.b64decode(self.file_content)
        try:
            p12 = crypto.load_pkcs12(filecontent, self.password)
        except Exception as ex:
            _logger.warning(tools.ustr(ex))
            raise UserError(
                _("Error opening the signature, possibly the signature key has been entered incorrectly or the file is not supported. \n%s"
                  ) % (tools.ustr(ex)))

        private_key = self.convert_key_cer_to_pem(filecontent, self.password)
        start_index = private_key.find("Signing Key")
        # cuando el archivo tiene mas de una firma electronica
        # viene varias secciones con BEGIN ENCRYPTED PRIVATE KEY
        # diferenciandose por:
        # * Decryption Key
        # * Signing Key
        # asi que tomar desde Signing Key en caso de existir
        if start_index >= 0:
            private_key = private_key[start_index:]
        start_index = private_key.find("-----BEGIN ENCRYPTED PRIVATE KEY-----")
        private_key = private_key[start_index:]
        cert = self._extract_x509(p12)
        issuer = cert.get_issuer()
        subject = cert.get_subject()
        vals = {
            "emision_date":
            datetime.strptime(cert.get_notBefore().decode("utf-8"),
                              "%Y%m%d%H%M%SZ"),
            "expire_date":
            datetime.strptime(cert.get_notAfter().decode("utf-8"),
                              "%Y%m%d%H%M%SZ"),
            "subject_common_name":
            subject.CN,
            "subject_serial_number":
            subject.serialNumber,
            "issuer_common_name":
            issuer.CN,
            "cert_serial_number":
            cert.get_serial_number(),
            "cert_version":
            cert.get_version(),
            "private_key":
            private_key,
            "state":
            "valid",
        }
        self.write(vals)
        return True
コード例 #33
0
 def p12parse(self):
     ''' parse p12 cert and get the cert / priv key for requests module '''
     # open it, using password. Supply/read your own from stdin.
     p12 = crypto.load_pkcs12(open(self.p12, 'rb').read(), self.pwd)
     # grab the certs / keys
     p12cert = p12.get_certificate()  # (signed) certificate object
     p12private = p12.get_privatekey()  # private key.
     # dump private key and cert
     symphony_key = crypto.dump_privatekey(crypto.FILETYPE_PEM, p12private)
     symphony_crt = crypto.dump_certificate(crypto.FILETYPE_PEM, p12cert)
     # write tmpfiles
     crtpath = self.write_tmpfile(symphony_crt)
     keypath = self.write_tmpfile(symphony_key)
     # return cert and privkey
     return crtpath, keypath
コード例 #34
0
ファイル: xmlutils.py プロジェクト: ComradeHadi/stoq
    def _get_key_cert(self, cert, password):
        with open(cert, 'rb') as f:
            pkcs12 = crypto.load_pkcs12(f.read(), str(password))

        private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                             pkcs12.get_privatekey())
        key = load_pem_private_key(private_key,
                                   password=None,
                                   backend=default_backend())

        cert = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                       pkcs12.get_certificate())
        cert = '\n'.join(cert.split('\n')[1:-2])

        return key, cert
コード例 #35
0
def pkcs12_key_as_pem(private_key_text, private_key_password):
    """Convert the contents of a PKCS12 key to PEM using OpenSSL.

    Args:
        private_key_text: String. Private key.
        private_key_password: String. Password for PKCS12.

    Returns:
        String. PEM contents of ``private_key_text``.
    """
    decoded_body = base64.b64decode(private_key_text)
    private_key_password = _to_bytes(private_key_password)

    pkcs12 = crypto.load_pkcs12(decoded_body, private_key_password)
    return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey())
コード例 #36
0
def pkcs12_data(cert_file, password):
    if six.PY3:
        password = password.encode('utf-8')
    with open(cert_file, 'rb') as fp:
        content_pkcs12 = crypto.load_pkcs12(fp.read(), password)
    pkey = content_pkcs12.get_privatekey()
    cert_X509 = content_pkcs12.get_certificate()
    key_str = crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey)
    cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM, cert_X509)
    return {
        'key_str': key_str,
        'cert_str': cert_str,
        'key': pkey,
        'cert': cert_X509,
    }
コード例 #37
0
 def _get_certificate_private_key_and_thumbnail(self, cert_path,
                                                cert_password):
     with open(cert_path, 'rb') as cert_file:
         pkcs12 = crypto.load_pkcs12(cert_file.read(), cert_password)
     private_key = pkcs12.get_privatekey() \
         .to_cryptography_key()  \
         .private_bytes(
             serialization.Encoding.PEM,
             serialization.PrivateFormat.PKCS8,
             serialization.NoEncryption())
     thumbprint = pkcs12.get_certificate() \
         .digest('sha1') \
         .decode() \
         .replace(':', '')
     return private_key, thumbprint
コード例 #38
0
ファイル: crypt.py プロジェクト: sprig/CUPS-Cloud-Print
  def from_string(key, password='******'):
    """Construct a Signer instance from a string.

    Args:
      key: string, private key in P12 format.
      password: string, password for the private key file.

    Returns:
      Signer instance.

    Raises:
      OpenSSL.crypto.Error if the key can't be parsed.
    """
    pkey = crypto.load_pkcs12(key, password).get_privatekey()
    return Signer(pkey)
コード例 #39
0
 def signMessage(self, message):
     """
         Signs the message using the private key with sha1 as digest
     """
     privateKeyFile = open(self._privateKey, 'rb')
     try:
         p12 = crypto.load_pkcs12(privateKeyFile.read(),
                                  self._password.encode("utf-8"))
         privateKey = p12.get_privatekey()
         sign = crypto.sign(privateKey, message.encode("utf-8"), 'SHA256')
         privateKeyFile.close()
         return util.base64Encode(sign)
     except:
         privateKeyFile.close()
         raise Exception("Error Reading the key file")
コード例 #40
0
ファイル: Server.py プロジェクト: hugo-cmac/MIETI
 def __init__(self):
     self.p12 = crypto.load_pkcs12(
         open("Cliente1.p12", 'rb').read(), "1234")
     self.cert_pem = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                             self.p12.get_certificate())
     self.private_key = serialization.load_pem_private_key(
         crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                self.p12.get_privatekey()), None,
         default_backend())
     self.trusted_cert = crypto.load_certificate(
         crypto.FILETYPE_PEM,
         crypto.dump_certificate(
             crypto.FILETYPE_PEM,
             crypto.load_certificate(crypto.FILETYPE_ASN1,
                                     open("CA.cer", 'rb').read())))
コード例 #41
0
def firmar(msg, p12):
    """ Firma un mensaje con el archivo p12 indicado
        Args:
            msg (str): Cadena a firmar
            p12 (str): Cadena de ubicacion del archivo p12 con el que se firmara msg
        
        Returns:
            str: Una cadena con el mensaje y la firma concatenados
    """
    p12 = crypto.load_pkcs12(open(p12, "rb").read(), "12345678")
    private_key = p12.get_privatekey()
    sign = crypto.sign(private_key, msg, "sha384")
    stringQR = "".join(',' + str(int(x)) for x in bytearray(sign))
    resp = msg + '(' + stringQR[1:] + ')'
    return resp
コード例 #42
0
    def extrair_certificado_a1(self,arquivo,senha):
        '''
        Extrai o conteúdo do certificado A1
        @param arquivo:caminho para o arquivo .pfx
        @param senha: senha do certificado.
        @return: dicionário com a string do certificado e da chave privada. 
        '''
        
        conteudo_pkcs12 = crypto.load_pkcs12(file(arquivo, 'rb').read(), senha)
      
        key = crypto.dump_privatekey(crypto.FILETYPE_PEM, conteudo_pkcs12.get_privatekey())

        cert = crypto.dump_certificate(crypto.FILETYPE_PEM, conteudo_pkcs12.get_certificate())

        return{'cert':cert,'key':key}
コード例 #43
0
    def load_cert_pk12(self, filecontent):
        try:
            p12 = crypto.load_pkcs12(filecontent, self.dec_pass)
        except UserError:
            raise UserError(
                _("Error when opening the signature. You may have entered the "
                  "wrong key or the file is not compatible."))

        cert = p12.get_certificate()
        privky = p12.get_privatekey()
        issuer = cert.get_issuer()
        subject = cert.get_subject()

        self.not_before = datetime.strptime(
            cert.get_notBefore().decode("utf-8"), "%Y%m%d%H%M%SZ").date()
        self.not_after = datetime.strptime(cert.get_notAfter().decode("utf-8"),
                                           "%Y%m%d%H%M%SZ").date()

        # self.final_date =
        self.subject_c = subject.C
        self.subject_title = subject.title
        self.subject_common_name = subject.CN
        self.subject_serial_number = subject.serialNumber
        self.subject_email_address = subject.emailAddress

        self.issuer_country = issuer.C
        self.issuer_organization = issuer.O
        self.issuer_common_name = issuer.CN
        self.issuer_serial_number = issuer.serialNumber
        self.issuer_email_address = issuer.emailAddress

        self.cert_serial_number = cert.get_serial_number()
        self.cert_signature_algor = cert.get_signature_algorithm()
        self.cert_version = cert.get_version()
        self.cert_hash = cert.subject_name_hash()

        # data privada
        self.private_key_bits = privky.bits()
        self.private_key_check = privky.check()
        self.private_key_type = privky.type()
        # self.cacert = cacert

        certificate = p12.get_certificate()
        private_key = p12.get_privatekey()

        self.priv_key = crypto.dump_privatekey(type_, private_key)
        self.cert = crypto.dump_certificate(type_, certificate)
        self.dec_pass = False
コード例 #44
0
    def parse(self, module):
        """Read PKCS#12 file."""

        try:
            with open(self.src, 'rb') as pkcs12_fh:
                pkcs12_content = pkcs12_fh.read()
            p12 = crypto.load_pkcs12(pkcs12_content, self.passphrase)
            pkey = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                          p12.get_privatekey())
            crt = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                          p12.get_certificate())

            crypto_utils.write_file(module, b'%s%s' % (pkey, crt))

        except IOError as exc:
            raise PkcsError(exc)
コード例 #45
0
def create_pem_files(CERT_HOST, CERT_PASS, CERT_PEM_FILE, KEY_PEM_FILE):
    import os.path
    from emensageriapro.padrao import salvar_arquivo
    from OpenSSL import crypto

    pkcs12 = crypto.load_pkcs12(open(CERT_HOST, 'rb').read(), CERT_PASS)

    if not os.path.isfile(CERT_PEM_FILE):
        cert_str = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                           pkcs12.get_certificate())
        salvar_arquivo(CERT_PEM_FILE, cert_str)

    if not os.path.isfile(KEY_PEM_FILE):
        key_str = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                         pkcs12.get_privatekey())
        salvar_arquivo(KEY_PEM_FILE, key_str)
コード例 #46
0
ファイル: xmlutils.py プロジェクト: ComradeHadi/stoq
    def _create_tmp_cert(self, cert, password):
        with open(cert) as f:
            cert_file = f.read()

        # Reads the file in pkcs12 format how binary.
        pkcs12 = crypto.load_pkcs12(cert_file, password)
        cert = pkcs12.get_certificate()
        key = pkcs12.get_privatekey()
        p12 = crypto.PKCS12()
        p12.set_privatekey(key)
        p12.set_certificate(cert)

        with tempfile.NamedTemporaryFile(delete=False) as tmp_cert:
            tmp_cert.write(p12.export())

        return tmp_cert.name
コード例 #47
0
    def load_cert_pk12(self, filecontent):

        p12 = crypto.load_pkcs12(filecontent, self.dec_pass)

        cert = p12.get_certificate()
        privky = p12.get_privatekey()
        cacert = p12.get_ca_certificates()
        issuer = cert.get_issuer()
        subject = cert.get_subject()

        self.not_before = datetime.datetime.strptime(
            cert.get_notBefore().decode("utf-8"), '%Y%m%d%H%M%SZ')
        self.not_after = datetime.datetime.strptime(
            cert.get_notAfter().decode("utf-8"), '%Y%m%d%H%M%SZ')

        # self.final_date =
        self.subject_c = subject.C
        self.subject_title = subject.title
        self.subject_common_name = subject.CN
        self.subject_serial_number = subject.serialNumber
        self.subject_email_address = subject.emailAddress

        self.issuer_country = issuer.C
        self.issuer_organization = issuer.O
        self.issuer_common_name = issuer.CN
        self.issuer_serial_number = issuer.serialNumber
        self.issuer_email_address = issuer.emailAddress
        self.status = 'expired' if cert.has_expired() else 'valid'

        self.cert_serial_number = cert.get_serial_number()
        self.cert_signature_algor = cert.get_signature_algorithm()
        self.cert_version = cert.get_version()
        self.cert_hash = cert.subject_name_hash()

        # data privada
        self.private_key_bits = privky.bits()
        self.private_key_check = privky.check()
        self.private_key_type = privky.type()
        # self.cacert = cacert

        certificate = p12.get_certificate()
        private_key = p12.get_privatekey()

        self.priv_key = crypto.dump_privatekey(type_, private_key)
        self.cert = crypto.dump_certificate(type_, certificate)

        self.dec_pass = False
コード例 #48
0
 def test_sign(self):
     root = parse_xml("data/unsigned-sample.xml")
     sign = root.xpath("//ds:Signature",
                       namespaces={"ds": xmlsig.constants.DSigNs})[0]
     policy = GenericPolicyId(
         "http://www.facturae.es/politica_de_firma_formato_facturae/"
         "politica_de_firma_formato_facturae_v3_1.pdf",
         u"Politica de Firma FacturaE v3.1",
         xmlsig.constants.TransformSha1,
     )
     ctx = XAdESContext(policy)
     with open(path.join(BASE_DIR, "data/keyStore.p12"), "rb") as key_file:
         ctx.load_pkcs12(crypto.load_pkcs12(key_file.read()))
     with patch("xades.policy.urllib.urlopen") as mock:
         mock.return_value = UrllibMock()
         ctx.sign(sign)
         ctx.verify(sign)
コード例 #49
0
 def send_method(self):
     if self.integration_id.method_id == self.env.ref(
             'l10n_es_facturae_face.integration_face'):
         invoice = self.integration_id.invoice_id
         cert = crypto.load_pkcs12(
             base64.b64decode(invoice.company_id.facturae_cert),
             invoice.company_id.facturae_cert_password)
         cert.set_ca_certificates(None)
         client = Client(
             wsdl=self.env["ir.config_parameter"].sudo().get_param(
                 "account.invoice.face.server", default=None),
             wsse=MemorySignature(
                 cert.export(),
                 base64.b64decode(
                     self.env.ref(
                         'l10n_es_facturae_face.face_certificate').datas)))
         invoice_file = client.get_type('ns0:FacturaFile')(
             self.integration_id.attachment_id.datas,
             self.integration_id.attachment_id.datas_fname,
             self.integration_id.attachment_id.mimetype)
         anexos_list = []
         if self.integration_id.attachment_ids:
             for attachment in self.integration_id.attachment_ids:
                 anexo = client.get_type('ns0:AnexoFile')(
                     attachment.datas, attachment.datas_fname,
                     attachment.mimetype)
                 anexos_list.append(anexo)
         anexos = client.get_type('ns0:ArrayOfAnexoFile')(anexos_list)
         invoice_call = client.get_type('ns0:EnviarFacturaRequest')(
             invoice.company_id.face_email, invoice_file, anexos)
         response = client.service.enviarFactura(invoice_call)
         self.result_code = response.resultado.codigo
         self.log = response.resultado.descripcion
         if self.result_code == '0':
             self.state = 'sent'
             integ = self.integration_id
             integ.register_number = response.factura.numeroRegistro
             integ.state = 'sent'
             integ.can_cancel = True
             integ.can_update = True
             integ.can_send = False
         else:
             self.integration_id.state = 'failed'
             self.state = 'failed'
         return
     return super(AccountInvoiceIntegration, self).send_method()
コード例 #50
0
ファイル: Certificado.py プロジェクト: esosaja/PyTrustNFe
def converte_pfx_pem(caminho, senha):
    if not os.path.isfile(caminho):
        raise Exception('Certificado não existe')
    stream = open(caminho, 'rb').read()
    try:
        certificado = crypto.load_pkcs12(stream, senha)

        privada = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                         certificado.get_privatekey())
        certificado = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                              certificado.get_certificate())
    except Exception as e:
        if len(e.message) == 1 and len(
                e.message[0]) == 3 and e.message[0][2] == 'mac verify failure':
            raise Exception('Senha inválida')
        raise
    return privada, certificado
コード例 #51
0
    def create_service_account_key(self, outputfile):
        '''create an service account key'''
        results = self._create_service_account_key(self.service_account_name,
                                                   outputfile, self.key_format)
        if results['returncode'] != 0:
            return results

        if self.key_format == 'p12':
            # we need to dump the private key out and return it
            from OpenSSL import crypto
            p12 = crypto.load_pkcs12(
                open(outputfile, 'rb').read(), 'notasecret')
            results['results'] = crypto.dump_privatekey(
                crypto.FILETYPE_PEM, p12.get_privatekey()).strip()
        else:
            results['results'] = json.load(open(outputfile))
        return results
コード例 #52
0
def sslTest():
    import ssl, socket
    from OpenSSL.crypto import load_pkcs12
    certfile = os.path.join(os.path.dirname(__file__), 'csclient.p12')
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    p12 = load_pkcs12(file(keyfile, 'rb').read(), 'elastos')
    cert = p12.get_certificate()
    key = p12.get_privatekey()
    try:
        conn = ssl.wrap_socket(sock,
                               certfile=certfile,
                               ssl_version=ssl.PROTOCOL_TLSv1,
                               cert_reqs=ssl.CERT_REQUIRED,
                               ca_certs=certfile)
        conn.connect(('192.168.5.37', 18080))
    except Exception, e:
        pass
コード例 #53
0
ファイル: helpers.py プロジェクト: cdezz/pharmacy_portal
def pfx_to_pem(pfx_path: str, pfx_password: str) -> str:
    ''' Decrypts the .pfx file to be used with requests. '''
    with tempfile.NamedTemporaryFile(suffix='.pem') as t_pem:
        f_pem = open(t_pem.name, 'wb')
        pfx = open(pfx_path, 'rb').read()
        p12 = crypto.load_pkcs12(pfx, pfx_password)
        f_pem.write(
            crypto.dump_privatekey(crypto.FILETYPE_PEM, p12.get_privatekey()))
        f_pem.write(
            crypto.dump_certificate(crypto.FILETYPE_PEM,
                                    p12.get_certificate()))
        ca = p12.get_ca_certificates()
        if ca is not None:
            for cert in ca:
                f_pem.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
        f_pem.close()
        yield t_pem.name
コード例 #54
0
def main():
    signer_pkey_filename = 'OpenSSLKeys/sign_key.pem'
    user_image_filename = 'user_bw.jpeg'
    qr_code_filename = 'user_qr.png'

    # Define QR code specification
    qr = qrcode.QRCode(
        version=40,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4,
    )

    # Create user data
    user_img = open(user_image_filename, "rb").read()
    user_name = "Alice Doe"
    user_date = "16052020-16082020"
    user_CID = "0x1fc60e1a4e238ac6cce9d79097a268af"
    user_certData = CertificateData(user_img, user_name, user_date, user_CID)

    # Load private key for signing user data
    key_file = open(signer_pkey_filename, "r")
    key = key_file.read()
    key_file.close()
    if key.startswith('-----BEGIN '):
        pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key)
    else:
        pkey = crypto.load_pkcs12(key).get_privatekey()

    # Get signed user certificate and build QR code
    signed_user_cert = user_certData.getSignedCertificateByteArray(pkey)

    qr.add_data(base64.b85encode(signed_user_cert))

    try:
        qr.make(fit=True)
    except qrcode.exceptions.DataOverflowError:
        print('User data too big for QR code. Please optimise image.')
        exit()

    qr_img = qr.make_image(fill_color="black", back_color="white")
    plt.imshow(qr_img, cmap='gray')
    plt.axis('off')
    plt.savefig(qr_code_filename, bbox_inches='tight')
    print('User QR code output to {}'.format(qr_code_filename))
    print('Done.')
コード例 #55
0
ファイル: ssl.py プロジェクト: swormke/f5-common-python
        def from_PKCS12_data(self, pkcs12_data=None, import_passphrase=None):
            if len(pkcs12_data):
                if not import_passphrase:
                    raise Exception("PKCS12 requires a import password.")

                try:
                    pkcspackage = crypto.load_pkcs12(  # @UndefinedVariable
                        pkcs12_data, import_passphrase)
                except crypto.Error as error:  # @UndefinedVariable
                    if "mac verify failure" in error.message[0]:
                        raise Exception(
                            "import passphrase for PKCS12 was incorrect")
                    else:
                        raise
                x509cert = pkcspackage.get_certificate()
                tm = list(time.strptime(x509cert.get_notAfter()[:8],
                                        "%Y%m%d"))[:6]
                tm.append(0)
                tm.append(None)

                self.subject_cn = \
                    x509cert.get_subject().__getattribute__('CN')
                self.serial_number = int(x509cert.get_serial_number())
                self.certificate_data = \
                    crypto.dump_certificate(  # @UndefinedVariable
                        crypto.FILETYPE_PEM,  # @UndefinedVariable
                        x509cert
                    )
                self.expiration_date = datetime(*tm).date()
                self.issuer_cn = \
                    x509cert.get_issuer().__getattribute__('CN')
                self.version = int(x509cert.get_version())

                private_key = pkcspackage.get_privatekey()
                self.key_data = crypto.dump_privatekey(  # @UndefinedVariable
                    crypto.FILETYPE_PEM,  # @UndefinedVariable
                    private_key)
                self.bit_length = int(private_key.bits())
                self.key_passphrase_required = False
                self.key_passphrase = None

                if not self.certificate_id:
                    self.id_from_subject_cn()

            else:
                raise Exception("PKCS12 data must not be None")
コード例 #56
0
ファイル: crypt.py プロジェクト: itielshwartz/BackendApi
    def pkcs12_key_as_pem(private_key_text, private_key_password):
        """Convert the contents of a PKCS12 key to PEM using OpenSSL.

        Args:
          private_key_text: String. Private key.
          private_key_password: String. Password for PKCS12.

        Returns:
          String. PEM contents of ``private_key_text``.
        """
        decoded_body = base64.b64decode(private_key_text)
        if isinstance(private_key_password, six.string_types):
            private_key_password = private_key_password.encode('ascii')

        pkcs12 = crypto.load_pkcs12(decoded_body, private_key_password)
        return crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                      pkcs12.get_privatekey())
コード例 #57
0
ファイル: __init__.py プロジェクト: robizd/fiskali
    def __init__(self, key, password):
        """
        Args:
        key (str): path to file holding your key. This file should be in pem format
        passwrod (str): password for key file
        cert (str): path to certificate file. This file should be in pem format
        trustcerts (str): path to file vhere are CA certificates in.pem format
        """

        p12 = crypto.load_pkcs12(open(key, 'rb').read(), password)

        self.init_error = []
        self.key = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                          p12.get_privatekey())
        self.password = password.encode()
        self.certificate = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                   p12.get_certificate())
コード例 #58
0
    def test_x509_pem(self):
        p12 = load_pkcs12(self.pkcs12_data, self.pkcs12_password_bytes)
        cert_bytes = p12.get_certificate().to_cryptography().public_bytes(Encoding.PEM)
        pk_bytes = p12.get_privatekey().\
                       to_cryptography_key().\
                       private_bytes(Encoding.PEM, PrivateFormat.PKCS8,
                                     BestAvailableEncryption(self.pkcs12_password_bytes))

        adapter = X509Adapter(max_retries=3, cert_bytes=cert_bytes,
                              pk_bytes=pk_bytes, password=self.pkcs12_password_bytes)
        self.session.mount('https://', adapter)
        recorder = get_betamax(self.session)
        with recorder.use_cassette('test_x509_adapter_pem'):
            r = self.session.get('https://pkiprojecttest01.dev.labs.internal/', verify=False)

        assert r.status_code == 200
        assert r.text
コード例 #59
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)
コード例 #60
0
ファイル: CertUtil.py プロジェクト: tumi8/sKnock
    def __init__(self, pfxFile, pfxPasswd):
        self.platform = PlatformUtils.detectPlatform()
        self.revokedCertificateSerials = None

        if (self.platform == PlatformUtils.LINUX):
            LOG.debug("Loading certificates...")
            try:
                LOG.debug("Loading certficate:" + pfxFile)
                pfx = crypto.load_pkcs12(file(pfxFile, 'rb').read(), pfxPasswd)

                self.loadCAFromPFX(pfx)
                self.certificate = pfx.get_certificate()
                self.privKey = pfx.get_privatekey()

            except:
                LOG.error("Failed to load certificates!")
                sys.exit("Failed to load certificates!")