Python cryptography.hazmat.primitives.asymmetric.ec.generate_private_key() Examples
The following are 30
code examples of cryptography.hazmat.primitives.asymmetric.ec.generate_private_key().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
cryptography.hazmat.primitives.asymmetric.ec
, or try the search function
.
Example #1
Source File: util.py From Spectrum-Access-System with Apache License 2.0 | 6 votes |
def generateCpiRsaKeys(): """Generate a private/public RSA 2048 key pair. Returns: A tuple (private_key, public key) as PEM string encoded. """ rsa_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend()) rsa_private_key = rsa_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) rsa_public_key = rsa_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) return rsa_private_key, rsa_public_key
Example #2
Source File: m2crypto.py From py-ipv8 with GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, curve=None, keystring=None, filename=None): """ Create a new M2Crypto secret key. Optionally load it from a string representation (in a file) or generate it using some curve. :param curve: the EllipticCurve object specifying the curve :param keystring: the string to load the key from :param filename: the filename to load the key from """ if curve: self.ec = ec.generate_private_key(curve, default_backend()) elif keystring: self.ec = self.key_from_pem(b"-----BEGIN EC PRIVATE KEY-----\n%s-----END EC PRIVATE KEY-----\n" % encodebytes(keystring)) elif filename: with open(filename, 'rb') as keyfile: self.ec = self.key_from_pem(keyfile.read())
Example #3
Source File: cert.py From scapy with GNU General Public License v2.0 | 6 votes |
def fill_and_store(self, modulus=None, modulusLen=None, pubExp=None): pubExp = pubExp or 65537 if not modulus: real_modulusLen = modulusLen or 2048 private_key = rsa.generate_private_key(public_exponent=pubExp, key_size=real_modulusLen, backend=default_backend()) self.pubkey = private_key.public_key() else: real_modulusLen = len(binrepr(modulus)) if modulusLen and real_modulusLen != modulusLen: warning("modulus and modulusLen do not match!") pubNum = rsa.RSAPublicNumbers(n=modulus, e=pubExp) self.pubkey = pubNum.public_key(default_backend()) # Lines below are only useful for the legacy part of pkcs1.py pubNum = self.pubkey.public_numbers() self._modulusLen = real_modulusLen self._modulus = pubNum.n self._pubExp = pubNum.e
Example #4
Source File: fields.py From PGPy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _generate(self, key_size): if any(c != 0 for c in self): # pragma: no cover raise PGPError("key is already populated") # generate some big numbers! pk = rsa.generate_private_key(65537, key_size, default_backend()) pkn = pk.private_numbers() self.n = MPI(pkn.public_numbers.n) self.e = MPI(pkn.public_numbers.e) self.d = MPI(pkn.d) self.p = MPI(pkn.p) self.q = MPI(pkn.q) # from the RFC: # "- MPI of u, the multiplicative inverse of p, mod q." # or, simply, p^-1 mod p # rsa.rsa_crt_iqmp(p, q) normally computes q^-1 mod p, # so if we swap the values around we get the answer we want self.u = MPI(rsa.rsa_crt_iqmp(pkn.q, pkn.p)) del pkn del pk self._compute_chksum()
Example #5
Source File: fields.py From PGPy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def _generate(self, key_size): if any(c != 0 for c in self): # pragma: no cover raise PGPError("key is already populated") # generate some big numbers! pk = dsa.generate_private_key(key_size, default_backend()) pkn = pk.private_numbers() self.p = MPI(pkn.public_numbers.parameter_numbers.p) self.q = MPI(pkn.public_numbers.parameter_numbers.q) self.g = MPI(pkn.public_numbers.parameter_numbers.g) self.y = MPI(pkn.public_numbers.y) self.x = MPI(pkn.x) del pkn del pk self._compute_chksum()
Example #6
Source File: ecdsakey.py From imoocc with GNU General Public License v2.0 | 6 votes |
def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None): """ Generate a new private ECDSA key. This factory function can be used to generate a new host key or authentication key. :param function progress_func: Not used for this type of key. :returns: A new private key (`.ECDSAKey`) object """ if bits is not None: curve = cls._ECDSA_CURVES.get_by_key_length(bits) if curve is None: raise ValueError("Unsupported key length: %d"%(bits)) curve = curve.curve_class() private_key = ec.generate_private_key(curve, backend=default_backend()) return ECDSAKey(vals=(private_key, private_key.public_key())) ### internals...
Example #7
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
def generate_rsa_private_key(key_size=2048, public_exponent=65537): """ Generate RSA private key. Args: key_size (int): RSA key size public_exponent (int): Key public exponent Return: rsa.RSAPrivateKey """ return rsa.generate_private_key( public_exponent=public_exponent, key_size=key_size, backend=cryptography_default_backend )
Example #8
Source File: tls.py From dcos-e2e with Apache License 2.0 | 6 votes |
def generate_rsa_private_key(key_size=2048, public_exponent=65537): """ Generate RSA private key. Args: key_size (int): RSA key size public_exponent (int): Key public exponent Return: rsa.RSAPrivateKey """ return rsa.generate_private_key( public_exponent=public_exponent, key_size=key_size, backend=cryptography_default_backend )
Example #9
Source File: keyexchange.py From scapy with GNU General Public License v2.0 | 6 votes |
def fill_missing(self): s = self.tls_session params = s.client_kx_ecdh_params s.client_kx_privkey = ec.generate_private_key(params, default_backend()) pubkey = s.client_kx_privkey.public_key() x = pubkey.public_numbers().x y = pubkey.public_numbers().y self.ecdh_Yc = (b"\x04" + pkcs_i2osp(x, params.key_size // 8) + pkcs_i2osp(y, params.key_size // 8)) if s.client_kx_privkey and s.server_kx_pubkey: pms = s.client_kx_privkey.exchange(ec.ECDH(), s.server_kx_pubkey) s.pre_master_secret = pms s.compute_ms_and_derive_keys()
Example #10
Source File: encrypted_queries_tools.py From github-token with GNU General Public License v3.0 | 6 votes |
def encrypt(message, receiver_public_key): sender_private_key = ec.generate_private_key(ec.SECP256K1(), backend) shared_key = sender_private_key.exchange(ec.ECDH(), receiver_public_key) sender_public_key = sender_private_key.public_key() point = sender_public_key.public_numbers().encode_point() iv = '000000000000' xkdf = x963kdf.X963KDF( algorithm = hashes.SHA256(), length = 32, sharedinfo = '', backend = backend ) key = xkdf.derive(shared_key) encryptor = Cipher( algorithms.AES(key), modes.GCM(iv), backend = backend ).encryptor() ciphertext = encryptor.update(message) + encryptor.finalize() return point + encryptor.tag + ciphertext
Example #11
Source File: crypto.py From fabric-sdk-py with Apache License 2.0 | 5 votes |
def generate_private_key(self): """Generate asymmetric key pair. :return: An private key object which include public key object. """
Example #12
Source File: fields.py From PGPy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _generate(self, oid): if any(c != 0 for c in self): # pragma: no cover raise PGPError("Key is already populated!") self.oid = EllipticCurveOID(oid) if not self.oid.can_gen: raise ValueError("Curve not currently supported: {}".format(oid.name)) pk = ec.generate_private_key(self.oid.curve(), default_backend()) pubn = pk.public_key().public_numbers() self.p = ECPoint.from_values(self.oid.key_size, ECPointFormat.Standard, MPI(pubn.x), MPI(pubn.y)) self.s = MPI(pk.private_numbers().private_value) self._compute_chksum()
Example #13
Source File: crypto.py From fabric-sdk-py with Apache License 2.0 | 5 votes |
def generate_private_key(self): """ECDSA key pair generation by current curve. :return: A private key object which include public key object. """ return ec.generate_private_key(self.curve, default_backend())
Example #14
Source File: utils.py From django-ca with GNU General Public License v3.0 | 5 votes |
def generate_private_key(key_size, key_type, ecc_curve): """Generate a private key. This function assumes that you called :py:func:`~django_ca.utils.validate_key_parameters` on the input values and does not do any sanity checks on its own. Parameters ---------- key_size : int The size of the private key (not used for ECC keys). key_type : {'RSA', 'DSA', 'ECC'} The type of the private key. ecc_curve : :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` The ECC curve to use for an ECC key. Returns ------- key A private key of the appropriate type. """ if key_type == 'DSA': private_key = dsa.generate_private_key(key_size=key_size, backend=default_backend()) elif key_type == 'ECC': private_key = ec.generate_private_key(ecc_curve, default_backend()) else: private_key = rsa.generate_private_key(public_exponent=65537, key_size=key_size, backend=default_backend()) return private_key
Example #15
Source File: crypto.py From fabric-sdk-py with Apache License 2.0 | 5 votes |
def encrypt(self, public_key, plain_text): """ECIES encrypt plain text. First create a ephemeral ecdsa key pair, then serialize the public key for part of result. Then derived a shared key based ecdh, using the key based hkdf to generate aes key and hmac key, using aes-256-cfb to generate the part of result. Last using hmac-sha3 and the part of previous step to generate last part of result. :param public_key: public key :param plain_text: plain text :return: cipher text """ ephemeral_private_key = self.generate_private_key() rb = ephemeral_private_key.public_key().public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) z = ephemeral_private_key.exchange(ec.ECDH(), public_key) hkdf_output = Hkdf(salt=None, input_key_material=z, hash=self._hash) \ .expand(length=AES_KEY_LENGTH + HMAC_KEY_LENGTH) aes_key = hkdf_output[:AES_KEY_LENGTH] hmac_key = hkdf_output[AES_KEY_LENGTH:AES_KEY_LENGTH + HMAC_KEY_LENGTH] aes_cipher = AES.new(aes_key, AES.MODE_CFB) em = aes_cipher.iv + aes_cipher.encrypt(plain_text) mac = hmac.new(hmac_key, em, self._hash) d = mac.digest() return rb + em + d
Example #16
Source File: ecc.py From synapse with Apache License 2.0 | 5 votes |
def generate(): ''' Generate a new ECC PriKey instance. Returns: PriKey: A new PriKey instance. ''' return PriKey(c_ec.generate_private_key( c_ec.SECP384R1(), default_backend() ))
Example #17
Source File: ecies.py From trinity with MIT License | 5 votes |
def generate_privkey() -> datatypes.PrivateKey: """Generate a new SECP256K1 private key and return it""" privkey = ec.generate_private_key(CURVE, default_backend()) return keys.PrivateKey(pad32(int_to_big_endian(privkey.private_numbers().private_value)))
Example #18
Source File: tls.py From dcos-e2e with Apache License 2.0 | 5 votes |
def generate_ec_private_key(curve=None): """ Generate EC private key. Args: curve (ec.EllipticCurve): EC if not provided SECP384R1 used. Return: ec.EllipticCurvePrivateKey """ curve = ec.SECP384R1() if curve is None else curve return ec.generate_private_key( curve=curve, backend=cryptography_default_backend )
Example #19
Source File: tls.py From dcos-e2e with Apache License 2.0 | 5 votes |
def generate_dsa_private_key(key_size=1024): """ Generate DSA private key. Args: key_size (int): Key size of DSA key. Return: ec.DSAPrivateKey """ return dsa.generate_private_key( key_size=key_size, backend=cryptography_default_backend )
Example #20
Source File: tls.py From dcos-e2e with Apache License 2.0 | 5 votes |
def generate_ec_private_key(curve=None): """ Generate EC private key. Args: curve (ec.EllipticCurve): EC if not provided SECP384R1 used. Return: ec.EllipticCurvePrivateKey """ curve = ec.SECP384R1() if curve is None else curve return ec.generate_private_key( curve=curve, backend=cryptography_default_backend )
Example #21
Source File: plugin_x509.py From deen with Apache License 2.0 | 5 votes |
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
Example #22
Source File: _utilities.py From sros2 with Apache License 2.0 | 5 votes |
def build_key_and_cert(subject_name, *, ca=False, ca_key=None, issuer_name=''): if not issuer_name: issuer_name = subject_name # DDS-Security section 9.3.1 calls for prime256v1, for which SECP256R1 is an alias private_key = ec.generate_private_key(ec.SECP256R1, cryptography_backend()) if not ca_key: ca_key = private_key if ca: extension = x509.BasicConstraints(ca=True, path_length=1) else: extension = x509.BasicConstraints(ca=False, path_length=None) utcnow = datetime.datetime.utcnow() builder = x509.CertificateBuilder( ).issuer_name( issuer_name ).serial_number( x509.random_serial_number() ).not_valid_before( # Using a day earlier here to prevent Connext (5.3.1) from complaining # when extracting it from the permissions file and thinking it's in the future # https://github.com/ros2/ci/pull/436#issuecomment-624874296 utcnow - datetime.timedelta(days=1) ).not_valid_after( # TODO: This should not be hard-coded utcnow + datetime.timedelta(days=3650) ).public_key( private_key.public_key() ).subject_name( subject_name ).add_extension( extension, critical=ca ) cert = builder.sign(ca_key, hashes.SHA256(), cryptography_backend()) return (cert, private_key)
Example #23
Source File: Mastodon.py From Mastodon.py with MIT License | 5 votes |
def push_subscription_generate_keys(self): """ Generates a private key, public key and shared secret for use in webpush subscriptions. Returns two dicts: One with the private key and shared secret and another with the public key and shared secret. """ if not IMPL_HAS_CRYPTO: raise NotImplementedError('To use the crypto tools, please install the webpush feature dependencies.') push_key_pair = ec.generate_private_key(ec.SECP256R1(), default_backend()) push_key_priv = push_key_pair.private_numbers().private_value crypto_ver = cryptography.__version__ if len(crypto_ver) < 5: crypto_ver += ".0" if bigger_version(crypto_ver, "2.5.0") == crypto_ver: push_key_pub = push_key_pair.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) else: push_key_pub = push_key_pair.public_key().public_numbers().encode_point() push_shared_secret = os.urandom(16) priv_dict = { 'privkey': push_key_priv, 'auth': push_shared_secret } pub_dict = { 'pubkey': push_key_pub, 'auth': push_shared_secret } return priv_dict, pub_dict
Example #24
Source File: test_EC.py From python-jose with MIT License | 5 votes |
def test_cryptography_sig_component_length(algorithm, expected_length): # Put mapping inside here to avoid more complex handling for test runs that do not have pyca/cryptography mapping = { ALGORITHMS.ES256: CryptographyEc.SECP256R1, ALGORITHMS.ES384: CryptographyEc.SECP384R1, ALGORITHMS.ES512: CryptographyEc.SECP521R1, } key = CryptographyECKey( CryptographyEc.generate_private_key(mapping[algorithm](), backend=CryptographyBackend()), algorithm ) assert key._sig_component_length() == expected_length
Example #25
Source File: util.py From Spectrum-Access-System with Apache License 2.0 | 5 votes |
def generateCpiEcKeys(): """Generate a private/public EC SECP256R1 key pair. Returns: A tuple (private_key, public key) as PEM string encoded. """ ec_key = ec.generate_private_key(ec.SECP256R1(), default_backend()) ec_private_key = ec_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption()) ec_public_key = ec_key.public_key().public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) return ec_private_key, ec_public_key
Example #26
Source File: test.py From signxml with Apache License 2.0 | 5 votes |
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()))
Example #27
Source File: ecdsalib.py From virtualchain with GNU General Public License v3.0 | 5 votes |
def __init__(self, private_key=None, compressed=True): """ Takes in a private key/secret exponent. """ pk_i = None if private_key is None: pk_i = ec.generate_private_key(ec.SECP256K1(), default_backend()).private_numbers().private_value else: pk_i = keylib.key_formatting.encode_privkey(private_key, 'decimal') privkey_str = '{:064x}'.format(pk_i) assert len(privkey_str) == 64 self._ecdsa_private_key_string = privkey_str.decode('hex') self._compressed = compressed
Example #28
Source File: ckeygen.py From learn_python3_spider with MIT License | 5 votes |
def generateECDSAkey(options): from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import ec if not options['bits']: options['bits'] = 256 # OpenSSH supports only mandatory sections of RFC5656. # See https://www.openssh.com/txt/release-5.7 curve = b'ecdsa-sha2-nistp' + str(options['bits']).encode('ascii') keyPrimitive = ec.generate_private_key( curve=keys._curveTable[curve], backend=default_backend() ) key = keys.Key(keyPrimitive) _saveKey(key, options)
Example #29
Source File: ckeygen.py From learn_python3_spider with MIT License | 5 votes |
def generateDSAkey(options): from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import dsa if not options['bits']: options['bits'] = 1024 keyPrimitive = dsa.generate_private_key( key_size=int(options['bits']), backend=default_backend(), ) key = keys.Key(keyPrimitive) _saveKey(key, options)
Example #30
Source File: ckeygen.py From learn_python3_spider with MIT License | 5 votes |
def generateRSAkey(options): from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa if not options['bits']: options['bits'] = 1024 keyPrimitive = rsa.generate_private_key( key_size=int(options['bits']), public_exponent=65537, backend=default_backend(), ) key = keys.Key(keyPrimitive) _saveKey(key, options)