def private_pem(self): return self._private_key_object.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption(), ).decode('ascii')
def __openssl_to_crypto(self, key): pem = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) key = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, pem) return key
def generate_key(): key = ec.generate_private_key(ec.SECP256R1(), default_backend()) key_pem = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) return crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
def _clone(self, original_cert, self_sign, signature_algo): """Create a 1:1 clone of original_cert. If self_sign is False, the new_certificate will not yet be signed.""" cert = OpenSSL.crypto.X509() cert.set_version(original_cert.get_version()) cert.set_serial_number(original_cert.get_serial_number()) cert.set_notBefore(original_cert.get_notBefore()) cert.set_notAfter(original_cert.get_notAfter()) pkey = OpenSSL.crypto.PKey() if original_cert.get_pubkey().type() == OpenSSL.crypto.TYPE_RSA: pkey.generate_key(OpenSSL.crypto.TYPE_RSA, original_cert.get_pubkey().bits()) elif original_cert.get_pubkey().type() == OpenSSL.crypto.TYPE_EC: ec_key = original_cert.get_pubkey().to_cryptography_key() curve = ec_key.curve key = ec.generate_private_key(curve, default_backend()) key_pem = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) pkey = OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, key_pem) else: self.error = Exception('Unsupported certificate type ' + str(original_cert.get_pubkey().type())) self.log.error(self.error) self.log.debug(self.error, exc_info=True) return cert.set_pubkey(pkey) cert.set_issuer(original_cert.get_issuer()) cert.set_subject(original_cert.get_subject()) extensions = [] for extid in range(original_cert.get_extension_count()): extensions.append(original_cert.get_extension(extid)) cert.add_extensions(extensions) if self_sign: if not signature_algo: signature_algo = original_cert.get_signature_algorithm().decode() # evp_get_digestbyname_ex() might fail for signature # definition in ECDSA certs. Just take the actual # signature algorithm from the string. E. g. extract # "SHA256" from "ecdsa-with-SHA256". if '-' in signature_algo: signature_algo = signature_algo.split('-')[-1] cert.sign(pkey, signature_algo) return cert, pkey
def cryptography_create_pkcs12_bundle(self, keystore_p12_path, key_format='PEM', cert_format='PEM'): if key_format == 'PEM': key_loader = load_pem_private_key else: key_loader = load_der_private_key if cert_format == 'PEM': cert_loader = load_pem_x509_certificate else: cert_loader = load_der_x509_certificate try: with open(self.private_key_path, 'rb') as key_file: private_key = key_loader( key_file.read(), password=to_bytes(self.keypass), backend=backend ) except TypeError: # Re-attempt with no password to match existing behavior try: with open(self.private_key_path, 'rb') as key_file: private_key = key_loader( key_file.read(), password=None, backend=backend ) except (OSError, TypeError, ValueError, UnsupportedAlgorithm) as e: self.module.fail_json( msg="The following error occurred while loading the provided private_key: %s" % to_native(e) ) except (OSError, ValueError, UnsupportedAlgorithm) as e: self.module.fail_json( msg="The following error occurred while loading the provided private_key: %s" % to_native(e) ) try: with open(self.certificate_path, 'rb') as cert_file: cert = cert_loader( cert_file.read(), backend=backend ) except (OSError, ValueError, UnsupportedAlgorithm) as e: self.module.fail_json( msg="The following error occurred while loading the provided certificate: %s" % to_native(e) ) if self.password: encryption = BestAvailableEncryption(to_bytes(self.password)) else: encryption = NoEncryption() pkcs12_bundle = serialize_key_and_certificates( name=to_bytes(self.name), key=private_key, cert=cert, cas=None, encryption_algorithm=encryption ) with open(keystore_p12_path, 'wb') as p12_file: p12_file.write(pkcs12_bundle) self.result.update(msg="PKCS#12 bundle created by cryptography backend")
def get_private_bytes(self): return self.key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
def serialize(self) -> bytes: return self.key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
def __generate_client_cert(self, extra_vars, ssh_options, root_cert_path, root_key_path, certs_dir, remote_shell): node_ip = ssh_options["ssh_host"] with open(root_cert_path, 'rb') as cert_in: certlines = cert_in.read() root_cert = x509.load_pem_x509_certificate(certlines, default_backend()) with open(root_key_path, 'rb') 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.subject) builder = builder.not_valid_before(datetime.datetime.utcnow()) builder = builder.not_valid_after( datetime.datetime.utcnow() + 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) with tempfile.TemporaryDirectory() as common_path: 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.run_command('mkdir -p ' + certs_dir) # Give write permission in case file exists. If the command fails, ignore. remote_shell.run_command( 'chmod -f 666 {}/* || true'.format(certs_dir)) remote_shell.put_file(os.path.join(common_path, key_file), os.path.join(certs_dir, key_file)) remote_shell.put_file(os.path.join(common_path, cert_file), os.path.join(certs_dir, cert_file)) remote_shell.put_file(root_cert_path, os.path.join(certs_dir, self.ROOT_CERT_NAME)) remote_shell.run_command('chmod 400 {}/*'.format(certs_dir))
from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa, ec from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption import OpenSSL key = ec.generate_private_key(ec.SECP256R1(), default_backend()) print(key) key_pem = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) print(key_pem) print(OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, key_pem))
def key_pem_str(key_obj): return key_obj.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()).decode("utf-8")
def main(): """ Main function """ private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) public_key = private_key.public_key() name = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"BR"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Luz"), x509.NameAttribute(NameOID.COMMON_NAME, u"Luz Root"), ]) builder = x509.CertificateBuilder() builder = builder.subject_name(name) certificate_not_before = datetime.utcnow() certificate_not_after = datetime(2049, 12, 31, hour=23, minute=59, second=59) builder = builder.not_valid_before(certificate_not_before) builder = builder.not_valid_after(certificate_not_after) builder = builder.serial_number(x509.random_serial_number()) builder = builder.public_key(public_key) builder = builder.issuer_name(name) 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=None, decipher_only=None), critical=True) builder = builder.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(public_key), critical=False) certificate = builder.sign(private_key=private_key, algorithm=hashes.SHA512(), backend=default_backend()) cert_pem = certificate.public_bytes(Encoding.PEM) with open("ca.crt", "w") as text_file: text_file.write(cert_pem.decode()) privkey_pem = private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) #privkey with password = BestAvailableEncryption(b"password") with open("ca.key", "w") as text_file: text_file.write(privkey_pem.decode())
def private_key_bytes(k): return k.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
def _serialize_ed25519_private_key(key): return key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption())
def test_x509_der(self): p12 = load_pkcs12(self.pkcs12_data, self.pkcs12_password_bytes) cert_bytes = p12.get_certificate().to_cryptography().public_bytes(Encoding.DER) pk_bytes = p12.get_privatekey().to_cryptography_key().private_bytes(Encoding.DER, PrivateFormat.PKCS8, NoEncryption()) adapter = X509Adapter(max_retries=3, cert_bytes=cert_bytes, pk_bytes=pk_bytes, encoding=Encoding.DER) self.session.mount('https://', adapter) recorder = get_betamax(self.session) with recorder.use_cassette('test_x509_adapter_der'): r = self.session.get('https://pkiprojecttest01.dev.labs.internal/', verify=False) assert r.status_code == 200 assert r.text
SECP256K1, ECDSA, EllipticCurvePrivateKey, EllipticCurvePublicNumbers, derive_private_key as derive_privkey, generate_private_key as gen_privkey) from cryptography.hazmat.primitives.asymmetric.utils import ( decode_dss_signature) from cryptography.hazmat.primitives.hashes import SHA256 from cryptography.hazmat.primitives.serialization import (Encoding, NoEncryption, PrivateFormat, load_der_private_key, load_pem_private_key) from bit.exceptions import InvalidSignature # Memoize instances across application DEFAULT_BACKEND = default_backend() NOENCRYPTION = NoEncryption() SECP256K1 = SECP256K1() ECDSA_SHA256 = ECDSA(SHA256()) def get_ec_point(private_key): backend = private_key._backend get_func = backend._lib.EC_POINT_get_affine_coordinates_GFp group = backend._lib.EC_KEY_get0_group(private_key._ec_key) point = backend._lib.EC_KEY_get0_public_key(private_key._ec_key) backend.openssl_assert(point != backend._ffi.NULL) with backend._tmp_bn_ctx() as bn_ctx: bn_x = backend._lib.BN_CTX_get(bn_ctx)
def test_x448_private_key_size(self) -> None: private_key_bytes = X448.generate_private_key().private_bytes( encoding=Encoding.Raw, format=PrivateFormat.Raw, encryption_algorithm=NoEncryption()) self.assertEqual(len(private_key_bytes), TFC_PRIVATE_KEY_LENGTH)
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------------ """ Generate a private key to be used for the Trading Agent Competition. It prints the key in PEM format to the specified file. """ from tac.helpers.crypto import Crypto from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption import argparse parser = argparse.ArgumentParser("generate_private_key", description=__doc__) parser.add_argument("out_file", type=str, help="Where to save the private key.") if __name__ == '__main__': args = parser.parse_args() crypto = Crypto() pem = crypto._private_key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()) file = open(args.out_file, "wb") file.write(pem) file.close()
def main(): """ ###################################################################### # Generating the self signed cert # # Packages from cryptography.io which uses openssl in the backed # # is used here # ###################################################################### """ try: az = subprocess.check_output([ 'curl', '-s', 'http://169.254.169.254/latest/meta-data/placement/availability-zone' ]) list_az = az.split('-') region = list_az[0] + '-' + list_az[1] + '-' + list_az[2][0] ddb_client = boto3.client('dynamodb', region) ##################################################################################### # Generating key pair for self signed cert # # Storing private key of self signed cert in an encrypted DynamoDB table # # so that other python modules can access it # # The private key generated here is for demonstration purposes, the best practice # # is to store private keys on an HSM # ##################################################################################### privkey = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) privkey_pem = privkey.private_bytes(encoding=serialization.Encoding.PEM,\ format=serialization.PrivateFormat.PKCS8,\ encryption_algorithm=NoEncryption()) current_directory_path = os.path.dirname( os.path.realpath(__file__)) + '/' rootca_serial_number = random.randint(1, 100000) response = ddb_client.update_item( ExpressionAttributeNames={ '#rsn': 'rootca_serial_number', '#rcpk': 'root_ca_private_key', }, ExpressionAttributeValues={ ':a': { 'N': str(rootca_serial_number), }, ':b': { 'B': privkey_pem, }, }, Key={ 'shared_variables': { 'N': '1000', }, 'session': { 'N': '1000', }, }, ReturnValues='ALL_NEW', TableName='shared_variables_crypto_builders_usecase_6', UpdateExpression='SET #rsn = :a, #rcpk = :b', ) ############################################################# # Create the subject and issuer for the self signed cert # ############################################################# subject_name = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, u'rootca-builder'), x509.NameAttribute(NameOID.COUNTRY_NAME, u'US'), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u'Nevada'), x509.NameAttribute(NameOID.LOCALITY_NAME, u'Las Vegas'), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u'customer'), x509.NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, u'customerdept'), x509.NameAttribute(NameOID.SERIAL_NUMBER, unicode(str(rootca_serial_number))) ]) issuer_name = subject_name ################################################################## # Building the self signed cert pem file self-signed-cert.pem # ################################################################## # path_len=0 means this cert can only sign itself, not other certs. basic_contraints = x509.BasicConstraints(ca=True, path_length=1) pubkey = privkey.public_key() now = datetime.utcnow() cert = (x509.CertificateBuilder( ).subject_name(subject_name).issuer_name(issuer_name).public_key( pubkey).serial_number(rootca_serial_number).not_valid_before( now).not_valid_after(now + timedelta(days=10 * 365)).add_extension( basic_contraints, True).sign(privkey, hashes.SHA256(), default_backend())) cert_pem = cert.public_bytes(encoding=serialization.Encoding.PEM) current_directory_path = os.path.dirname( os.path.realpath(__file__)) + '/' self_signed_cert_filename_path = current_directory_path + 'self-signed-cert.pem' textfile = open(self_signed_cert_filename_path, 'w') textfile.write(cert_pem) textfile.close() print "Success - Self signed certificate file self_signed_cert.pem created" print "\nThis self signed certificate will be used in the certificate chain of trust" print "\nStep-3 has been successfully completed \n" except: print "Unexpected error:", sys.exc_info()[0] raise else: exit(0)
import datetime import os import logging logging.basicConfig(filename='/tmp/ingest.log', level=logging.DEBUG) logger = getLogger(__name__) with open("/home/hadoop/snowflake/hands-on/snowpipe/rsa_key.p8", 'rb') as pem_in: pemlines = pem_in.read() private_key_obj = load_pem_private_key( pemlines, os.environ['PRIVATE_KEY_PASSPHRASE'].encode(), default_backend()) private_key_text = private_key_obj.private_bytes( Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()).decode('utf-8') # Assume the public key has been registered in Snowflake: # private key in PEM format # List of files in the stage specified in the pipe definition file_list = ['departments.csv'] ingest_manager = SimpleIngestManager( account='<>', host='<>.<>.snowflakecomputing.com', user='******', pipe='dataload_db.dataload.load_dept_pipe', private_key=private_key_text) # List of files, but wrapped into a class staged_file_list = []
def save_key(key, filename): """Save a public/private key pair in PEM-encoded format.""" bstr = key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) with open(filename, 'w', encoding='utf8') as f: f.write(bstr.decode())
def serialize_private(key): return key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption())
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.subject) builder = builder.not_valid_before(datetime.datetime.utcnow()) builder = builder.not_valid_after(datetime.datetime.utcnow() + 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) # Give write permission in case file exists. If the command fails, ignore. remote_shell.run_command('chmod -f 666 {}/* || true'.format(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, self.ROOT_CERT_NAME)) remote_shell.run_command('chmod 400 {}/*'.format(certs_node_dir)) if "client_cert" in extra_vars: client_cert_path = extra_vars["client_cert"] client_key_path = extra_vars["client_key"] remote_shell.run_command('mkdir -p ' + self.YSQLSH_CERT_DIR) # Give write permission in case file exists. If the command fails, ignore. remote_shell.run_command('chmod -f 666 {}/* || true'.format(self.YSQLSH_CERT_DIR)) remote_shell.put_file(root_cert_path, os.path.join(self.YSQLSH_CERT_DIR, self.CLIENT_ROOT_NAME)) remote_shell.put_file(client_cert_path, os.path.join(self.YSQLSH_CERT_DIR, self.CLIENT_CERT_NAME)) remote_shell.put_file(client_key_path, os.path.join(self.YSQLSH_CERT_DIR, self.CLIENT_KEY_NAME)) remote_shell.run_command('chmod 400 {}/*'.format(self.YSQLSH_CERT_DIR)) try: shutil.rmtree(common_path) except OSError as e: raise YBOpsRuntimeError("Error: %s - %s." % (e.filename, e.strerror))
def private_key_to_raw(private_key): private_key_pkcs8 = private_key.private_bytes( Encoding.DER, PrivateFormat.PKCS8, NoEncryption()) # Key is serialized in the PKCS8 format, but we need the raw key bytestring # The raw key is found from byte 36 to 68 in the formatted key. return private_key_pkcs8[PRIVATE_BYTES_START:PRIVATE_BYTES_END]
def export_private_key(key): """ Exports a private key in OpenSSL PEM format. """ return key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption())
def issue_cert(self, *identities, **kwargs): """issue_cert(*identities, common_name=None, organization_name=None, \ organization_unit_name=None) Issues a certificate. The certificate can be used for either servers or clients. All arguments must be text strings (``unicode`` on Python 2, ``str`` on Python 3). Args: identities: The identities that this certificate will be valid for. Most commonly, these are just hostnames, but we accept any of the following forms: - Regular hostname: ``example.com`` - Wildcard hostname: ``*.example.com`` - International Domain Name (IDN): ``café.example.com`` - IDN in A-label form: ``xn--caf-dma.example.com`` - IPv4 address: ``127.0.0.1`` - IPv6 address: ``::1`` - IPv4 network: ``10.0.0.0/8`` - IPv6 network: ``2001::/16`` - Email address: ``[email protected]`` These ultimately end up as "Subject Alternative Names", which are what modern programs are supposed to use when checking identity. common_name: Sets the "Common Name" of the certificate. This is a legacy field that used to be used to check identity. It's an arbitrary string with poorly-defined semantics, so `modern programs are supposed to ignore it <https://developers.google.com/web/updates/2017/03/chrome-58-deprecations#remove_support_for_commonname_matching_in_certificates>`__. But it might be useful if you need to test how your software handles legacy or buggy certificates. organization_name: Sets the "Organization Name" (O) attribute on the certificate. By default, it will be "trustme" suffixed with a version number. organization_unit_name: Sets the "Organization Unit Name" (OU) attribute on the certificate. By default, a random one will be generated. Returns: LeafCert: the newly-generated certificate. """ common_name = kwargs.pop("common_name", None) organization_name = kwargs.pop("organization_name", None) organization_unit_name = kwargs.pop("organization_unit_name", None) if kwargs: raise TypeError("unrecognized keyword arguments {}".format(kwargs)) if not identities and common_name is None: raise ValueError( "Must specify at least one identity or common name" ) key = rsa.generate_private_key( public_exponent=65537, key_size=_KEY_SIZE, backend=default_backend() ) ski_ext = self._certificate.extensions.get_extension_for_class( x509.SubjectKeyIdentifier) ski = ski_ext.value # Workaround a bug in cryptography 2.6 and earlier, where you have to # pass the extension object instead of the actual SKI object try: # The new way aki = x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski) except AttributeError: # The old way aki = x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(ski_ext) cert = ( _cert_builder_common( _name( organization_unit_name or u"Testing cert #" + random_text(), organization_name=organization_name, common_name=common_name, ), self._certificate.subject, key.public_key(), ) .add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=True, ) .add_extension(aki, critical=False) .add_extension( x509.SubjectAlternativeName( [_identity_string_to_x509(ident) for ident in identities] ), critical=True, ) .sign( private_key=self._private_key, algorithm=hashes.SHA256(), backend=default_backend(), ) ) chain_to_ca = [] ca = self while ca.parent_cert is not None: chain_to_ca.append(ca._certificate.public_bytes(Encoding.PEM)) ca = ca.parent_cert return LeafCert( key.private_bytes( Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption(), ), cert.public_bytes(Encoding.PEM), chain_to_ca, )
def dumps_private_key(raw_key): obj = OKPKey.dumps_public_key(raw_key.public_key()) d_bytes = raw_key.private_bytes(Encoding.Raw, PrivateFormat.Raw, NoEncryption()) obj['d'] = to_unicode(urlsafe_b64encode(d_bytes)) return obj
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # ------------------------------------------------------------------------------ """ Generate a private key to be used for the Trading Agent Competition. It prints the key in PEM format to the specified file. """ from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption import argparse from aea.crypto.base import Crypto parser = argparse.ArgumentParser("generate_private_key", description=__doc__) parser.add_argument("out_file", type=str, help="Where to save the private key.") if __name__ == '__main__': args = parser.parse_args() crypto = Crypto() pem = crypto._private_key.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()) # type: ignore file = open(args.out_file, "wb") file.write(pem) file.close()
def main(): with open("ca.crt", 'rb') as cacert_file: cacert = x509.load_pem_x509_certificate(cacert_file.read(), default_backend()) with open("ca.key", 'rb') as cakey_file: cakey = load_pem_private_key(cakey_file.read(), password=None, backend=default_backend()) name = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"BR"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Luz"), x509.NameAttribute(NameOID.COMMON_NAME, u"gabrielluz.com"), ]) private_key = rsa.generate_private_key(public_exponent=65537, key_size=4096, backend=default_backend()) public_key = private_key.public_key() builder = x509.CertificateBuilder() builder = builder.subject_name(name) builder = builder.public_key(public_key) builder = builder.issuer_name(cacert.subject) certificate_not_before = datetime.utcnow() certificate_not_after = datetime(2049, 12, 31, hour=23, minute=59, second=59) builder = builder.not_valid_before(certificate_not_before) builder = builder.not_valid_after(certificate_not_after) certificate_serial_number = x509.random_serial_number() builder = builder.serial_number(certificate_serial_number) builder = builder.add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) builder = builder.add_extension(x509.SubjectAlternativeName( [x509.DNSName("gabrielluz.com")]), critical=False) builder = builder.add_extension(x509.ExtendedKeyUsage( [ExtendedKeyUsageOID.SERVER_AUTH]), critical=True) builder = builder.add_extension(x509.KeyUsage(digital_signature=True, content_commitment=False, key_encipherment=True, data_encipherment=False, key_agreement=False, key_cert_sign=False, crl_sign=False, encipher_only=None, decipher_only=None), critical=True) builder = builder.add_extension( x509.SubjectKeyIdentifier.from_public_key(public_key), critical=False) builder = builder.add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key( cacert.public_key()), critical=False ) #from_issuer_subject_public_key if CA certs does contain this extension certificate = builder.sign(private_key=cakey, algorithm=hashes.SHA512(), backend=default_backend()) cert_pem = certificate.public_bytes(Encoding.PEM) with open("server.crt", "w") as text_file: text_file.write(cert_pem.decode()) privkey_pem = private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) #privkey with password = BestAvailableEncryption(b"password") with open("server.key", "w") as text_file: text_file.write(privkey_pem.decode())
def encode_encryption_secret_key(sk: EncryptionSecretKey) -> bytes: return sk.private_bytes( # type: ignore Encoding.Raw, PrivateFormat.Raw, NoEncryption())
def save(self, dest): data = self.ec_private.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) with open(dest, 'wb') as f: f.write(data)