Python cryptography.hazmat.primitives.asymmetric.rsa 模块,generate_private_key() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用cryptography.hazmat.primitives.asymmetric.rsa.generate_private_key()

项目:requests-http-signature    作者:kislyuk    | 项目源码 | 文件源码
def test_rsa(self):
        from cryptography.hazmat.backends import default_backend
        from cryptography.hazmat.primitives.asymmetric import rsa
        from cryptography.hazmat.primitives import serialization
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        private_key_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.BestAvailableEncryption(passphrase)
        )
        public_key_pem = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        url = 'http://example.com/path?query#fragment'
        auth = HTTPSignatureAuth(algorithm="rsa-sha256", key=private_key_pem, key_id="sekret", passphrase=passphrase)
        self.session.get(url, auth=auth, headers=dict(pubkey=base64.b64encode(public_key_pem)))
项目:kolla-ansible    作者:openstack    | 项目源码 | 文件源码
def generate_RSA(bits=4096):
    new_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend()
    )
    private_key = new_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    public_key = new_key.public_key().public_bytes(
        encoding=serialization.Encoding.OpenSSH,
        format=serialization.PublicFormat.OpenSSH
    )
    return private_key, public_key
项目:kolla-ansible    作者:openstack    | 项目源码 | 文件源码
def generate_RSA(bits=4096):
    new_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend()
    )
    private_key = new_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    public_key = new_key.public_key().public_bytes(
        encoding=serialization.Encoding.OpenSSH,
        format=serialization.PublicFormat.OpenSSH
    )
    return private_key, public_key
项目:Chaos    作者:Chaosthebot    | 项目源码 | 文件源码
def create_decryptor(private_location, public_location):
    try:
        with open(private_location, "rb") as key_file:
            private_key = serialization.load_pem_private_key(
                key_file.read(),
                password=None,
                backend=default_backend()
            )
    except FileNotFoundError:
        with open(private_location, "wb") as key_file:
            private_key = rsa.generate_private_key(
                public_exponent=65537,
                key_size=2048,
                backend=default_backend()
            )
            key_file.write(private_key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.TraditionalOpenSSL,
                encryption_algorithm=serialization.NoEncryption()
            ))

    with open(public_location, "wb") as public_file:
        public_key = private_key.public_key()
        pem = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        public_file.write(pem)

    def decrypt(ciphertext):
        return private_key.decrypt(
            ciphertext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )

    return decrypt
项目:scitokens    作者:scitokens    | 项目源码 | 文件源码
def test_cache_timer(self):
        """
        Test if the cache max-age is retrieved from the HTTPS resource
        """
        private_key = generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        public_numbers = private_key.public_key().public_numbers()
        test_id = "thisisatestid"
        server_address = create_webserver.start_server(public_numbers.n, public_numbers.e, test_id)
        print(server_address)

        _, cache_timer = self.keycache._get_issuer_publickey("http://localhost:{}/".format(server_address[1]),
                                            key_id=test_id,
                                            insecure=True)

        self.assertEqual(cache_timer, 3600)
        create_webserver.shutdown_server()
项目:Parlay    作者:PromenadeSoftware    | 项目源码 | 文件源码
def generate_keys(self):
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )

        private_pem = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.BestAvailableEncryption(bytes(CloudLinkSettings.PRIVATE_KEY_PASSPHRASE))
        )
        public_pem = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        with open(CloudLinkSettings.PRIVATE_KEY_LOCATION, 'w') as key_file:
            key_file.write(str(private_pem))

        with open(CloudLinkSettings.PUBLIC_KEY_LOCATION, 'w') as key_file:
            key_file.write(str(public_pem))
项目:ComBunqWebApp    作者:OGKevin    | 项目源码 | 文件源码
def create_rsa_key():
        # generate private key
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )

        # output PEM encoded version of private key
        privateKey = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        )

        return privateKey.decode()
项目:zeus    作者:getsentry    | 项目源码 | 文件源码
def generate_key():
    # generate private/public key pair
    key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048)

    # get public key in OpenSSH format
    public_key = key.public_key().public_bytes(
        serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH
    )

    # get private key in PEM container format
    pem = key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption()
    )

    return KeyPair(pem.decode('utf-8'), public_key.decode('utf-8'))
项目:trustme    作者:python-trio    | 项目源码 | 文件源码
def __init__(self):
        self._private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=_KEY_SIZE,
            backend=default_backend()
        )

        name = _name(u"Testing CA #" + random_text())
        self._certificate = (
            _cert_builder_common(name, name, self._private_key.public_key())
            .add_extension(
                x509.BasicConstraints(ca=True, path_length=9), critical=True,
            )
            .sign(
                private_key=self._private_key,
                algorithm=hashes.SHA256(),
                backend=default_backend(),
            )
        )

        self.cert_pem = Blob(self._certificate.public_bytes(Encoding.PEM))
项目:virtapi    作者:spiperac    | 项目源码 | 文件源码
def generate_ssh_key():
    logging.info('NOTICE! Generating a new private/public key combination, be AWARE!')

    key = rsa.generate_private_key(
    backend=crypto_default_backend(),
    public_exponent=65537,
    key_size=2048
    )
    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.PKCS8,
        crypto_serialization.NoEncryption())
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    )

    with open("{}/keys/private.key".format(SETTINGS['RESOURCESDIR']), 'w') as content_file:
        content_file.write(private_key)
        chmod("{}/keys/private.key".format(SETTINGS['RESOURCESDIR']), 0600)
    with open("{}/keys/public.key".format(SETTINGS['RESOURCESDIR']), 'w') as content_file:
        content_file.write(public_key)
    return public_key
项目:cryptoverse-probe    作者:Cryptoverse    | 项目源码 | 文件源码
def generate_account(name='default'):
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    private_serialized = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    )
    public_serialized = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    )
    public_lines = public_serialized.splitlines()
    public_shrunk = ''
    for line in range(1, len(public_lines) - 1):
        public_shrunk += public_lines[line].strip('\n')

    return {
        'name': name,
        'private_key': private_serialized,
        'public_key': public_shrunk
    }
项目:cloudbridge    作者:ms-azure-cloudbroker    | 项目源码 | 文件源码
def gen_key_pair():
    """
    This method generates the public and private key pair.
    The public key format is OpenSSH and private key format is PEM container
    :return:
    """

    private_key = rsa.generate_private_key(backend=default_backend(),
                                           public_exponent=65537,
                                           key_size=2048)

    public_key_str = private_key.public_key(). \
        public_bytes(serialization.Encoding.OpenSSH,
                     serialization.PublicFormat.OpenSSH).decode('utf-8')

    private_key_str = private_key. \
        private_bytes(encoding=serialization.Encoding.PEM,
                      format=serialization.PrivateFormat.TraditionalOpenSSL,
                      encryption_algorithm=serialization.NoEncryption()
                      ).decode('utf-8')

    return (private_key_str, public_key_str)
项目:apex    作者:opnfv    | 项目源码 | 文件源码
def make_ssh_key():
    """
    Creates public and private ssh keys with 1024 bit RSA encryption
    :return: private, public key
    """
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=1024
    )

    private_key = key.private_bytes(
        crypto_serialization.Encoding.PEM,
        crypto_serialization.PrivateFormat.PKCS8,
        crypto_serialization.NoEncryption())
    public_key = key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    )
    return private_key.decode('utf-8'), public_key.decode('utf-8')
项目:newsreap    作者:caronc    | 项目源码 | 文件源码
def genkeys(self, key_size=KeySize.NORMAL, password=None):
        """
        Generates a Private and Public Key set and returns them in a tuple
        (private, public)

        """

        self.private_key = rsa.generate_private_key(
            # The public exponent of the new key. Usually one of the small
            # Fermat primes 3, 5, 17, 257, 65537. If in doubt you should use
            # 65537. See http://www.daemonology.net/blog/2009-06-11-\
            #  cryptographic-right-answers.html
            public_exponent=65537,
            key_size=key_size,
            backend=default_backend()
        )

        # Generate our Public Key
        self.public_key = self.private_key.public_key()

        # Store our password; this will be used when we save our content
        # via it's searialized value later on
        self.password = password

        # Returns a (RSAPrivateKey, RSAPublicKey)
        return (self.private_key, self.public_key)
项目:privcount    作者:privcount    | 项目源码 | 文件源码
def generate_keypair(key_out_path):
    private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend())
    pem = private_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption())
    with open(key_out_path, 'wb') as outf:
        print >>outf, pem
项目:Steganography    作者:Ludisposed    | 项目源码 | 文件源码
def gen_key():
    private_key = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend()
    )
    return private_key
项目:py2p    作者:p2p-today    | 项目源码 | 文件源码
def generate_self_signed_cert(cert_file, key_file):
    # type: (Any, Any) -> None
    """Given two file-like objects, generate an SSL key and certificate

    Args:
        cert_file:  The certificate file you wish to write to
        key_file:   The key file you wish to write to
    """
    one_day = timedelta(1, 0, 0)
    private_key = rsa.generate_private_key(
        public_exponent=65537, key_size=2048, backend=default_backend())
    public_key = private_key.public_key()
    builder = x509.CertificateBuilder()
    builder = builder.subject_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
        ]))
    builder = builder.issuer_name(
        x509.Name([
            x509.NameAttribute(NameOID.COMMON_NAME, u'cryptography.io'),
        ]))
    builder = builder.not_valid_before(datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.today() + timedelta(365 * 10))
    builder = builder.serial_number(uuid4().int)
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=False, path_length=None),
        critical=True, )
    certificate = builder.sign(
        private_key=private_key,
        algorithm=hashes.SHA256(),
        backend=default_backend())

    key_file.write(
        private_key.private_bytes(
            Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()))
    cert_file.write(certificate.public_bytes(Encoding.PEM))
项目:sshaolin    作者:bucknerns    | 项目源码 | 文件源码
def generate_ssh_keys(
        cls, size=4096, passphrase=None, private_format=PrivateFormat.PKCS8,
        public_format=PublicFormat.OpenSSH, private_encoding=Encoding.PEM,
            public_encoding=Encoding.OpenSSH):
        """Generates a public and private rsa ssh key

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

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

        return SSHKey(
            public_key=key.public_key().public_bytes(
                public_encoding, public_format),
            private_key=key.private_bytes(
                Encoding.PEM, private_format, encryption))
项目:Complete-Bunq-API-Python-Wrapper    作者:PJUllrich    | 项目源码 | 文件源码
def create_random_privkey():
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )

        return private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()
项目:Complete-Bunq-API-Python-Wrapper    作者:PJUllrich    | 项目源码 | 文件源码
def create_new_key_pair(self, save_to_config=True):
        """Creates a new public/private key pair and saves them to the config file

        :return: Prints out a success message
        """
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )

        private_key_decoded = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()

        public_key_decoded = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        ).decode()

        print('New key pair was created')

        if save_to_config:
            self.config.set('key_private', private_key_decoded)
            self.config.set('key_public', public_key_decoded)
        else:
            print('\tNew Private Key: %s' % private_key_decoded)
            print('\tNew Public Key:  %s' % public_key_decoded)

        return private_key_decoded, public_key_decoded
项目:pyetesync    作者:etesync    | 项目源码 | 文件源码
def generate_key_pair(cls):
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=3072,
            backend=default_backend()
        )
        return AsymmetricKeyPair(
                private_key.private_bytes(encryption_algorithm=serialization.NoEncryption(),
                                          encoding=serialization.Encoding.DER,
                                          format=serialization.PrivateFormat.TraditionalOpenSSL),
                private_key.public_key().public_bytes(encoding=serialization.Encoding.DER,
                                                      format=serialization.PublicFormat.PKCS1))
项目:kolla-kubernetes    作者:openstack    | 项目源码 | 文件源码
def generate_RSA(bits=4096):
    # public_exponent set to 655537 is what pyCA recommends
    new_key = rsa.generate_private_key(public_exponent=65537,
                                       key_size=bits,
                                       backend=default_backend())
    # we strip trailing space for 1:1 compat with previous implementation
    private_key = new_key.private_bytes(
        encoding=Encoding.PEM,
        format=PrivateFormat.PKCS8,
        encryption_algorithm=NoEncryption())
    public_key = new_key.public_key().public_bytes(encoding=Encoding.OpenSSH,
                                                   format=PublicFormat.OpenSSH)
    return private_key, public_key
项目:kolla-kubernetes    作者:openstack    | 项目源码 | 文件源码
def generate_RSA(bits=4096):
    # public_exponent set to 655537 is what pyCA recommends
    new_key = rsa.generate_private_key(public_exponent=65537,
                                       key_size=bits,
                                       backend=default_backend())
    # we strip trailing space for 1:1 compat with previous implementation
    private_key = new_key.private_bytes(
        encoding=Encoding.PEM,
        format=PrivateFormat.PKCS8,
        encryption_algorithm=NoEncryption())
    public_key = new_key.public_key().public_bytes(encoding=Encoding.OpenSSH,
                                                   format=PublicFormat.OpenSSH)
    return private_key, public_key
项目:cursive    作者:openstack    | 项目源码 | 文件源码
def test_verify_signature_ECC(self, mock_get_pub_key):
        data = b'224626ae19824466f2a7f39ab7b80f7f'
        # test every ECC curve
        for curve in signature_utils.ECC_CURVES:
            key_type_name = 'ECC_' + curve.name.upper()
            try:
                signature_utils.SignatureKeyType.lookup(key_type_name)
            except exception.SignatureVerificationError:
                import warnings
                warnings.warn("ECC curve '%s' not supported" % curve.name)
                continue

            # Create a private key to use
            private_key = ec.generate_private_key(curve,
                                                  default_backend())
            mock_get_pub_key.return_value = private_key.public_key()
            for hash_name, hash_alg in signature_utils.HASH_METHODS.items():
                signer = private_key.signer(
                    ec.ECDSA(hash_alg)
                )
                signer.update(data)
                signature = base64.b64encode(signer.finalize())
                img_sig_cert_uuid = 'fea14bc2-d75f-4ba5-bccc-b5c924ad0693'
                verifier = signature_utils.get_verifier(None,
                                                        img_sig_cert_uuid,
                                                        hash_name, signature,
                                                        key_type_name)
                verifier.update(data)
                verifier.verify()
项目:cryptokit    作者:istommao    | 项目源码 | 文件源码
def generate_private_key(key_size):
        """Generate rsa private key."""
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=key_size,
            backend=default_backend()
        )
        return private_key
项目:django-autocert    作者:farrepa    | 项目源码 | 文件源码
def set_key(self):
        password = settings.ACCOUNT_KEY_PASSWORD.encode()
        key = rsa.generate_private_key(public_exponent=65537, key_size=settings.BITS, backend=default_backend())
        self.key = key.private_bytes(encoding=serialization.Encoding.PEM,
                                     format=serialization.PrivateFormat.TraditionalOpenSSL,
                                     encryption_algorithm=serialization.BestAvailableEncryption(password))
项目:parsec-cloud    作者:Scille    | 项目源码 | 文件源码
def generate_asym_key(size):
    assert size > 1023
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=size,
        backend=default_backend()
    )
    return RSAPrivateKey(private_key)
项目:2FAssassin    作者:maxwellkoh    | 项目源码 | 文件源码
def ca_file(tmpdir):
    """
    Create a valid PEM file with CA certificates and return the path.
    """
    key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    public_key = key.public_key()

    builder = x509.CertificateBuilder()
    builder = builder.subject_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
    ]))
    builder = builder.issuer_name(x509.Name([
        x509.NameAttribute(NameOID.COMMON_NAME, u"pyopenssl.org"),
    ]))
    one_day = datetime.timedelta(1, 0, 0)
    builder = builder.not_valid_before(datetime.datetime.today() - one_day)
    builder = builder.not_valid_after(datetime.datetime.today() + one_day)
    builder = builder.serial_number(int(uuid.uuid4()))
    builder = builder.public_key(public_key)
    builder = builder.add_extension(
        x509.BasicConstraints(ca=True, path_length=None), critical=True,
    )

    certificate = builder.sign(
        private_key=key, algorithm=hashes.SHA256(),
        backend=default_backend()
    )

    ca_file = tmpdir.join("test.pem")
    ca_file.write_binary(
        certificate.public_bytes(
            encoding=serialization.Encoding.PEM,
        )
    )

    return str(ca_file).encode("ascii")
项目:morango    作者:learningequality    | 项目源码 | 文件源码
def generate_new_key(self, keysize=2048):
        self._private_key = crypto_rsa.generate_private_key(
            public_exponent=65537,
            key_size=keysize,
            backend=crypto_backend,
        )
        self._public_key = self._private_key.public_key()
项目:scitokens    作者:scitokens    | 项目源码 | 文件源码
def test_empty(self):
        """
        Test when the keycache should be empty
        """
        # Stand up an HTTP server
        private_key = generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        public_numbers = private_key.public_key().public_numbers()
        test_id = "thisisatestid"
        server_address = create_webserver.start_server(public_numbers.n, public_numbers.e, test_id)
        print(server_address)
        # Now try to get the public key from the server
        pubkey_from_keycache = self.keycache.getkeyinfo("http://localhost:{}/".format(server_address[1]),
                                 test_id,
                                 insecure=True)

        # Now compare the 2 public keys
        public_pem = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        pubkey_pem_from_keycache = pubkey_from_keycache.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        self.assertEqual(public_pem, pubkey_pem_from_keycache)

        create_webserver.shutdown_server()
项目:scitokens    作者:scitokens    | 项目源码 | 文件源码
def test_populated(self):
        """
        Test when there should be some entries populated in the sqllite DB
        """
        # Create a pem encoded public key
        private_key = generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        public_key = private_key.public_key()
        public_pem = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        self.keycache.addkeyinfo("https://doesnotexists.com/", "blahstuff", public_key, cache_timer=60)

        # Now extract the just inserted key
        pubkey = self.keycache.getkeyinfo("https://doesnotexists.com/", "blahstuff")

        public_pem2 = pubkey.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        self.assertEqual(public_pem, public_pem2)

        # Make sure it errors with urlerror when it should not exist
        with self.assertRaises(URLError):
            self.keycache.getkeyinfo("https://doesnotexists.com/", "asdf")
项目:scitokens    作者:scitokens    | 项目源码 | 文件源码
def test_cache_update_time(self):
        """
        Test if the cache next_update works
        """
        # Create a pem encoded public key
        private_key = generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        public_key = private_key.public_key()
        public_pem = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        self.keycache.addkeyinfo("https://doesnotexists.com/", "blahstuff", public_key, cache_timer=60, next_update=-1)

        # Even though the cache is still valid, the next update is triggered
        # We should still get the key, even though the next update fails
        # (invalid url)
        pubkey = self.keycache.getkeyinfo("https://doesnotexists.com/", "blahstuff")

        public_pem2 = pubkey.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )

        self.assertEqual(public_pem, public_pem2)
项目:scitokens    作者:scitokens    | 项目源码 | 文件源码
def setUp(self):
        self._private_key = generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        self._public_key = self._private_key.public_key()
        self._public_pem = self._public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        keycache = scitokens.utils.keycache.KeyCache.getinstance()
        keycache.addkeyinfo("local", "sample_key", self._private_key.public_key())
        self._token = scitokens.SciToken(key = self._private_key, key_id="sample_key")
项目:scitokens    作者:scitokens    | 项目源码 | 文件源码
def test_public_key(self):
        """
        Test when the public key is provided to deserialize
        """

        token = scitokens.SciToken(key = self._private_key)
        serialized_token = token.serialize(issuer = "local")

        new_token = scitokens.SciToken.deserialize(serialized_token, public_key = self._public_pem, insecure = True)
        self.assertIsInstance(new_token, scitokens.SciToken)

        # With invalid key
        with self.assertRaises(ValueError):
            scitokens.SciToken.deserialize(serialized_token, insecure=True, public_key = "asdf".encode())

        # With a proper key, but not the right one
        private_key = generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )
        public_key = private_key.public_key()
        pem = public_key.public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        )
        with self.assertRaises(DecodeError):
            scitokens.SciToken.deserialize(serialized_token, insecure=True, public_key = pem)
项目:seedbox    作者:nailgun    | 项目源码 | 文件源码
def generate_rsa_keypair(key_size=2048):
    key = rsa.generate_private_key(public_exponent=65537, key_size=key_size, backend=default_backend())
    public_key = key.public_key()
    public = public_key.public_bytes(encoding=serialization.Encoding.PEM,
                                     format=serialization.PublicFormat.SubjectPublicKeyInfo)
    private = key.private_bytes(encoding=serialization.Encoding.PEM,
                                format=serialization.PrivateFormat.TraditionalOpenSSL,
                                encryption_algorithm=serialization.NoEncryption())
    return public, private
项目:seedbox    作者:nailgun    | 项目源码 | 文件源码
def create_ca_certificate(cn, key_size=4096, certify_days=365):
    key = rsa.generate_private_key(public_exponent=65537, key_size=key_size, backend=default_backend())
    key_id = x509.SubjectKeyIdentifier.from_public_key(key.public_key())

    subject = issuer = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)])

    now = datetime.datetime.utcnow()
    serial = x509.random_serial_number()
    cert = x509.CertificateBuilder() \
        .subject_name(subject) \
        .issuer_name(issuer) \
        .public_key(key.public_key()) \
        .serial_number(serial) \
        .not_valid_before(now) \
        .not_valid_after(now + datetime.timedelta(days=certify_days)) \
        .add_extension(key_id, critical=False) \
        .add_extension(x509.AuthorityKeyIdentifier(key_id.digest,
                                                   [x509.DirectoryName(issuer)],
                                                   serial),
                       critical=False) \
        .add_extension(x509.BasicConstraints(ca=True, path_length=0), critical=True) \
        .add_extension(x509.KeyUsage(digital_signature=True,
                                     content_commitment=False,
                                     key_encipherment=False,
                                     data_encipherment=False,
                                     key_agreement=False,
                                     key_cert_sign=True,
                                     crl_sign=True,
                                     encipher_only=False,
                                     decipher_only=False),
                       critical=True) \
        .sign(key, hashes.SHA256(), default_backend())

    cert = cert.public_bytes(serialization.Encoding.PEM)
    key = key.private_bytes(encoding=serialization.Encoding.PEM,
                            format=serialization.PrivateFormat.TraditionalOpenSSL,
                            encryption_algorithm=serialization.NoEncryption())
    return cert, key
项目:ComBunqWebApp    作者:OGKevin    | 项目源码 | 文件源码
def create_new_key_pair(self, save_to_config=True):
        """Creates a new public/private key pair and saves them to the config file

        :return: Prints out a success message
        """
        private_key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
        )

        private_key_decoded = private_key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()

        public_key_decoded = private_key.public_key().public_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PublicFormat.SubjectPublicKeyInfo
        ).decode()

        print('New key pair was created')

        if save_to_config:
            self.config.set('key_private', private_key_decoded)
            self.config.set('key_public', public_key_decoded)
        else:
            print('\tNew Private Key: %s' % private_key_decoded)
            print('\tNew Public Key:  %s' % public_key_decoded)

        return private_key_decoded, public_key_decoded
项目:acmeclient    作者:samjy    | 项目源码 | 文件源码
def generate_private_key(key_size=4096):
    """Generate a private key.
    """
    if key_size < 1024:
        raise ValueError("Key is too small!")

    return crypto_util.make_key(key_size)
项目:acmeclient    作者:samjy    | 项目源码 | 文件源码
def generate_client_key(key_size=4096, public_exponent=65537):
    """Generate a client key
    """
    return acme.jose.JWKRSA(key=rsa.generate_private_key(
        public_exponent=public_exponent,
        key_size=key_size,
        backend=default_backend(),
    ))
项目:YATE    作者:GarethNelson    | 项目源码 | 文件源码
def make_keypair():
    return rsa.generate_private_key(
        public_exponent=65537,
        key_size=1024,
        backend=default_backend())
项目:certproxy    作者:geneanet    | 项目源码 | 文件源码
def create_privatekey(pkey_file):
    """ Create a private key """
    pkey = rsa.generate_private_key(
        public_exponent=65537,
        key_size=2048,
        backend=default_backend()
    )
    with open(pkey_file, 'wb') as f:
        f.write(pkey.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption()
        ))
    return pkey
项目:zeus    作者:getsentry    | 项目源码 | 文件源码
def private_key():
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.backends import default_backend

    return rsa.generate_private_key(backend=default_backend(), public_exponent=65537, key_size=2048)
项目:wile    作者:costela    | 项目源码 | 文件源码
def get_or_gen_key(ctx, account_key_path, new_account_key_size):
    account_key_path = os.path.expanduser(account_key_path)
    if os.path.exists(account_key_path):
        logger.debug('opening existing account key %s', account_key_path)
        with open(account_key_path, 'rb') as key_file:
            key_contents = key_file.read()
            try:
                try:
                    account_key = jose.JWKRSA(key=serialization.load_pem_private_key(key_contents, None,
                                              default_backend()))
                except TypeError:  # password required
                    password = click.prompt('Password for %s' % account_key_path, hide_input=True, default=None)
                    key = serialization.load_pem_private_key(key_contents, password.encode('utf-8'), default_backend())
                    account_key = jose.JWKRSA(key=key)
            except ValueError as e:
                logger.error('could not open key %s: %s', account_key_path, e)
                ctx.exit(1)
    else:
        logger.warn('no account key found; creating a new %d bit key in %s', new_account_key_size, account_key_path)
        account_key = jose.JWKRSA(key=rsa.generate_private_key(
            public_exponent=65537,
            key_size=new_account_key_size,
            backend=default_backend()))
        try:
            os.makedirs(os.path.dirname(account_key_path), 0o750)
        except os.error:
            pass  # dir already exists

        encryption_algorithm = ask_for_password_or_no_crypto(account_key_path)
        with open(account_key_path, 'wb') as key_file:
            key_file.write(account_key.key.private_bytes(
                encoding=serialization.Encoding.PEM,
                format=serialization.PrivateFormat.PKCS8,
                encryption_algorithm=encryption_algorithm
            ))
    return account_key
项目:py-ipv8    作者:qstokkink    | 项目源码 | 文件源码
def generate_primes(key_size=512):
    """
    Generate some primes. Key size in bits (minimum 512).
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa
    private_key = rsa.generate_private_key(public_exponent=65537,key_size=key_size,backend=default_backend())
    private_numbers = private_key.private_numbers()
    return min(private_numbers.p, private_numbers.q), max(private_numbers.p, private_numbers.q)
项目:telemetry-analysis-service    作者:mozilla    | 项目源码 | 文件源码
def rsa_key():
    key = rsa.generate_private_key(
        backend=crypto_default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    return key.public_key().public_bytes(
        crypto_serialization.Encoding.OpenSSH,
        crypto_serialization.PublicFormat.OpenSSH
    ).decode('utf-8')
项目:autocert    作者:mozilla-it    | 项目源码 | 文件源码
def _create_key(common_name, **kwargs):
    app.logger.info('called create_key:\n{0}'.format(pformat(locals())))
    key = rsa.generate_private_key(
        public_exponent=kwargs.get('public_exponent', CFG.key.public_exponent),
        key_size=kwargs.get('key_size', CFG.key.key_size),
        backend=default_backend())
    return key
项目:autocert    作者:mozilla-it    | 项目源码 | 文件源码
def _create_key(common_name, **kwargs):
    app.logger.info('called create_key:\n{0}'.format(pformat(locals())))
    key = rsa.generate_private_key(
        public_exponent=kwargs.get('public_exponent', CFG.key.public_exponent),
        key_size=kwargs.get('key_size', CFG.key.key_size),
        backend=default_backend())
    return key
项目:autocert    作者:mozilla-it    | 项目源码 | 文件源码
def _create_key(common_name, **kwargs):
    app.logger.info('called create_key:\n{0}'.format(pformat(locals())))
    key = rsa.generate_private_key(
        public_exponent=kwargs.get('public_exponent', CFG.key.public_exponent),
        key_size=kwargs.get('key_size', CFG.key.key_size),
        backend=default_backend())
    return key
项目:autocert    作者:mozilla-it    | 项目源码 | 文件源码
def _create_key(common_name, **kwargs):
    app.logger.info('called create_key:\n{0}'.format(pformat(locals())))
    key = rsa.generate_private_key(
        public_exponent=kwargs.get('public_exponent', CFG.key.public_exponent),
        key_size=kwargs.get('key_size', CFG.key.key_size),
        backend=default_backend())
    return key
项目:komlogd    作者:komlog-io    | 项目源码 | 文件源码
def generate_rsa_key(key_size=4096):
    privkey = rsa.generate_private_key(
        public_exponent=65537,
        key_size=key_size,
        backend=default_backend()
    )
    return privkey