def setUp(self): self.signing_digest = "sha256" # Set up CSR data csr_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backends.default_backend() ) csr = x509.CertificateSigningRequestBuilder().subject_name( x509.Name([ x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"test"), ])).sign(csr_key, hashes.SHA256(), backends.default_backend()) self.certificate_signing_request = csr.public_bytes( serialization.Encoding.PEM) # Set up keys self.ca_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backends.default_backend() ) self.ca_private_key_passphrase = b"Testing" self.ca_private_key = self.ca_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption( self.ca_private_key_passphrase), ) super(BaseLocalCSRTestCase, self).setUp()
def setUp(self): self.signing_digest = "sha256" # Set up CSR data csr_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backends.default_backend() ) csr = x509.CertificateSigningRequestBuilder().subject_name( x509.Name([ x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"test"), ])).sign(csr_key, hashes.SHA256(), backends.default_backend()) self.certificate_signing_request = csr.public_bytes( serialization.Encoding.PEM) # Set up CA data ca_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backends.default_backend() ) self.ca_private_key_passphrase = b"Testing" self.ca_private_key = ca_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption( self.ca_private_key_passphrase), ) ca_cert = x509.CertificateBuilder() valid_from_datetime = datetime.datetime.utcnow() valid_until_datetime = (datetime.datetime.utcnow() + datetime.timedelta( seconds=2 * 365 * 24 * 60 * 60)) ca_cert = ca_cert.not_valid_before(valid_from_datetime) ca_cert = ca_cert.not_valid_after(valid_until_datetime) ca_cert = ca_cert.serial_number(1) subject_name = x509.Name([ x509.NameAttribute(x509.oid.NameOID.COUNTRY_NAME, u"US"), x509.NameAttribute(x509.oid.NameOID.STATE_OR_PROVINCE_NAME, u"Oregon"), x509.NameAttribute(x509.oid.NameOID.LOCALITY_NAME, u"Springfield"), x509.NameAttribute(x509.oid.NameOID.ORGANIZATION_NAME, u"Springfield Nuclear Power Plant"), x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, u"maggie1"), ]) ca_cert = ca_cert.subject_name(subject_name) ca_cert = ca_cert.issuer_name(subject_name) ca_cert = ca_cert.public_key(ca_key.public_key()) signed_cert = ca_cert.sign(private_key=ca_key, algorithm=hashes.SHA256(), backend=backends.default_backend()) self.ca_certificate = signed_cert.public_bytes( encoding=serialization.Encoding.PEM) super(TestLocalGenerator, self).setUp()
def setUp(self): super().setUp() self.cur = mock.MagicMock() self.conn = conn = mock.MagicMock() self.conn.cursor.return_value = self.cur self.conn.login = '******' self.conn.password = '******' self.conn.schema = 'public' self.conn.extra_dejson = {'database': 'db', 'account': 'airflow', 'warehouse': 'af_wh', 'region': 'af_region', 'role': 'af_role'} class UnitTestSnowflakeHook(SnowflakeHook): conn_name_attr = 'snowflake_conn_id' def get_conn(self): return conn def get_connection(self, connection_id): return conn self.db_hook = UnitTestSnowflakeHook() self.nonEncryptedPrivateKey = "/tmp/test_key.pem" self.encryptedPrivateKey = "/tmp/test_key.p8" # Write some temporary private keys. First is not encrypted, second is with a passphrase. key = rsa.generate_private_key( backend=default_backend(), public_exponent=65537, key_size=2048 ) private_key = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) with open(self.nonEncryptedPrivateKey, "wb") as f: f.write(private_key) key = rsa.generate_private_key( backend=default_backend(), public_exponent=65537, key_size=2048 ) private_key = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( self.conn.password.encode())) with open(self.encryptedPrivateKey, "wb") as f: f.write(private_key)
def _dummy_key(algorithm): if algorithm == ALGO.RSA1024: return rsa.generate_private_key(65537, 1024, default_backend()) if algorithm == ALGO.RSA2048: return rsa.generate_private_key(65537, 2048, default_backend()) if algorithm == ALGO.ECCP256: return ec.generate_private_key(ec.SECP256R1(), default_backend()) if algorithm == ALGO.ECCP384: return ec.generate_private_key(ec.SECP384R1(), default_backend()) raise UnsupportedAlgorithm( 'Unsupported algorithm: %s' % algorithm, algorithm_id=algorithm)
def _generate_keys(cls): keys = {} keys['signature'] = rsa.generate_private_key( public_exponent = 65537, key_size = 4096, backend = CRYPTO_BACKEND ) keys['encryption'] = rsa.generate_private_key( public_exponent = 65537, key_size = 4096, backend = CRYPTO_BACKEND ) keys['exchange'] = ECDHPrivate() return keys
def set_private_key(config_obj, backend_obj): algorithm_name = config_obj.data['root_cert_config']['algorithm_name'] if algorithm_name == 'secp256r1': private_key_obj = ec.generate_private_key(ec.SECP256R1, backend_obj) elif algorithm_name == 'secp384r1': private_key_obj = ec.generate_private_key(ec.SECP384R1, backend_obj) elif algorithm_name == 'secp521r1': private_key_obj = ec.generate_private_key(ec.SECP521R1, backend_obj) elif algorithm_name == 'rsa2048': private_key_obj = rsa.generate_private_key(65537, 2048, backend_obj) elif algorithm_name == 'rsa4096': private_key_obj = rsa.generate_private_key(65537, 4096, backend_obj) else: private_key_obj = rsa.generate_private_key(65537, 4096, backend_obj) return private_key_obj
def setUp(self): self.example_xml_files = (os.path.join(os.path.dirname(__file__), "example.xml"), os.path.join(os.path.dirname(__file__), "example2.xml")) self.keys = dict(hmac=b"secret", rsa=rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()), dsa=dsa.generate_private_key(key_size=1024, backend=default_backend()), ecdsa=ec.generate_private_key(curve=ec.SECP384R1(), backend=default_backend()))
def gen_key(length=None, pub_exp=None, typ=None, raw=False, password=None): if not length: length = 4096 if not pub_exp: pub_exp = 65537 if not typ: typ = TYPE_RSA if isinstance(password, str): password = password.encode() if length not in _RSA_SUPPORTED_LENGTH: raise TypeError("Length must be one of '{}'".format(_RSA_SUPPORTED_LENGTH)) if pub_exp not in _RSA_SUPPORTED_EXP: raise TypeError("pub_exp must be one of '{}'".format(_RSA_SUPPORTED_EXP)) if typ != TYPE_RSA: raise TypeError("Only type '{}' supported".format(TYPE_RSA)) priv_key = rsa.generate_private_key(pub_exp, length, default_backend()) if raw: return priv_key else: if not password: encryption = serialization.NoEncryption() else: encryption = serialization.BestAvailableEncryption(password) priv_pem = priv_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=encryption) return priv_pem.decode()
def generate_key(self): ''' Generates key pair using type and length specified in config :return: None ''' if self.config['key']['key_type'] == 'rsa': self.key = rsa.generate_private_key( public_exponent=65537, key_size=self.config['key']['key_peram'], backend=default_backend() ) elif self.config['key']['key_type'] == 'dsa': self.key = dsa.generate_private_key( key_size=self.config['key']['key_peram'], backend=default_backend() ) elif self.config['key']['key_type'] == 'ec': self.key = ec.generate_private_key( curve=getattr(ec, self.config['key']['key_peram'])(), backend=default_backend() ) else: raise ValueError("\nFailed to generate key, no key_type key type provided!\n" "Offending key name: {}\n".format(self.name))
def generatePrivateKey(keyParams): """ Generate a key pair according to keyParams and return a new TpmPrivateKey with the private key. You can get the public key with derivePublicKey. :param KeyParams keyParams: The parameters of the key. :return: A new TpmPrivateKey. :rtype: TpmPrivateKey :raises ValueError: If the key type is not supported. :raises TpmPrivateKey.Error: For an invalid key size, or an error generating. """ if (keyParams.getKeyType() == KeyType.RSA or keyParams.getKeyType() == KeyType.EC): if keyParams.getKeyType() == KeyType.RSA: privateKey = rsa.generate_private_key( public_exponent = 65537, key_size = keyParams.getKeySize(), backend = default_backend()) else: privateKey = ec.generate_private_key( TpmPrivateKey._getEcCurve(keyParams.getKeySize()), default_backend()) else: raise ValueError( "Cannot generate a key pair of type " + str(keyParams.getKeyType())) result = TpmPrivateKey() result._privateKey = privateKey result._keyType = keyParams.getKeyType() return result
def generate_csr_and_key(common_name): """Return a dict with a new csr, public key and private key.""" private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend()) public_key = private_key.public_key() csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([ x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, common_name), ])).sign(private_key, hashes.SHA256(), default_backend()) result = { 'csr': csr.public_bytes( encoding=serialization.Encoding.PEM).decode("utf-8"), 'private_key': private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()).decode("utf-8"), 'public_key': public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo).decode( "utf-8"), } return result
def santest_csr(request, santest_host_1, santest_host_2): backend = default_backend() pkey = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=backend ) csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, santest_host_1.fqdn), x509.NameAttribute(NameOID.ORGANIZATION_NAME, api.env.realm) ])).add_extension(x509.SubjectAlternativeName([ x509.DNSName(santest_host_1.name), x509.DNSName(santest_host_2.name) ]), False ).add_extension( x509.BasicConstraints(ca=False, path_length=None), True ).add_extension( x509.KeyUsage( digital_signature=True, content_commitment=True, key_encipherment=True, data_encipherment=False, key_agreement=False, key_cert_sign=False, crl_sign=False, encipher_only=False, decipher_only=False ), False ).sign( pkey, hashes.SHA256(), backend ).public_bytes(serialization.Encoding.PEM) return csr.decode('ascii')
def RSA_generate(): private_key = rsa.generate_private_key( public_exponent=3, key_size=2048, backend=default_backend() ) return private_key
def sns_privatekey(): key = rsa.generate_private_key( public_exponent=65537, key_size=1024, # 1024 shouldn't be used, but for tests it's fine. backend=default_backend(), ) return key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())
def make_rsa_keys(self, passphrase=None, bits=DEFAULT_MODULUS) -> typing.Tuple[bytes, bytes]: """ Create new rsa private and public keys :param passphrase: Optional RSA private key passphrase. Returns encrypted version if set :param bits: Bits for pycrypto's generate function. Safe to ignore. :rtype: tuple of string version of keys (private, public) """ self.private_key = rsa.generate_private_key( public_exponent=65537, key_size=bits, backend=default_backend() ) self.public_key = self.private_key.public_key() if passphrase: encryption_alg = serialization.BestAvailableEncryption( passphrase.encode() ) _format = serialization.PrivateFormat.PKCS8 else: encryption_alg = serialization.NoEncryption() _format = serialization.PrivateFormat.TraditionalOpenSSL private = self.private_key.private_bytes( encoding=serialization.Encoding.PEM, format=_format, encryption_algorithm=encryption_alg ) public = self.public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) return private, public
def test_should_raise_for_pycrypto_stored_key_no_private_key(self): self.order_meta.update(self.stored_key_meta) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() private_key_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) self.private_key_value = base64.b64encode(private_key_pem) public_key_pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1 ) self.public_key_value = base64.b64encode(public_key_pem) self.store_plugin.get_secret.side_effect = self.stored_key_side_effect self.result.status = cert_man.CertificateStatus.WAITING_FOR_CA secret_repo.delete_entity_by_id( self.private_key.id, self.external_project_id) self.assertRaises(excep.StoredKeyPrivateKeyNotFound, cert_res.issue_certificate_request, self.order, self.project, self.result_follow_on)
def test_works_with_lowercase_attr_type_shortname(self, generator): principal = { 'uid': ['testuser'], 'mail': ['*****@*****.**'], } template_env = { 'ipacertificatesubjectbase': [ 'o=DOMAIN.EXAMPLE.COM' # lower-case attr type shortname ], } config = generator.csr_config(principal, template_env, 'userCert') key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) adaptor = csrgen.OpenSSLAdaptor(key=key) reqinfo = bytes(csrgen_ffi.build_requestinfo( config.encode('utf-8'), adaptor.get_subject_public_key_info())) csr_der = adaptor.sign_csr(reqinfo) csr = x509.load_der_x509_csr(csr_der, default_backend()) assert ( csr.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) == [x509.NameAttribute(x509.NameOID.COMMON_NAME, u'testuser')] ) assert ( csr.subject.get_attributes_for_oid(x509.NameOID.ORGANIZATION_NAME) == [x509.NameAttribute( x509.NameOID.ORGANIZATION_NAME, u'DOMAIN.EXAMPLE.COM')] )
def generate_rsa_keys(key_size=4096): private_key = rsa.generate_private_key( key_size=key_size, public_exponent=65537, backend=default_backend()) return (private_key, private_key.public_key())
def setUp(self): # Load Azure app defaults try: with open('azurermconfig.json') as configFile: configData = json.load(configFile) except FileNotFoundError: print("Error: Expecting vmssConfig.json in current folder") sys.exit() tenant_id = configData['tenantId'] app_id = configData['appId'] app_secret = configData['appSecret'] self.subscription_id = configData['subscriptionId'] self.access_token = azurerm.get_access_token(tenant_id, app_id, app_secret) self.location = configData['location'] # create resource names h = Haikunator() self.rgname = h.haikunate() self.service_name = h.haikunate(delimiter='') self.agent_dns = h.haikunate(delimiter='') self.master_dns = h.haikunate(delimiter='') # generate RSA Key for container service key = rsa.generate_private_key(backend=default_backend(), public_exponent=65537, \ key_size=2048) self.public_key = key.public_key().public_bytes(serialization.Encoding.OpenSSH, \ serialization.PublicFormat.OpenSSH).decode('utf-8') # create resource group print('Creating resource group: ' + self.rgname) response = azurerm.create_resource_group(self.access_token, self.subscription_id, \ self.rgname, self.location) self.assertEqual(response.status_code, 201)
def test_should_return_for_pycrypto_stored_key_without_passphrase(self): self.order_meta.update(self.stored_key_meta) private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) public_key = private_key.public_key() private_key_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) self.private_key_value = base64.b64encode(private_key_pem) public_key_pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.PKCS1 ) self.public_key_value = base64.b64encode(public_key_pem) 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._verify_issue_certificate_plugins_called() self.assertIsNotNone( self.order.order_barbican_meta['generated_csr'])
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)
def main(): message = 'This is my benchmarking message; it should really be longer' e1 = time.time() #Time key generation: EC eck1 = ec.generate_private_key(ec.SECP384R1(), default_backend()) eck2 = ec.generate_private_key(ec.SECP384R1(), default_backend()) e2 = time.time() #Time key generation: RSA rsak = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) e3 = time.time() #Time Encryption: EC ecct = transport_security.construct_message(message, srcprivkey=eck1, destpubkey=eck2.public_key()) e4 = time.time() #Time Encryption: RSA rsact = transport_security.get_raw_encrypted(message, pubkey=rsak.public_key()) e5 = time.time() #Time Decryption: EC ecpt = transport_security.deconstruct_message(message_dict=ecct, destprivkey=eck2, srcpubkey=eck1.public_key()) e6 = time.time() if ecpt == message: print("EC Decryption successful") else: print("EC Decryption failed") #Time Decryption: RSA rsapt = transport_security.get_raw_decrypted(ciphertext=rsact, privkey=rsak) e7 = time.time() if ecpt == message: print("RSA Decryption successful") else: print("RSA Decryption failed") with open('timing.out', 'a') as f: record = "{}\t{}\t{}\t{}\t{}\t{}\n".format(e2-e1, e3-e2, e4-e3, e5-e4, e6-e5, e7-e6) f.write(record)
def generate( cls, fast=False ): private_key = rsa.generate_private_key( public_exponent=65537, key_size=RSA_KEY_SIZE_FAST if fast else RSA_KEY_SIZE_SAFE, backend=default_backend() ) return cls('rsa', private_key)
def generate_keypair(cls): """RSA keypair generator""" return rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() )
def generate_self_signed_cert(cert_file, key_file): """Given two file-like objects, generate an SSL key and certificate.""" one_day = datetime.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.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + datetime.timedelta(365*10)) builder = builder.serial_number(int(uuid.uuid4())) 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))
def generate_certificate(hostname): """ Generate self-signed certificate for some DNS name. The certificate is valid for 100 days from moment of generation. :param hostname: DNS name (str|unicode) """ key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) if isinstance(hostname, bytes): hostname = hostname.decode() subject = issuer = x509.Name( [x509.NameAttribute(NameOID.COMMON_NAME, hostname)] ) cert = x509.CertificateBuilder() cert = cert.subject_name(subject).issuer_name(issuer).public_key( key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.utcnow() ).not_valid_after( datetime.utcnow() + timedelta(days=100) ).add_extension( x509.SubjectAlternativeName([x509.DNSName(hostname)]), critical=False ).sign(key, hashes.SHA256(), default_backend()) return cert.public_bytes(serialization.Encoding.PEM).decode()
def gen_private_key(self): """generate a private key with cryptography""" return rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), )
def generate_csr(cn, is_hostname=True): """ Generate certificate signing request :param cn: common name (str|unicode) :param is_hostname: is the common name a hostname (default: True) """ key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) if isinstance(cn, bytes): cn = cn.decode() csr = x509.CertificateSigningRequestBuilder() csr = csr.subject_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)]) ) if is_hostname: csr = csr.add_extension( x509.SubjectAlternativeName([x509.DNSName(cn)]), critical=False ) csr = csr.sign(key, hashes.SHA256(), default_backend()) return csr.public_bytes(serialization.Encoding.PEM).decode()
def _generate_public_and_private_key(self, length, name): crypto_private_key = rsa.generate_private_key( public_exponent=65537, key_size=length, backend=backends.default_backend()) private_der = crypto_private_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) crypto_public_key = crypto_private_key.public_key() public_der = crypto_public_key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo) private_key = pri_key.PrivateKey( algorithm='RSA', bit_length=length, key=bytearray(private_der), name=name) public_key = pub_key.PublicKey( algorithm='RSA', bit_length=length, key=bytearray(public_der), name=name) return private_key, public_key
def create_ca(self, cn=ISSUER_CN): """Create root CA. :returns: bytes -- Root CA in PEM format. """ self.ca_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend(), ) self.ca_public_key = self.ca_key.public_key() subject = self.issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, six.text_type(cn)), ]) builder = x509.CertificateBuilder() builder = builder.subject_name(subject) builder = builder.issuer_name(self.issuer) builder = builder.public_key(self.ca_public_key) builder = builder.serial_number(x509.random_serial_number()) builder = builder.not_valid_before(self.now) builder = builder.not_valid_after(self.now + self.delta) builder = builder.add_extension( x509.KeyUsage( digital_signature=False, 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, ) builder = builder.add_extension( x509.BasicConstraints(ca=True, path_length=None), critical=True, ) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(self.ca_public_key), critical=False, ) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key( self.ca_public_key ), critical=False, ) cert = builder.sign(self.ca_key, hashes.SHA256(), default_backend()) return cert.public_bytes(serialization.Encoding.PEM)
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa # Generate the public/private key pair. private_key = rsa.generate_private_key( public_exponent=65537, key_size=4096, backend=default_backend(), ) # Save the private key to a file. with open('private.key', 'wb') as f: f.write( private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), )) # Save the public key to a file. with open('public.pem', 'wb') as f: f.write(private_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ))
def generateNewKeyPair( ) -> Tuple[RSAPrivateKeyWithSerialization, RSAPublicKey]: private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) return private_key, private_key.public_key()
def set_key(self, pub_key): self._key = rsa.generate_private_key( public_exponent=pub_key, key_size=2048, backend=default_backend()).public_key()
def private_key(): return rsa.generate_private_key( public_exponent=65537, key_size=2048, )
import base64 # Third-Party imports from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.exceptions import InvalidSignature from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicNumbers from cryptography.hazmat.primitives.serialization import load_der_public_key from cryptography.hazmat.primitives.serialization import load_der_private_key from cryptography.fernet import Fernet private_key = rsa.generate_private_key(65537,2048,default_backend()) pem=private_key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.TraditionalOpenSSL,serialization.NoEncryption()) print pem public_key = private_key.public_key() pem=public_key.public_bytes(serialization.Encoding.PEM,serialization.PublicFormat.SubjectPublicKeyInfo) print pem with open("private.pem", "rb") as key_file: pubkey=key_file.read() b64data= '\n'.join(pubkey.splitlines()[1:-1]) derdata=base64.b64decode(b64data) key=load_der_private_key(derdata,None,default_backend()) print key with open("public.pem", "rb") as key_file:
def generate_rsa_private_key(): return rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend())
def generate_asymmetric(self, generate_dto, kek_meta_dto, project_id): """Generate asymmetric keys based on below rules: - RSA, with passphrase (supported) - RSA, without passphrase (supported) - DSA, without passphrase (supported) - DSA, with passphrase (supported) """ if(generate_dto.algorithm is None or generate_dto .algorithm.lower() == 'rsa'): private_key = rsa.generate_private_key( public_exponent=65537, key_size=generate_dto.bit_length, backend=default_backend() ) elif generate_dto.algorithm.lower() == 'dsa': private_key = dsa.generate_private_key( key_size=generate_dto.bit_length, backend=default_backend() ) else: raise c.CryptoPrivateKeyFailureException() public_key = private_key.public_key() if generate_dto.algorithm.lower() == 'rsa': private_key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=self._get_encryption_algorithm( generate_dto.passphrase) ) public_key = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) if generate_dto.algorithm.lower() == 'dsa': private_key = private_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=self._get_encryption_algorithm( generate_dto.passphrase) ) public_key = public_key.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo ) private_dto = self.encrypt(c.EncryptDTO(private_key), kek_meta_dto, project_id) public_dto = self.encrypt(c.EncryptDTO(public_key), kek_meta_dto, project_id) passphrase_dto = None if generate_dto.passphrase: if isinstance(generate_dto.passphrase, six.text_type): generate_dto.passphrase = generate_dto.passphrase.encode( 'utf-8') passphrase_dto = self.encrypt(c.EncryptDTO(generate_dto. passphrase), kek_meta_dto, project_id) return private_dto, public_dto, passphrase_dto
def get_crypto_keys(): private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) public_key = private_key.public_key() return private_key, public_key
def generate_tls_keys(): """ Creates a TLS private key (RSA, 4096 bits, PEM format) and certificate signing request (CSR). """ # Query the user for CSR attributes country = input("Country: ") state = input("State or province: ") locality = input("Locality: ") organization = input("Organization: ") organizational_unit = input("Organizational unit: ") email = input("Email: ") common_name = input("Common name: ") print( "Enter any subject alternative names (SANs) you wish to attach to the certificate. Leave blank to continue." ) sans = [] while True: san = input("Subject alternative name: ") if san == '': break sans.append(DNSName(san)) # Make sure we can open the output files first private_key_file = open("private.key", "wb") csr_file = open("certificate_signing_request", "wb") # Generate the private key key = generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) attributes = [ NameAttribute(NameOID.COUNTRY_NAME, country), NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, state), NameAttribute(NameOID.LOCALITY_NAME, locality), NameAttribute(NameOID.ORGANIZATION_NAME, organization), NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, organizational_unit), NameAttribute(NameOID.EMAIL_ADDRESS, email), NameAttribute(NameOID.COMMON_NAME, common_name), ] # Generate the CSR and sign it with the private key csr = CertificateSigningRequestBuilder().subject_name(Name(attributes)) if sans: csr = csr.add_extension(SubjectAlternativeName(sans), critical=False) csr = csr.sign(key, SHA256(), default_backend()) # Write the private key and CSR to disk private_key_file.write( key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption())) csr_file.write(csr.public_bytes(Encoding.PEM)) private_key_file.close() csr_file.close() # Success! print( "Successfully generated a private key and certificate signing request." )
def generate_rsa_keys(self, keysize): private_key = rsa.generate_private_key(public_exponent=65537, key_size=keysize, backend=default_backend()) return private_key
def register(config, account_storage, tos_cb=None): """Register new account with an ACME CA. This function takes care of generating fresh private key, registering the account, optionally accepting CA Terms of Service and finally saving the account. It should be called prior to initialization of `Client`, unless account has already been created. :param .IConfig config: Client configuration. :param .AccountStorage account_storage: Account storage where newly registered account will be saved to. Save happens only after TOS acceptance step, so any account private keys or `.RegistrationResource` will not be persisted if `tos_cb` returns ``False``. :param tos_cb: If ACME CA requires the user to accept a Terms of Service before registering account, client action is necessary. For example, a CLI tool would prompt the user acceptance. `tos_cb` must be a callable that should accept `.RegistrationResource` and return a `bool`: ``True`` iff the Terms of Service present in the contained `.Registration.terms_of_service` is accepted by the client, and ``False`` otherwise. ``tos_cb`` will be called only if the client action is necessary, i.e. when ``terms_of_service is not None``. This argument is optional, if not supplied it will default to automatic acceptance! :raises certbot.errors.Error: In case of any client problems, in particular registration failure, or unaccepted Terms of Service. :raises acme.errors.Error: In case of any protocol problems. :returns: Newly registered and saved account, as well as protocol API handle (should be used in `Client` initialization). :rtype: `tuple` of `.Account` and `acme.client.Client` """ # Log non-standard actions, potentially wrong API calls if account_storage.find_all(): logger.info("There are already existing accounts for %s", config.server) if config.email is None: if not config.register_unsafely_without_email: msg = ("No email was provided and " "--register-unsafely-without-email was not present.") logger.warning(msg) raise errors.Error(msg) if not config.dry_run: logger.info("Registering without email!") # Each new registration shall use a fresh new key key = jose.JWKRSA(key=jose.ComparableRSAKey( rsa.generate_private_key( public_exponent=65537, key_size=config.rsa_key_size, backend=default_backend()))) acme = acme_from_config_key(config, key) # TODO: add phone? regr = perform_registration(acme, config, tos_cb) acc = account.Account(regr, key) account.report_new_account(config) account_storage.save(acc, acme) eff.handle_subscription(config) return acc, acme
def generate(cls, size=2048): """Generate a new private key, reprsenting an asymetric RSA key pair.""" private_key = rsa.generate_private_key(public_exponent=65537, key_size=size, backend=default_backend()) return PrivateKey(private_key)
def test_anchor_signed_server(self): home = self.user.usercomponent_set.get(name="home") self.app.set_user(user="******") privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) pempub = privkey.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, ).strip() createurl = reverse("spider_base:ucontent-add", kwargs={ "token": home.token, "type": "PublicKey" }) response = self.app.get(createurl) form = response.forms["main_form"] form["key"] = pempub form["content_control-description"] = "valid" response = form.submit().follow() keyob = PublicKey.objects.filter( associated__description="valid").first() self.assertTrue(keyob) createurl = reverse("spider_base:ucontent-add", kwargs={ "token": home.token, "type": "AnchorKey" }) response = self.app.get(createurl) form = response.forms["main_form"] form.select("key", value=str(keyob.associated.id)) response = form.submit() updateurl = response.location response = response.follow() form = response.forms["main_form"] identifier = form["identifier"].value.encode("utf-8") chosen_hash = settings.SPIDER_HASH_ALGORITHM signature = privkey.sign( identifier, padding.PSS(mgf=padding.MGF1(chosen_hash), salt_length=padding.PSS.MAX_LENGTH), chosen_hash) with self.subTest(msg="block invalid signature"): response = self.app.get(updateurl) form = response.forms["main_form"] form["signature"].value = signature response = form.submit() response = self.app.get(updateurl) form = response.forms["main_form"] self.assertEqual(form["signature"].value, "") with self.subTest(msg="valid signature"): u = binascii.hexlify(signature).decode("ascii") response = self.app.get(updateurl) form = response.forms["main_form"] form["signature"].value = u response = form.submit() response = self.app.get(updateurl) form = response.forms["main_form"] self.assertEqual(response.status_code, 200) self.assertEqual(form["signature"].value, u)
def _create_key(common_name, public_exponent, key_size, **kwargs): key = rsa.generate_private_key(public_exponent=public_exponent, key_size=key_size, backend=default_backend()) return key
def generate_client_cert(self, extra_vars, ssh_options): node_ip = ssh_options["ssh_host"] root_cert_path = extra_vars["rootCA_cert"] root_key_path = extra_vars["rootCA_key"] certs_node_dir = extra_vars["certs_node_dir"] with open(root_cert_path, 'r') as cert_in: certlines = cert_in.read() root_cert = x509.load_pem_x509_certificate(certlines, default_backend()) with open(root_key_path, 'r') as key_in: keylines = key_in.read() root_key = load_pem_private_key(keylines, None, default_backend()) private_key = rsa.generate_private_key( public_exponent=self.PUBLIC_EXPONENT, key_size=self.KEY_SIZE, backend=default_backend()) public_key = private_key.public_key() builder = x509.CertificateBuilder() builder = builder.subject_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, six.text_type(node_ip)), x509.NameAttribute(NameOID.ORGANIZATION_NAME, six.text_type(extra_vars["org_name"])) ])) builder = builder.issuer_name(root_cert.issuer) builder = builder.not_valid_before(datetime.datetime.today()) builder = builder.not_valid_after( datetime.datetime.today() + datetime.timedelta(extra_vars["cert_valid_duration"])) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(public_key) builder = builder.add_extension(x509.BasicConstraints( ca=False, path_length=None), critical=True) certificate = builder.sign(private_key=root_key, algorithm=hashes.SHA256(), backend=default_backend()) # Write private key to file pem = private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) key_file = 'node.{}.key'.format(node_ip) cert_file = 'node.{}.crt'.format(node_ip) common_path = '{}/{}'.format(self.CERTS_TEMP_DIR, node_ip) try: os.makedirs(common_path) except OSError as exc: # Guard against race condition if exc.errno != errno.EEXIST: raise YBOpsRuntimeError(common_path + " could not be be created") with open(os.path.join(common_path, key_file), 'wb') as pem_out: pem_out.write(pem) # Write certificate to file pem = certificate.public_bytes(encoding=Encoding.PEM) with open(os.path.join(common_path, cert_file), 'wb') as pem_out: pem_out.write(pem) # Copy files over to node remote_shell = RemoteShell(ssh_options) remote_shell.run_command('mkdir -p ' + certs_node_dir) remote_shell.put_file(os.path.join(common_path, key_file), os.path.join(certs_node_dir, key_file)) remote_shell.put_file(os.path.join(common_path, cert_file), os.path.join(certs_node_dir, cert_file)) remote_shell.put_file(root_cert_path, os.path.join(certs_node_dir, 'ca.crt')) try: shutil.rmtree(common_path) except OSError as e: raise YBOpsRuntimeError("Error: %s - %s." % (e.filename, e.strerror))
def generate_rsa_public_and_private(bits=_DEFAULT_RSA_KEY_BITS): """ <Purpose> Generate public and private RSA keys with modulus length 'bits'. The public and private keys returned conform to 'tuf.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ...' or '-----BEGIN RSA PRIVATE KEY----- ...' The public and private keys are returned as strings in PEM format. 'generate_rsa_public_and_private()' enforces a minimum key size of 2048 bits. If 'bits' is unspecified, a 3072-bit RSA key is generated, which is the key size recommended by TUF. >>> public, private = generate_rsa_public_and_private(2048) >>> tuf.formats.PEMRSA_SCHEMA.matches(public) True >>> tuf.formats.PEMRSA_SCHEMA.matches(private) True <Arguments> bits: The key size, or key length, of the RSA key. 'bits' must be 2048, or greater. 'bits' defaults to 3072 if not specified. <Exceptions> tuf.FormatError, if 'bits' does not contain the correct format. <Side Effects> The RSA keys are generated from pyca/cryptography's rsa.generate_private_key() function. <Returns> A (public, private) tuple containing the RSA keys in PEM format. """ # Does 'bits' have the correct format? # This check will ensure 'bits' conforms to 'tuf.formats.RSAKEYBITS_SCHEMA'. # 'bits' must be an integer object, with a minimum value of 2048. # Raise 'tuf.FormatError' if the check fails. tuf.formats.RSAKEYBITS_SCHEMA.check_match(bits) # Generate the public and private RSA keys. The pyca/cryptography 'rsa' # module performs the actual key generation. The 'bits' argument is used, # and a 2048-bit minimum is enforced by # tuf.formats.RSAKEYBITS_SCHEMA.check_match(). private_key = rsa.generate_private_key(public_exponent=65537, key_size=bits, backend=default_backend()) # Extract the public & private halves of the RSA key and generate their # PEM-formatted representations. Return the key pair as a (public, private) # tuple, where each RSA is a string in PEM format. private_pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) # Need to generate the public pem from the private key before serialization # to PEM. public_key = private_key.public_key() public_pem = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) return public_pem.decode(), private_pem.decode()
def test_import_rsa4096(self): priv = rsa.generate_private_key(E, 4096, default_backend()) self.controller.verify_admin(DEFAULT_ADMIN_PIN) self.controller.import_key(KEY_SLOT.SIG, priv)
def distribute_keys(self) -> None: """Create a new key pair and distributes it to all hosts. Ensure that the hosts have a safe communication. The name of the key is the cluster's name """ if self.cluster_has_key(): logger.info(cl.GR("Cluster has already configured key pair")) return # 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()) # decode to printable strings private_key_str = pem.decode('utf-8') public_key_str = public_key.decode('utf-8') logger.debug("New key pair generated") def m(ins): ins._run_cmd(f"rm -rf {ins.get_home_path()}/{const.PUBLIC_KEY}") ins._run_cmd(f"rm -rf {ins.get_home_path()}/{const.PRIVATE_KEY}") ret = ins._run_cmd( f"echo '{public_key_str}' >> {ins.get_home_path()}/.ssh/authorized_keys", retries=3 ) if not ret.success: raise man_errors.ClusterError("Could not send key to authorized_keys") with tempfile.NamedTemporaryFile("w") as t: t.write(private_key_str) t.flush() ins.send_rsync(t.name, f"{ins.get_home_path()}/{const.PRIVATE_KEY}") ins._run_cmd(f"chmod 600 {ins.get_home_path()}/{const.PRIVATE_KEY}") with tempfile.NamedTemporaryFile("w") as t: t.write(public_key_str) t.flush() ins.send_rsync(t.name, f"{ins.get_home_path()}/{const.PUBLIC_KEY}") logger.debug(f"New key pair sent to {ins.host}") with ThreadPoolExecutor() as executor: futures = {} for ins in self._get_all_hosts(): futures[executor.submit(m, ins)] = ins for f in futures.keys(): try: f.result() except errors.RemoteCommandError: raise except Exception as exc: logger.error('Generated an exception: {}'.format(exc)) raise logger.info(cl.GR("Distributed keys"))
def create_cert(subject_com_name, subject_bumen_name, subject_zuzhi_name, subject_city_name, subject_shengfen_name, subject_guojia_name, issuer_com_name, issuer_zuzhi_name, issuer_guojia_name, root_flag, before_time, after_time, mysf, beiyong_name, myqd, qmsf, key_pass): key = None builder = None certificate = None try: if subject_bumen_name: builder = x509.CertificateBuilder().subject_name( x509.Name([ # Provide various details about who we are. x509.NameAttribute(NameOID.COUNTRY_NAME, subject_guojia_name), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, subject_shengfen_name), x509.NameAttribute(NameOID.LOCALITY_NAME, subject_city_name), x509.NameAttribute(NameOID.ORGANIZATION_NAME, subject_zuzhi_name), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, subject_bumen_name), x509.NameAttribute(NameOID.COMMON_NAME, subject_com_name), ])) else: builder = x509.CertificateBuilder().subject_name( x509.Name([ # Provide various details about who we are. x509.NameAttribute(NameOID.COUNTRY_NAME, subject_guojia_name), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, subject_shengfen_name), x509.NameAttribute(NameOID.LOCALITY_NAME, subject_city_name), x509.NameAttribute(NameOID.ORGANIZATION_NAME, subject_zuzhi_name), x509.NameAttribute(NameOID.COMMON_NAME, subject_com_name), ])) except Exception as e: print(e) return {'error': False, 'msg': u'提交内容错误!'} # 添加issuer信息 builder = builder.issuer_name( x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, issuer_com_name), x509.NameAttribute(NameOID.ORGANIZATION_NAME, issuer_zuzhi_name), x509.NameAttribute(NameOID.COUNTRY_NAME, issuer_guojia_name), ])) # 其他杂项 ############## try: builder = builder.not_valid_before( datetime.datetime.strptime(before_time, '%Y-%m-%d %H:%M:%S')) builder = builder.not_valid_after( datetime.datetime.strptime(after_time, '%Y-%m-%d %H:%M:%S')) except Exception as e: return {'error': False, 'msg': u'过期时间小于颁发时间!'} builder = builder.serial_number(x509.random_serial_number()) ################## try: dns_name = [x509.DNSName(i) for i in beiyong_name.split(',')] except Exception as e: print(e) return {'error': False, 'msg': u'备用名请用逗号隔开!'} builder = builder.add_extension(x509.SubjectAlternativeName(dns_name), critical=False) builder = builder.add_extension( x509.BasicConstraints(ca=root_flag, path_length=None), critical=True, ) ######################### ######################### if mysf == 'RSA': private_key = rsa.generate_private_key(public_exponent=65537, key_size=int(myqd), backend=default_backend()) builder = builder.public_key(private_key.public_key()) if key_pass: key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( key_pass), ) else: key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) if qmsf == 'MD5': certificate = builder.sign(private_key=private_key, algorithm=hashes.MD5(), backend=default_backend()) elif qmsf == 'SHA1': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA1(), backend=default_backend()) elif qmsf == 'SHA224': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA224(), backend=default_backend()) elif qmsf == 'SHA256': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend()) elif qmsf == 'SHA384': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA384(), backend=default_backend()) elif qmsf == 'SHA512': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA512(), backend=default_backend()) else: certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA1(), backend=default_backend()) return { 'error': True, 'cert': certificate.public_bytes(serialization.Encoding.PEM), 'priv_key': key } elif mysf == 'DSA': private_key = dsa.generate_private_key(key_size=int(myqd), backend=default_backend()) builder = builder.public_key(private_key.public_key()) if key_pass: key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( key_pass), ) else: key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) if qmsf == 'SHA1': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA1(), backend=default_backend()) elif qmsf == 'SHA224': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA224(), backend=default_backend()) elif qmsf == 'SHA256': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend()) else: certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA1(), backend=default_backend()) return { 'error': True, 'cert': certificate.public_bytes(serialization.Encoding.PEM), 'priv_key': key } elif mysf == 'ECDSA': if myqd == 'P192': private_key = ec.generate_private_key(curve=ec.SECP192R1(), backend=default_backend()) builder = builder.public_key(private_key.public_key()) elif myqd == 'P224': private_key = ec.generate_private_key(curve=ec.SECP224R1(), backend=default_backend()) builder = builder.public_key(private_key.public_key()) elif myqd == 'P256': private_key = ec.generate_private_key(curve=ec.SECP256R1(), backend=default_backend()) builder = builder.public_key(private_key.public_key()) elif myqd == 'P384': private_key = ec.generate_private_key(curve=ec.SECP384R1(), backend=default_backend()) builder = builder.public_key(private_key.public_key()) elif myqd == 'P521': private_key = ec.generate_private_key(curve=ec.SECP521R1(), backend=default_backend()) builder = builder.public_key(private_key.public_key()) else: private_key = ec.generate_private_key(curve=ec.SECP256R1(), backend=default_backend()) builder = builder.public_key(private_key.public_key()) if key_pass: key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption( key_pass), ) else: key = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption(), ) if qmsf == 'SHA1': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA1(), backend=default_backend()) elif qmsf == 'SHA224': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA224(), backend=default_backend()) elif qmsf == 'SHA256': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA256(), backend=default_backend()) elif qmsf == 'SHA384': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA384(), backend=default_backend()) elif qmsf == 'SHA512': certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA512(), backend=default_backend()) else: certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA1(), backend=default_backend()) return { 'error': True, 'cert': certificate.public_bytes(serialization.Encoding.PEM), 'priv_key': key }
def request_cert(domain): domain = domain.lower() print("Generating user key") user_key = josepy.JWKRSA( key=rsa.generate_private_key( public_exponent=65537, key_size=KEY_SIZE, backend=default_backend() ) ) save_key(user_key, domain) print("Connecting to Let's Encrypt on {}".format(DIRECTORY_URL)) acme = client.Client(DIRECTORY_URL, user_key) print("Registering") regr = acme.register() print("Agreeing to ToS") acme.agree_to_tos(regr) print("Requesting challenges") authzr = acme.request_challenges( identifier=messages.Identifier(typ=messages.IDENTIFIER_FQDN, value=domain) ) print("Looking for DNS challenge") challenge = get_dns_challenge(authzr) print("You need to set up the challenge response.") print("DNS (TXT) record: _acme-challenge.{}".format(domain)) print("Content: {}".format(challenge.chall.validation(user_key))) response = challenge.chall.response(user_key) while not response.simple_verify(challenge.chall, domain, user_key.public_key()): input("It doesn't look like it's set up yet; press return when it is.") print("Authorizing -- here goes...") auth_response = acme.answer_challenge(challenge, challenge.chall.response(user_key)) print("Response was {}".format(auth_response.body.status.name)) print("Waiting for authorization to become valid") while True: print("Polling") authzr, authzr_response = acme.poll(authzr) challenge = get_dns_challenge(authzr) if challenge.status.name == "valid": break print("DNS challenge is currently {}".format(challenge.status.name)) time.sleep(10) print("Auth valid") print("Generating CSR") certificate_key = crypto.PKey() certificate_key.generate_key(crypto.TYPE_RSA, 2048) csr = crypto.X509Req() csr.get_subject().CN = domain csr.set_pubkey(certificate_key) csr.sign(certificate_key, "sha256") print("Requesting certificate") certificate_response = acme.request_issuance(josepy.util.ComparableX509(csr), [authzr]) print("Got it!") print("Fetching chain") chain = acme.fetch_chain(certificate_response) print("Done!") print("Here are the details:") print("Private key:") print(crypto.dump_privatekey(FILETYPE_PEM, certificate_key)) print("Combined cert:") print(crypto.dump_certificate(FILETYPE_PEM, certificate_response.body.wrapped)) for cert in chain: print(crypto.dump_certificate(FILETYPE_PEM, cert.wrapped))
def generate_cert(common_name, alternative_names=None, password=None, issuer_name=None, signing_key=None, signing_key_password=None, generate_ca=False): """Generate x.509 certificate. Example of how to create a certificate chain:: (cakey, cacert) = generate_cert( 'DivineAuthority', generate_ca=True) (crkey, crcert) = generate_cert( 'test.com', issuer_name='DivineAuthority', signing_key=cakey) :param common_name: Common Name to use in generated certificate :type common_name: str :param alternative_names: List of names to add as SubjectAlternativeName :type alternative_names: Optional[list(str)] :param password: Password to protect encrypted private key with :type password: Optional[str] :param issuer_name: Issuer name, must match provided_private_key issuer :type issuer_name: Optional[str] :param signing_key: PEM encoded PKCS8 formatted private key :type signing_key: Optional[str] :param signing_key_password: Password to decrypt private key :type signing_key_password: Optional[str] :param generate_ca: Generate a certificate usable as a CA certificate :type generate_ca: bool :returns: x.509 certificate :rtype: cryptography.x509.Certificate """ if password is not None: encryption_algorithm = serialization.BestAvailableEncryption( password.encode('utf-8')) else: encryption_algorithm = serialization.NoEncryption() if signing_key: if signing_key_password: signing_key_password = signing_key_password.encode('utf-8') _signing_key = serialization.load_pem_private_key( signing_key, password=signing_key_password, backend=cryptography.hazmat.backends.default_backend(), ) private_key = rsa.generate_private_key( public_exponent=65537, # per RFC 5280 Appendix C key_size=2048, backend=cryptography.hazmat.backends.default_backend()) public_key = private_key.public_key() builder = cryptography.x509.CertificateBuilder() builder = builder.subject_name( cryptography.x509.Name([ cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.COMMON_NAME, common_name), ])) if issuer_name is None: issuer_name = common_name builder = builder.issuer_name( cryptography.x509.Name([ cryptography.x509.NameAttribute( cryptography.x509.oid.NameOID.COMMON_NAME, issuer_name), ])) builder = builder.not_valid_before( datetime.datetime.utcnow() - datetime.timedelta(0, 1, 0), ) builder = builder.not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(30, 0, 0), ) builder = builder.serial_number(cryptography.x509.random_serial_number()) builder = builder.public_key(public_key) san_list = [cryptography.x509.DNSName(common_name)] if alternative_names is not None: for name in alternative_names: try: addr = ipaddress.ip_address(name) except ValueError: san_list.append(cryptography.x509.DNSName(name)) else: san_list.append(cryptography.x509.IPAddress(addr)) builder = builder.add_extension( cryptography.x509.SubjectAlternativeName(san_list, ), critical=False, ) builder = builder.add_extension( cryptography.x509.BasicConstraints(ca=generate_ca, path_length=None), critical=True, ) if signing_key: sign_key = _signing_key else: sign_key = private_key certificate = builder.sign( private_key=sign_key, algorithm=cryptography.hazmat.primitives.hashes.SHA256(), backend=cryptography.hazmat.backends.default_backend(), ) return (private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=encryption_algorithm), certificate.public_bytes(serialization.Encoding.PEM))
""" with open(path, "wb") as f: f.write( key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo, )) def public_key_load(path, key): """ Returns public key PEM file """ return serialization.load_pem_public_key( open(path, 'rb').read(), default_backend()) if __name__ == "__main__": private_key = rsa.generate_private_key(public_exponent=16111995, key_size=2048, backend=default_backend()) public_key = private_key.public_key() # Public key to sign the certificate key = 50211111111111111111111111 # fake key to store, for example el gammal key, unfortunately must be odd... fake_key = FakePublicKey(key) cert = cert_build_signed(private_key, fake_key.get_key(), "ali") print(cert_validate_signature(cert, public_key)) print(cert_get_pub_key(cert).public_numbers().e ) # Check the fake key we attached to the certificate
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
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)
def create_key(path: Path, password: bytes): private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) dump_key(path, private_key, password)
def generate(self, module): """ Generate a hostkey pair """ # If size is wrong, delete the key. A new key will be generated in the next step. if self.key_current_size != self.size and not self.ignore_size: self.remove() self.key_exists = False else: self.changed = False # If there is no key or user has set "force" if not self.key_exists or self.force: if self.type == "RSA": self.key = crypto_rsa.generate_private_key( public_exponent=65537, key_size=self.size, backend=crypto_default_backend()) elif self.type == "DSA": self.key = crypto_dsa.generate_private_key( key_size=self.size, backend=crypto_default_backend()) elif self.type == "ECDSA": if self.size == 256: self.curve = crypto_ec.SECP256R1() elif self.size == 384: self.curve = crypto_ec.SECP384R1() elif self.size == 521: self.curve = crypto_ec.SECP521R1() self.key = crypto_ec.generate_private_key( curve=self.curve, backend=crypto_default_backend()) elif self.type == "ED25519": self.size = 128 self.curve = "EC25519" else: raise HostkeyError("Unknown key type.") if self.type != "ED25519": self.privkey = self.key.private_bytes( crypto_serialization.Encoding.PEM, crypto_serialization.PrivateFormat.PKCS8, crypto_serialization.NoEncryption()) self.pubkey = self.key.public_key().public_bytes( crypto_serialization.Encoding.OpenSSH, crypto_serialization.PublicFormat.OpenSSH) try: privfile = os.open(self.fullpath, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, self.mode) os.write(privfile, self.privkey) os.close(privfile) pubfile = os.open(self.fullpath + ".pub", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, self.mode) os.write(pubfile, self.pubkey) os.close(pubfile) self.changed = True except IOError: self.remove() raise HostkeyError(get_exception()) else: # use ssh-keygen to generate ED25519 Hostkeys # Keyfile must not exist, as there is no "force-overwrite" in ssh-keygen self.remove() retcode = subprocess.call([ "ssh-keygen", "-q", "-t", "ed25519", "-N", '', "-f", self.fullpath ]) self.changed = True else: self.changed = False file_args = module.load_file_common_arguments(module.params) file_args['path'] = self.fullpath if module.set_fs_attributes_if_different(file_args, False): self.changed = True file_args['path'] = self.fullpath + ".pub" file_args['mode'] = self.pubmode if module.set_fs_attributes_if_different(file_args, False): self.changed = True
def generate_private_key(self): self.__private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend()) self.public_key = self.__private_key.public_key()
def GenerateKey(cls, bits=2048, exponent=65537): key = rsa.generate_private_key(public_exponent=exponent, key_size=bits, backend=openssl.backend) return cls(key)
key_provider=MasterKeyInfo(provider_id=_PROVIDER_ID, key_info=_KEY_ID), data_key= b'*!\xa1"^-(\xf3\x105\x05i@B\xc2\xa2\xb7\xdd\xd5\xd5\xa9\xddm\xfae\xa8\\$\xf9d\x1e(', ), encryption_context=_ENCRYPTION_CONTEXT, keyring_trace=[ KeyringTrace( wrapping_key=MasterKeyInfo(provider_id=_PROVIDER_ID, key_info=_KEY_ID), flags={KeyringTraceFlag.GENERATED_DATA_KEY}, ) ], ) _rsa_private_key_a = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) _rsa_private_key_b = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) _MULTI_KEYRING_WITH_GENERATOR_AND_CHILDREN = MultiKeyring( generator=RawAESKeyring( key_namespace=_PROVIDER_ID, key_name=_KEY_ID, wrapping_key=_WRAPPING_KEY_AES, ), children=[ RawRSAKeyring( key_namespace=_PROVIDER_ID, key_name=_KEY_ID, wrapping_algorithm=WrappingAlgorithm.RSA_OAEP_SHA256_MGF1,
def gen_key_pair(): private_key = rsa.generate_private_key(public_exponent=65537, key_size=3072, backend=default_backend()) public_key = private_key.public_key() return private_key, public_key