Python OpenSSL.crypto.TYPE_RSA Examples

The following are 30 code examples of OpenSSL.crypto.TYPE_RSA(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module OpenSSL.crypto , or try the search function .
Example #1
Source File: test_sslverify.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def makeCertificate(**kw):
    keypair = PKey()
    keypair.generate_key(TYPE_RSA, 512)

    certificate = X509()
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365) # One year
    for xname in certificate.get_issuer(), certificate.get_subject():
        for (k, v) in kw.items():
            setattr(xname, k, v)

    certificate.set_serial_number(counter())
    certificate.set_pubkey(keypair)
    certificate.sign(keypair, "md5")

    return keypair, certificate 
Example #2
Source File: turnserver.py    From aioice with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_self_signed_cert(name="localhost"):
    from OpenSSL import crypto

    # create key pair
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    # create self-signed certificate
    cert = crypto.X509()
    cert.get_subject().CN = name
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10 * 365 * 86400)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(key)
    cert.sign(key, "sha1")

    with open(CERT_FILE, "wb") as fp:
        fp.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(KEY_FILE, "wb") as fp:
        fp.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) 
Example #3
Source File: server.py    From Loki with MIT License 6 votes vote down vote up
def gen_cert(self):
        key_pair = crypto.PKey()
        key_pair.generate_key(crypto.TYPE_RSA, 2048)

        cert = crypto.X509()
        cert.get_subject().O = 'Loki'
        cert.get_subject().CN = 'Sami'
        cert.get_subject().OU = 'Pure-L0G1C'
        cert.get_subject().C = 'US'
        cert.get_subject().L = 'Los Santos'
        cert.get_subject().ST = 'California'

        cert.set_serial_number(SystemRandom().randint(2048 ** 8, 4096 ** 8))
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(256 * 409600)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(key_pair)
        cert.sign(key_pair, 'sha256')

        with open(const.CERT_FILE, 'wb') as f:
            f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))

        with open(const.KEY_FILE, 'wb') as f:
            f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key_pair)) 
Example #4
Source File: test_sslverify.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeCertificate(**kw):
    keypair = PKey()
    keypair.generate_key(TYPE_RSA, 1024)

    certificate = X509()
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365) # One year
    for xname in certificate.get_issuer(), certificate.get_subject():
        for (k, v) in kw.items():
            setattr(xname, k, nativeString(v))

    certificate.set_serial_number(counter())
    certificate.set_pubkey(keypair)
    certificate.sign(keypair, "md5")

    return keypair, certificate 
Example #5
Source File: createPemFiles.py    From devopsloft with GNU General Public License v3.0 6 votes vote down vote up
def SelfSignedCertificate():
    # 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 = "IL"
    cert.get_subject().ST = "Jerusalem"
    cert.get_subject().L = "Jerusalem"
    cert.get_subject().OU = "DevOps Loft"
    cert.get_subject().CN = gethostname()
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_issuer(cert.get_subject())
    cert.set_pubkey(k)
    cert.sign(k, 'sha1')

    with open(CERT_FILE, "wb") as cert_f:
        cert_f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    with open(KEY_FILE, "wb") as key_f:
        key_f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) 
Example #6
Source File: ssl.py    From Slackor with GNU General Public License v3.0 6 votes vote down vote up
def generateImpacketCert(certname='/tmp/impacket.crt'):
    # Create a private key
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    # Create the certificate
    cert = crypto.X509()
    cert.gmtime_adj_notBefore(0)
    # Valid for 5 years
    cert.gmtime_adj_notAfter(60*60*24*365*5)
    subj = cert.get_subject()
    subj.CN = 'impacket'
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")
    # We write both from the same file
    with open(certname, 'w') as certfile:
        certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))
        certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))
    LOG.debug('Wrote certificate to %s' % certname)

# Class to wrap the client socket in SSL when serving as a SOCKS server 
Example #7
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeCertificate(**kw):
    keypair = PKey()
    keypair.generate_key(TYPE_RSA, 768)

    certificate = X509()
    certificate.gmtime_adj_notBefore(0)
    certificate.gmtime_adj_notAfter(60 * 60 * 24 * 365) # One year
    for xname in certificate.get_issuer(), certificate.get_subject():
        for (k, v) in kw.items():
            setattr(xname, k, nativeString(v))

    certificate.set_serial_number(counter())
    certificate.set_pubkey(keypair)
    certificate.sign(keypair, "md5")

    return keypair, certificate 
Example #8
Source File: certs.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def __init__(self, filename=None, text=None, passphrase=None,
                 filetype="pem", bits=2048, _key=None):
        self.__passphrase = passphrase  # can also be a callable
        if _key is not None:
            key = _key
        else:
            ftype = _FILETYPES[filetype]
            if filename is not None:
                ftype, text = get_type_and_text(filename)
            if text is not None:
                if passphrase is not None:
                    key = crypto.load_privatekey(ftype, text, passphrase)
                else:
                    key = crypto.load_privatekey(ftype, text)
            else:
                key = crypto.PKey()
                key.generate_key(crypto.TYPE_RSA, bits)
        key.check()
        self._key = key 
Example #9
Source File: test_crypto.py    From oss-ftp with MIT License 6 votes vote down vote up
def setUp(self):
        """
        Create a new private key and start a certificate request (for a test
        method to finish in one way or another).
        """
        super(X509ExtTests, self).setUp()
        # Basic setup stuff to generate a certificate
        self.pkey = PKey()
        self.pkey.generate_key(TYPE_RSA, 384)
        self.req = X509Req()
        self.req.set_pubkey(self.pkey)
        # Authority good you have.
        self.req.get_subject().commonName = "Yoda root CA"
        self.x509 = X509()
        self.subject = self.x509.get_subject()
        self.subject.commonName = self.req.get_subject().commonName
        self.x509.set_issuer(self.subject)
        self.x509.set_pubkey(self.pkey)
        now = b(datetime.now().strftime("%Y%m%d%H%M%SZ"))
        expire  = b((datetime.now() + timedelta(days=100)).strftime("%Y%m%d%H%M%SZ"))
        self.x509.set_notBefore(now)
        self.x509.set_notAfter(expire) 
Example #10
Source File: ssl.py    From Exchange2domain with MIT License 6 votes vote down vote up
def generateImpacketCert(certname='/tmp/impacket.crt'):
    # Create a private key
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)

    # Create the certificate
    cert = crypto.X509()
    cert.gmtime_adj_notBefore(0)
    # Valid for 5 years
    cert.gmtime_adj_notAfter(60*60*24*365*5)
    subj = cert.get_subject()
    subj.CN = 'impacket'
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")
    # We write both from the same file
    with open(certname, 'w') as certfile:
        certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8'))
        certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8'))
    LOG.debug('Wrote certificate to %s' % certname)

# Class to wrap the client socket in SSL when serving as a SOCKS server 
Example #11
Source File: authentication.py    From deskcon-desktop with GNU General Public License v3.0 6 votes vote down vote up
def generate_keypair(uuid):
    hostname = socket.gethostname()
    # create a key pair
    keypair = crypto.PKey()
    keypair.generate_key(crypto.TYPE_RSA, 2048)

    # create a self-signed cert
    cert = crypto.X509()
    cert.set_version(2)
    cert.get_subject().CN = str(uuid)+"/"+hostname
    cert.get_issuer().CN = str(uuid)+"/"+hostname
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(10*365*24*60*60)
    cert.set_pubkey(keypair)
    cert.sign(keypair, 'sha256')

    certificate = crypto.dump_certificate(crypto.FILETYPE_PEM, cert)
    privatekey = crypto.dump_privatekey(crypto.FILETYPE_PEM, keypair)
    return certificate, privatekey 
Example #12
Source File: test_certificate_resources.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def _do_pyopenssl_stored_key_request(self):
        self.order_meta.update(self.stored_key_meta)

        pkey = crypto.PKey()
        pkey.generate_key(crypto.TYPE_RSA, 2048)
        key_pem = crypto.dump_privatekey(
            crypto.FILETYPE_PEM, pkey)
        self.private_key_value = base64.b64encode(key_pem)
        self.public_key_value = "public_key"
        self.passphrase_value = None
        self.store_plugin.get_secret.side_effect = self.stored_key_side_effect

        self._test_should_return_waiting_for_ca(
            cert_res.issue_certificate_request)

        self._test_should_return_certificate_generated(
            cert_res.check_certificate_request) 
Example #13
Source File: test_certificate_resources.py    From sgx-kms with Apache License 2.0 6 votes vote down vote up
def test_should_return_for_pyopenssl_stored_key_with_extensions(self):
        self.order_meta.update(self.stored_key_meta)
        pkey = crypto.PKey()
        pkey.generate_key(crypto.TYPE_RSA, 2048)
        self.private_key_value = base64.b64encode(crypto.dump_privatekey(
            crypto.FILETYPE_PEM, pkey))

        self.store_plugin.get_secret.side_effect = self.stored_key_side_effect
        self.order_meta['extensions'] = 'my ASN.1 extensions structure here'
        # TODO(alee-3) Add real extensions data here

        self.result.status = cert_man.CertificateStatus.WAITING_FOR_CA

        cert_res.issue_certificate_request(self.order,
                                           self.project,
                                           self.result_follow_on)

        self._verify_issue_certificate_plugins_called()
        self.assertIsNotNone(self.order.order_barbican_meta['generated_csr'])

        # TODO(alee-3) Add tests to validate the request based on the validator
        # code that dave-mccowan is adding.
        # TODO(alee-3) Add tests to validate the extensions in the request 
Example #14
Source File: man_cert_setup.py    From aws-greengrass-mini-fulfillment with Apache License 2.0 5 votes vote down vote up
def create_group_cert(cli):
    k = crypto.PKey()
    k.generate_key(crypto.TYPE_RSA, 2048)  # generate RSA key-pair

    cert = crypto.X509()
    cert.get_subject().countryName = "US"
    cert.get_subject().stateOrProvinceName = "CA"
    cert.get_subject().organizationName = "mini-fulfillment"
    cert.get_subject().organizationalUnitName = "demo"
    cert.get_subject().commonName = "mini-fulfillment"
    cert.set_serial_number(1000)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(5 * 365 * 24 * 60 * 60)  # 5 year expiry date
    cert.set_issuer(cert.get_subject())  # self-sign this certificate
    cert.set_pubkey(k)
    san_list = ["IP:{0}".format(cli.ip_address)]
    extension_list = [
        crypto.X509Extension(type_name=b"basicConstraints",
                             critical=False, value=b"CA:false"),
        crypto.X509Extension(type_name=b"subjectAltName",
                             critical=True, value=", ".join(san_list)),
        # crypto.X509Extension(type_name=b"subjectKeyIdentifier",
        #                      critical=True, value=b"hash")
    ]
    cert.add_extensions(extension_list)
    cert.sign(k, 'sha256')

    prefix = str(cli.out_dir) + '/' + cli.group_name

    open("{0}-server.crt".format(prefix), 'wt').write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open("{0}-server-private.key".format(prefix), 'wt').write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey=k))
    open("{0}-server-public.key".format(prefix), 'wt').write(
        crypto.dump_publickey(crypto.FILETYPE_PEM, pkey=k)) 
Example #15
Source File: certificate_utils.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def create_csr_with_bad_subject_dn():
    """Generate a CSR that has a bad subject dn."""
    key_pair = create_key_pair(crypto.TYPE_RSA, 2048)
    csr = crypto.X509Req()
    subject = csr.get_subject()
    # server certs require attribute 'CN'
    setattr(subject, "UID", "bar")
    csr.set_pubkey(key_pair)
    csr.sign(key_pair, "sha256")
    pem = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    return pem 
Example #16
Source File: serving.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
def generate_adhoc_ssl_pair(cn=None):
    from random import random
    crypto = _get_openssl_crypto_module()

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = '*'

    cert = crypto.X509()
    cert.set_serial_number(int(random() * sys.maxsize))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)

    subject = cert.get_subject()
    subject.CN = cn
    subject.O = 'Dummy Certificate'

    issuer = cert.get_issuer()
    issuer.CN = 'Untrusted Authority'
    issuer.O = 'Self-Signed'

    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 1024)
    cert.set_pubkey(pkey)
    cert.sign(pkey, 'md5')

    return cert, pkey 
Example #17
Source File: utils.py    From spid-testenv2 with GNU Affero General Public License v3.0 5 votes vote down vote up
def generate_certificate(fname, path):
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)
    cert = crypto.X509()
    cert.get_subject().C = 'IT'
    cert.gmtime_adj_notBefore(-50 * 365 * 24 * 60 * 60)
    cert.gmtime_adj_notAfter(50 * 365 * 24 * 60 * 60)
    cert.set_pubkey(key)
    cert.sign(key, str('sha256'))
    open(os.path.join(path, '{}.crt'.format(fname)), "wb").write(
        crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
    open(os.path.join(path, '{}.key'.format(fname)), "wb").write(
        crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) 
Example #18
Source File: self_signed.py    From personal-backend with Apache License 2.0 5 votes vote down vote up
def create_self_signed_cert(cert_dir, name="mycroft"):
    """
    If name.crt and name.key don't exist in cert_dir, create a new
    self-signed cert and key pair and write them into that directory.
    """

    CERT_FILE = name + ".crt"
    KEY_FILE = name + ".key"
    cert_path = join(cert_dir, CERT_FILE)
    key_path = join(cert_dir, KEY_FILE)

    if not exists(join(cert_dir, CERT_FILE)) \
            or not exists(join(cert_dir, KEY_FILE)):
        # 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 = "PT"
        cert.get_subject().ST = "Europe"
        cert.get_subject().L = "Mountains"
        cert.get_subject().O = "Jarbas AI"
        cert.get_subject().OU = "Mycroft is <3"
        cert.get_subject().CN = gethostname()
        cert.set_serial_number(random.randint(0, 2000))
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(10 * 365 * 24 * 60 * 60)
        cert.set_issuer(cert.get_subject())
        cert.set_pubkey(k)
        cert.sign(k, 'sha1')
        if not exists(cert_dir):
            makedirs(cert_dir)
        open(cert_path, "wb").write(
            crypto.dump_certificate(crypto.FILETYPE_PEM, cert))
        open(join(cert_dir, KEY_FILE), "wb").write(
            crypto.dump_privatekey(crypto.FILETYPE_PEM, k))

    return cert_path, key_path 
Example #19
Source File: generate-certificates.py    From mpyc with MIT License 5 votes vote down vote up
def create_key(bits):
    """Create a public/private key pair."""
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, bits)
    return pkey 
Example #20
Source File: serving.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def generate_adhoc_ssl_pair(cn=None):
    from random import random
    crypto = _get_openssl_crypto_module()

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = '*'

    cert = crypto.X509()
    cert.set_serial_number(int(random() * sys.maxsize))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)

    subject = cert.get_subject()
    subject.CN = cn
    subject.O = 'Dummy Certificate'

    issuer = cert.get_issuer()
    issuer.CN = 'Untrusted Authority'
    issuer.O = 'Self-Signed'

    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)
    cert.set_pubkey(pkey)
    cert.sign(pkey, 'sha256')

    return cert, pkey 
Example #21
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def create_server_pair(self, o, cn, san=[]):
        """Issue a X.509 server key/certificate pair"""

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

        # cert
        cert = crypto.X509()
        cert.set_serial_number(self.__next_serial)
        cert.set_version(2)
        cert.set_pubkey(key)
        cert.gmtime_adj_notBefore(0)
        cert.gmtime_adj_notAfter(365*24*60*60)

        cert_subject = cert.get_subject()
        cert_subject.O = o
        cert_subject.OU = 'kOVHernetes'
        cert_subject.CN = cn
        cert.set_issuer(self.cert.get_issuer())

        cert_ext = []
        cert_ext.append(crypto.X509Extension(b'subjectKeyIdentifier', False, b'hash', cert))
        cert_ext.append(crypto.X509Extension(b'authorityKeyIdentifier', False, b'keyid,issuer:always', issuer=self.cert))
        cert_ext.append(crypto.X509Extension(b'basicConstraints', False, b'CA:FALSE'))
        cert_ext.append(crypto.X509Extension(b'keyUsage', True, b'digitalSignature, keyEncipherment'))
        cert_ext.append(crypto.X509Extension(b'extendedKeyUsage', True, b'serverAuth'))
        if san: cert_ext.append(crypto.X509Extension(b'subjectAltName', False, ','.join(san).encode()))
        cert.add_extensions(cert_ext)

        # sign cert with CA key
        cert.sign(self.key, 'sha256')

        type(self).__next_serial += 1

        return key, cert 
Example #22
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 5 votes vote down vote up
def generateCSR(cn, c, st, l, o, ou, email, sans):
    # TODO: support different kind/size keys???
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    csr = crypto.X509Req()
    csr.get_subject().CN = cn
    csr.get_subject().countryName = c
    csr.get_subject().stateOrProvinceName = st
    csr.get_subject().localityName = l
    csr.get_subject().organizationName = o
    csr.get_subject().organizationalUnitName = ou
    csr.get_subject().emailAddress = email
    # csr.get_subject().subjectAltName = 'test.example.com'

    x509_extensions = ([])

    # TODO: support "IP:" in addition to "DNS:" below
    sans_list = []
    for san in sans:
        sans_list.append("DNS: {0}".format(san))

    sans_list = ", ".join(sans_list).encode()

    if sans_list:
        x509_extensions.append(crypto.X509Extension("subjectAltName".encode(), False, sans_list))

    csr.add_extensions(x509_extensions)

    csr.set_pubkey(key)
    csr.sign(key, "sha256")

    csr_out = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    key_out = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

    return key_out,csr_out 
Example #23
Source File: generate_csr.py    From infra-ansible with Apache License 2.0 5 votes vote down vote up
def generateCSR(cn, c, st, l, o, ou, email, sans):
    # TODO: support different kind/size keys???
    key = crypto.PKey()
    key.generate_key(crypto.TYPE_RSA, 2048)

    csr = crypto.X509Req()
    csr.get_subject().CN = cn
    csr.get_subject().countryName = c
    csr.get_subject().stateOrProvinceName = st
    csr.get_subject().localityName = l
    csr.get_subject().organizationName = o
    csr.get_subject().organizationalUnitName = ou
    csr.get_subject().emailAddress = email
    # csr.get_subject().subjectAltName = 'test.example.com'

    x509_extensions = ([])

    # TODO: support "IP:" in addition to "DNS:" below
    sans_list = []
    for san in sans:
        sans_list.append("DNS: {0}".format(san))

    sans_list = ", ".join(sans_list).encode()

    if sans_list:
        x509_extensions.append(crypto.X509Extension("subjectAltName".encode(), False, sans_list))

    csr.add_extensions(x509_extensions)

    csr.set_pubkey(key)
    csr.sign(key, "sha256")

    csr_out = crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr)
    key_out = crypto.dump_privatekey(crypto.FILETYPE_PEM, key)

    return key_out,csr_out 
Example #24
Source File: test_ssl.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generateCertificateObjects(organization, organizationalUnit):
    """
    Create a certificate for given C{organization} and C{organizationalUnit}.

    @return: a tuple of (key, request, certificate) objects.
    """
    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 1024)
    req = crypto.X509Req()
    subject = req.get_subject()
    subject.O = organization
    subject.OU = organizationalUnit
    req.set_pubkey(pkey)
    req.sign(pkey, "md5")

    # Here comes the actual certificate
    cert = crypto.X509()
    cert.set_serial_number(1)
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60) # Testing certificates need not be long lived
    cert.set_issuer(req.get_subject())
    cert.set_subject(req.get_subject())
    cert.set_pubkey(req.get_pubkey())
    cert.sign(pkey, "md5")

    return pkey, req, cert 
Example #25
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def generate(Class, kind=crypto.TYPE_RSA, size=2048):
        pkey = crypto.PKey()
        pkey.generate_key(kind, size)
        return Class(pkey) 
Example #26
Source File: _sslverify.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def inspect(self):
        t = self.original.type()
        if t == crypto.TYPE_RSA:
            ts = 'RSA'
        elif t == crypto.TYPE_DSA:
            ts = 'DSA'
        else:
            ts = '(Unknown Type!)'
        L = (self.original.bits(), ts, self.keyHash())
        return '%s-bit %s Key Pair with Hash: %s' % L 
Example #27
Source File: serving.py    From scylla with Apache License 2.0 5 votes vote down vote up
def generate_adhoc_ssl_pair(cn=None):
    from random import random

    crypto = _get_openssl_crypto_module()

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = "*"

    cert = crypto.X509()
    cert.set_serial_number(int(random() * sys.maxsize))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)

    subject = cert.get_subject()
    subject.CN = cn
    subject.O = "Dummy Certificate"  # noqa: E741

    issuer = cert.get_issuer()
    issuer.CN = subject.CN
    issuer.O = subject.O  # noqa: E741

    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")

    return cert, pkey 
Example #28
Source File: serving.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def generate_adhoc_ssl_pair(cn=None):
    from random import random

    crypto = _get_openssl_crypto_module()

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = "*"

    cert = crypto.X509()
    cert.set_serial_number(int(random() * sys.maxsize))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)

    subject = cert.get_subject()
    subject.CN = cn
    subject.O = "Dummy Certificate"  # noqa: E741

    issuer = cert.get_issuer()
    issuer.CN = subject.CN
    issuer.O = subject.O  # noqa: E741

    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")

    return cert, pkey 
Example #29
Source File: serving.py    From Building-Recommendation-Systems-with-Python with MIT License 5 votes vote down vote up
def generate_adhoc_ssl_pair(cn=None):
    from random import random

    crypto = _get_openssl_crypto_module()

    # pretty damn sure that this is not actually accepted by anyone
    if cn is None:
        cn = "*"

    cert = crypto.X509()
    cert.set_serial_number(int(random() * sys.maxsize))
    cert.gmtime_adj_notBefore(0)
    cert.gmtime_adj_notAfter(60 * 60 * 24 * 365)

    subject = cert.get_subject()
    subject.CN = cn
    subject.O = "Dummy Certificate"  # noqa: E741

    issuer = cert.get_issuer()
    issuer.CN = subject.CN
    issuer.O = subject.O  # noqa: E741

    pkey = crypto.PKey()
    pkey.generate_key(crypto.TYPE_RSA, 2048)
    cert.set_pubkey(pkey)
    cert.sign(pkey, "sha256")

    return cert, pkey 
Example #30
Source File: ca.py    From kOVHernetes with Apache License 2.0 5 votes vote down vote up
def create_key(self):
        """Issue a X.509 key"""

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