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 test_generate_unknown_curve(self, backend): with raises_unsupported_algorithm( exceptions._Reasons.UNSUPPORTED_ELLIPTIC_CURVE ): ec.generate_private_key(DummyCurve(), backend) assert backend.elliptic_curve_signature_algorithm_supported( ec.ECDSA(hashes.SHA256()), DummyCurve() ) is False
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 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 generateKeyPair(self, keyName, params): """ Generate a pair of asymmetric keys. :param Name keyName: The name of the key pair. :param KeyParams params: The parameters of the key. """ if (params.getKeyType() == KeyType.RSA or params.getKeyType() == KeyType.ECDSA): if params.getKeyType() == KeyType.RSA: privateKey = rsa.generate_private_key( public_exponent = 65537, key_size = params.getKeySize(), backend = default_backend()) else: privateKey = ec.generate_private_key( PrivateKeyStorage.getEcCurve(params.getKeySize()), default_backend()) self.setPublicKeyForKeyName( keyName, params.getKeyType(), privateKey.public_key().public_bytes( encoding = serialization.Encoding.DER, format = serialization.PublicFormat.SubjectPublicKeyInfo)) self.setPrivateKeyForKeyName( keyName, params.getKeyType(), privateKey.private_bytes( encoding = serialization.Encoding.DER, format = serialization.PrivateFormat.PKCS8, encryption_algorithm = serialization.NoEncryption())) # TODO generate ECDSA keys else: raise RuntimeError("generateKeyPair: KeyType is not supported")
def create_jws_keypair(private_key_path, public_key_path): """Create an ECDSA key pair using an secp256r1, or NIST P-256, curve. :param private_key_path: location to save the private key :param public_key_path: location to save the public key """ private_key = ec.generate_private_key(ec.SECP256R1(), default_backend()) with open(private_key_path, 'wb') as f: f.write( private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() ) ) public_key = private_key.public_key() with open(public_key_path, 'wb') as f: f.write( public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo ) )
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 test_public_bytes_openssh(self, backend): _skip_curve_unsupported(backend, ec.SECP192R1()) _skip_curve_unsupported(backend, ec.SECP256R1()) key_bytes = load_vectors_from_file( os.path.join( "asymmetric", "PEM_Serialization", "ec_public_key.pem" ), lambda pemfile: pemfile.read(), mode="rb" ) key = serialization.load_pem_public_key(key_bytes, backend) ssh_bytes = key.public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH ) assert ssh_bytes == ( b"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy" b"NTYAAABBBCS8827s9rUZyxZTi/um01+oIlWrwLHOjQxRU9CDAndom00zVAw5BRrI" b"KtHB+SWD4P+sVJTARSq1mHt8kOIWrPc=" ) key = ec.generate_private_key(ec.SECP192R1(), backend).public_key() with pytest.raises(ValueError): key.public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH )
def generate_csr(domains, key_path, csr_path, key_type=RSA_KEY_TYPE): """ Generate a private key, and a CSR for the given domains using this key. :param domains: the domain names to include in the CSR :type domains: `list` of `str` :param str key_path: path to the private key that will be generated :param str csr_path: path to the CSR that will be generated :param str key_type: type of the key (misc.RSA_KEY_TYPE or misc.ECDSA_KEY_TYPE) """ if key_type == RSA_KEY_TYPE: key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) elif key_type == ECDSA_KEY_TYPE: key = ec.generate_private_key(ec.SECP384R1(), default_backend()) key = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) key = crypto.load_privatekey(crypto.FILETYPE_PEM, key) else: raise ValueError('Invalid key type: {0}'.format(key_type)) key_bytes = crypto.dump_privatekey(crypto.FILETYPE_PEM, key) with open(key_path, 'wb') as file: file.write(key_bytes) csr_bytes = crypto_util.make_csr(key_bytes, domains) with open(csr_path, 'wb') as file: file.write(csr_bytes)
def test_verify_signature_ECC(self, mock_get_pub_key): data = b'224626ae19824466f2a7f39ab7b80f7f' # test every ECC curve for curve in signature_utils.ECC_CURVES: key_type_name = 'ECC_' + curve.name.upper() try: signature_utils.SignatureKeyType.lookup(key_type_name) except exception.SignatureVerificationError: import warnings warnings.warn("ECC curve '%s' not supported" % curve.name) continue # Create a private key to use private_key = ec.generate_private_key(curve, default_backend()) mock_get_pub_key.return_value = private_key.public_key() for hash_name, hash_alg in signature_utils.HASH_METHODS.items(): signer = private_key.signer( ec.ECDSA(hash_alg) ) signer.update(data) signature = base64.b64encode(signer.finalize()) image_props = {CERT_UUID: 'fea14bc2-d75f-4ba5-bccc-b5c924ad0693', HASH_METHOD: hash_name, KEY_TYPE: key_type_name, SIGNATURE: signature} verifier = signature_utils.get_verifier(None, image_props) verifier.update(data) verifier.verify()
def main(): parser = argparse.ArgumentParser(description='Encrypt messages to Oraclize using Elliptic Curve Integrated Encryption Scheme.') parser.add_argument('-e', '--encrypt', dest='mode', action='store_const', const='encrypt', help='Encrypt a string. Requires -p') parser.add_argument('-p', '--with-public-key', dest='public_key', action='store', help='Use the provided hex-encoded public key to encrypt') parser.add_argument('-d', '--decrypt', dest='mode', action='store_const', const='decrypt', help='Decrypt a string. Provide private key in Wallet Import Format in standard input, or first line of standard input if encrypted text is also provided on standard input. DO NOT PUT YOUR PRIVATE KEY ON THE COMMAND LINE.') parser.add_argument('-g', '--generate', dest='mode', action='store_const', const='generate', help='Generates a public and a private key') parser.add_argument('text', nargs='?', action='store', help='String to encrypt, decrypt. If not specified, standard input will be used.') args = parser.parse_args() if args.mode != 'encrypt' and args.mode != 'decrypt' and args.mode != 'generate': parser.print_help() return if args.mode == 'encrypt' and not args.public_key: print(args.public_key) print("Please, provide a valid public key") return if args.mode == 'encrypt': if args.public_key: pub_key = hex_to_key(args.public_key) if args.text: print(base64.b64encode(encrypt(args.text, pub_key)).decode('utf-8')) return else: print(base64.b64encode(encrypt(sys.stdin.read(), pub_key)).decode('utf-8')) return elif args.mode == 'decrypt': if args.text: print("Insert your public key") public_key = sys.stdin.read() print("Insert your private key:") private_key = sys.stdin.read() private_key = hex_to_priv_key(private_key, public_key) text = base64.b64decode(args.text) else: print("Insert your public key") public_key = sys.stdin.read() print("\nInsert your private key:") private_key = sys.stdin.read() private_key = hex_to_priv_key(private_key, public_key) print("\nInsert encrypted text") text = base64.b64decode(sys.stdin.read()) print(decrypt(text, private_key)) if args.mode == 'generate': receiver_private_key = ec.generate_private_key(ec.SECP256K1(), backend) receiver_public_key = receiver_private_key.public_key() number = receiver_private_key.private_numbers() print( "Public Key:", receiver_public_key.public_bytes( encoding=serialization.Encoding.X962, format=serialization.PublicFormat.UncompressedPoint ).hex() ) print("Private Key:", hex(number.private_value))
def test_encode(self): for content_encoding in ["aesgcm", "aes128gcm"]: recv_key = ec.generate_private_key( ec.SECP256R1, default_backend()) subscription_info = self._gen_subscription_info(recv_key) data = "Mary had a little lamb, with some nice mint jelly" push = WebPusher(subscription_info) encoded = push.encode(data, content_encoding=content_encoding) """ crypto_key = base64.urlsafe_b64encode( self._get_pubkey_str(recv_key) ).strip(b'=') """ # Convert these b64 strings into their raw, binary form. raw_salt = None if 'salt' in encoded: raw_salt = base64.urlsafe_b64decode( push._repad(encoded['salt'])) raw_dh = None if content_encoding != "aes128gcm": raw_dh = base64.urlsafe_b64decode( push._repad(encoded['crypto_key'])) raw_auth = base64.urlsafe_b64decode( push._repad(subscription_info['keys']['auth'])) decoded = http_ece.decrypt( encoded['body'], salt=raw_salt, dh=raw_dh, private_key=recv_key, auth_secret=raw_auth, version=content_encoding ) eq_(decoded.decode('utf8'), data)
def test_unknown_signature_algoritm(self, backend): _skip_curve_unsupported(backend, ec.SECP192R1()) key = ec.generate_private_key(ec.SECP192R1(), backend) with raises_unsupported_algorithm( exceptions._Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): key.signer(DummySignatureAlgorithm()) with raises_unsupported_algorithm( exceptions._Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): key.sign(b"somedata", DummySignatureAlgorithm()) with raises_unsupported_algorithm( exceptions._Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): key.public_key().verifier(b"", DummySignatureAlgorithm()) with raises_unsupported_algorithm( exceptions._Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM ): key.public_key().verify( b"signature", b"data", DummySignatureAlgorithm() ) assert backend.elliptic_curve_signature_algorithm_supported( DummySignatureAlgorithm(), ec.SECP192R1() ) is False
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_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 encrypt(pubkey, data): public_key = _pub_to_public(pubkey) private_key = ec.generate_private_key(ec.SECP256K1(), openssl.backend) secret = private_key.exchange(ec.ECDH(), public_key) key = hashlib.sha512(secret).digest() enckey = key[0:32] mackey = key[32:64] iv = os.urandom(16) padder = padding.PKCS7(128).padder() paddeddata = padder.update(data) + padder.finalize() cipher = Cipher(algorithms.AES(enckey), modes.CBC(iv), openssl.backend) encryptor = cipher.encryptor() ciphertext = encryptor.update(paddeddata) + encryptor.finalize() s = serialize.Serializer() s.bytes(iv) s.uint(0x02ca, 2) public_numbers = private_key.public_key().public_numbers() x = public_numbers.x.to_bytes(32, 'big').lstrip(b'\x00') s.uint(len(x), 2) s.bytes(x) y = public_numbers.y.to_bytes(32, 'big').lstrip(b'\x00') s.uint(len(y), 2) s.bytes(y) s.bytes(ciphertext) maccer = HMAC(mackey, hashes.SHA256(), openssl.backend) maccer.update(s.data) mac = maccer.finalize() s.bytes(mac) return s.data
def test_build_ca_request_with_ec(self, backend): if backend._lib.OPENSSL_VERSION_NUMBER < 0x10001000: pytest.skip("Requires a newer OpenSSL. Must be >= 1.0.1") _skip_curve_unsupported(backend, ec.SECP256R1()) private_key = ec.generate_private_key(ec.SECP256R1(), backend) request = x509.CertificateSigningRequestBuilder().subject_name( x509.Name([ x509.NameAttribute(x509.OID_STATE_OR_PROVINCE_NAME, u'Texas'), ]) ).add_extension( x509.BasicConstraints(ca=True, path_length=2), critical=True ).sign(private_key, hashes.SHA1(), backend) assert isinstance(request.signature_hash_algorithm, hashes.SHA1) public_key = request.public_key() assert isinstance(public_key, ec.EllipticCurvePublicKey) subject = request.subject assert isinstance(subject, x509.Name) assert list(subject) == [ x509.NameAttribute(x509.OID_STATE_OR_PROVINCE_NAME, u'Texas'), ] basic_constraints = request.extensions.get_extension_for_oid( x509.OID_BASIC_CONSTRAINTS ) assert basic_constraints.value.ca is True assert basic_constraints.value.path_length == 2
def test_sign_ec_key_unsupported(self, backend): if backend._lib.CRYPTOGRAPHY_OPENSSL_LESS_THAN_101: pytest.skip("Requires a newer OpenSSL. Must be >= 1.0.1") _skip_curve_unsupported(backend, ec.SECP256R1()) private_key = ec.generate_private_key(ec.SECP256R1(), backend) invalidity_date = x509.InvalidityDate(datetime.datetime(2002, 1, 1, 0, 0)) ian = x509.IssuerAlternativeName([x509.UniformResourceIdentifier(u"https://cryptography.io")]) revoked_cert0 = ( x509.RevokedCertificateBuilder() .serial_number(2) .revocation_date(datetime.datetime(2012, 1, 1, 1, 1)) .add_extension(invalidity_date, False) .build(backend) ) last_update = datetime.datetime(2002, 1, 1, 12, 1) next_update = datetime.datetime(2030, 1, 1, 12, 1) builder = ( x509.CertificateRevocationListBuilder() .issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u"cryptography.io CA")])) .last_update(last_update) .next_update(next_update) .add_revoked_certificate(revoked_cert0) .add_extension(ian, False) ) crl = builder.sign(private_key, hashes.SHA256(), backend) assert crl.extensions.get_extension_for_class(x509.IssuerAlternativeName).value == ian assert crl[0].serial_number == revoked_cert0.serial_number assert crl[0].revocation_date == revoked_cert0.revocation_date assert len(crl[0].extensions) == 1 ext = crl[0].extensions.get_extension_for_class(x509.InvalidityDate) assert ext.critical is False assert ext.value == invalidity_date
def test_lib_crypto_ecc_exchange(self): spvk1 = s_ecc.PriKey.generate() spbk1 = spvk1.public() spvk2 = s_ecc.PriKey.generate() spbk2 = spvk2.public() k1 = (spvk1.exchange(spbk2)) k2 = (spvk2.exchange(spbk1)) self.eq(k1, k2) # Curves must be the same _pkd = c_ec.generate_private_key( c_ec.SECP192R1(), # We don't use this curve default_backend() ) prkdiff = s_ecc.PriKey(_pkd) pbkdiff = prkdiff.public() self.raises(s_exc.BadEccExchange, spvk1.exchange, pbkdiff) self.raises(s_exc.BadEccExchange, prkdiff.exchange, spbk1) # Do a demonstrative ephemeral exchange epvk1 = s_ecc.PriKey.generate() epbk1 = epvk1.public() epvk2 = s_ecc.PriKey.generate() epbk2 = epvk2.public() # assume epbk2 is sent to the owner of pvk1 z1e = epvk1.exchange(epbk2) z1s = spvk1.exchange(spbk2) z1 = z1e + z1s # assume epbk1 is sent to the owner of pvk2 z2e = epvk2.exchange(epbk1) z2s = spvk2.exchange(spbk1) z2 = z2e + z2s self.eq(z1, z2) # run through kdf kdf1 = c_hkdf.HKDF(c_hashes.SHA256(), length=64, salt=None, info=b'test', backend=default_backend()) k1 = kdf1.derive(z1) k1tx, k1rx = k1[32:], k1[:32] kdf2 = c_hkdf.HKDF(c_hashes.SHA256(), length=64, salt=None, info=b'test', backend=default_backend()) k2 = kdf2.derive(z2) k2rx, k2tx = k2[32:], k2[:32] self.eq(k1tx, k2rx) self.eq(k1rx, k2tx) self.ne(k1tx, k2tx)
def test_signature_not_bytes(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) key = ec.generate_private_key(ec.SECP256R1(), backend) public_key = key.public_key() with pytest.raises(TypeError), \ pytest.warns(CryptographyDeprecationWarning): public_key.verifier(1234, ec.ECDSA(hashes.SHA256()))
def fill_missing(self): """ We do not want TLSServerKeyExchange.build() to overload and recompute things everytime it is called. This method can be called specifically to have things filled in a smart fashion. XXX We should account for the point_format (before 'point' filling). """ s = self.tls_session if self.curve_type is None: self.curve_type = _tls_ec_curve_types["named_curve"] if self.named_curve is None: curve = ec.SECP256R1() s.server_kx_privkey = ec.generate_private_key(curve, default_backend()) curve_id = 0 for cid, name in six.iteritems(_tls_named_curves): if name == curve.name: curve_id = cid break self.named_curve = curve_id else: curve_name = _tls_named_curves.get(self.named_curve) if curve_name is None: # this fallback is arguable curve = ec.SECP256R1() else: curve_cls = ec._CURVE_TYPES.get(curve_name) if curve_cls is None: # this fallback is arguable curve = ec.SECP256R1() else: curve = curve_cls() s.server_kx_privkey = ec.generate_private_key(curve, default_backend()) if self.point is None: pubkey = s.server_kx_privkey.public_key() self.point = pubkey.public_numbers().encode_point() # else, we assume that the user wrote the server_kx_privkey by himself if self.pointlen is None: self.pointlen = len(self.point) if not s.client_kx_ecdh_params: s.client_kx_ecdh_params = curve
def test_verify(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) message = b"one little message" algorithm = ec.ECDSA(hashes.SHA1()) private_key = ec.generate_private_key(ec.SECP256R1(), backend) signature = private_key.sign(message, algorithm) public_key = private_key.public_key() public_key.verify(signature, message, algorithm)
def get_new_private_key_in_pem_format(self): private_key = ec.generate_private_key( ec.SECP256R1(), default_backend()) return private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() )
def __init__(self, curve_id): try: curve, _ = _curves[curve_id] except KeyError: # pragma: no cover, other curves not registered raise ValueError('Unknown EC curve %s' % curve_id.decode()) from None self._priv_key = ec.generate_private_key(curve, backend)
def test_prehashed_unsupported_in_verifier_ctx(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) private_key = ec.generate_private_key(ec.SECP256R1(), backend) public_key = private_key.public_key() with pytest.raises(TypeError): public_key.verifier( b"0" * 64, ec.ECDSA(Prehashed(hashes.SHA1())) )
def generate(cls, curve_id): """Generate a new ECDSA private key""" curve, hash_alg = cls.lookup_curve(curve_id) priv_key = ec.generate_private_key(curve, backend) priv = priv_key.private_numbers() pub = priv.public_numbers return cls(curve_id, hash_alg, pub, priv, priv_key)
def test_sign_prehashed_digest_mismatch(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) message = b"one little message" h = hashes.Hash(hashes.SHA1(), backend) h.update(message) data = h.finalize() algorithm = ec.ECDSA(Prehashed(hashes.SHA256())) private_key = ec.generate_private_key(ec.SECP256R1(), backend) with pytest.raises(ValueError): private_key.sign(data, algorithm)
def generate(curve=ec.SECP256R1(), progress_func=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 """ private_key = ec.generate_private_key(curve, backend=default_backend()) return ECDSAKey(vals=(private_key, private_key.public_key()))
def __init__(self, xml): logging.debug('Generating new pub/priv key pair') self.dh = ec.generate_private_key(SECP521R1(), default_backend()) self.peer_public_key = self.pubkey_from_xml(xml) logging.debug('Imported peer public key') self.shared_key = self.dh.exchange(ec.ECDH(), self.peer_public_key) sha256 = hashes.Hash(hashes.SHA256(), backend=default_backend()) sha256.update(self.shared_key) self.derived_key = sha256.finalize()
def generate_private_key(key_type): """ Generates a new private key based on key_type. Valid key types: RSA2048, RSA4096', 'ECCPRIME192V1', 'ECCPRIME256V1', 'ECCSECP192R1', 'ECCSECP224R1', 'ECCSECP256R1', 'ECCSECP384R1', 'ECCSECP521R1', 'ECCSECP256K1', 'ECCSECT163K1', 'ECCSECT233K1', 'ECCSECT283K1', 'ECCSECT409K1', 'ECCSECT571K1', 'ECCSECT163R2', 'ECCSECT233R1', 'ECCSECT283R1', 'ECCSECT409R1', 'ECCSECT571R2' :param key_type: :return: """ _CURVE_TYPES = { "ECCPRIME192V1": ec.SECP192R1(), "ECCPRIME256V1": ec.SECP256R1(), "ECCSECP192R1": ec.SECP192R1(), "ECCSECP224R1": ec.SECP224R1(), "ECCSECP256R1": ec.SECP256R1(), "ECCSECP384R1": ec.SECP384R1(), "ECCSECP521R1": ec.SECP521R1(), "ECCSECP256K1": ec.SECP256K1(), "ECCSECT163K1": ec.SECT163K1(), "ECCSECT233K1": ec.SECT233K1(), "ECCSECT283K1": ec.SECT283K1(), "ECCSECT409K1": ec.SECT409K1(), "ECCSECT571K1": ec.SECT571K1(), "ECCSECT163R2": ec.SECT163R2(), "ECCSECT233R1": ec.SECT233R1(), "ECCSECT283R1": ec.SECT283R1(), "ECCSECT409R1": ec.SECT409R1(), "ECCSECT571R2": ec.SECT571R1(), } if key_type not in CERTIFICATE_KEY_TYPES: raise Exception("Invalid key type: {key_type}. Supported key types: {choices}".format( key_type=key_type, choices=",".join(CERTIFICATE_KEY_TYPES) )) if 'RSA' in key_type: key_size = int(key_type[3:]) return rsa.generate_private_key( public_exponent=65537, key_size=key_size, backend=default_backend() ) elif 'ECC' in key_type: return ec.generate_private_key( curve=_CURVE_TYPES[key_type], backend=default_backend() )
def generate_ec_certificate(common_name, curve=ec.SECP256R1, alternative_names=[]): key = ec.generate_private_key(backend=default_backend(), curve=curve) subject = issuer = x509.Name( [x509.NameAttribute(x509.NameOID.COMMON_NAME, common_name)]) builder = (x509.CertificateBuilder().subject_name(subject).issuer_name( issuer).public_key(key.public_key()).serial_number( x509.random_serial_number()).not_valid_before( datetime.datetime.utcnow()).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=10))) if alternative_names: builder = builder.add_extension( x509.SubjectAlternativeName( [x509.DNSName(name) for name in alternative_names]), critical=False, ) cert = builder.sign(key, hashes.SHA256(), default_backend()) return cert, key
def generate_metahash_address(): print("Step 1. Generate private and public keys. Take part of the public " "key that equals to 65 bytes.") private_key = ec.generate_private_key(ec.SECP256K1(), default_backend()) private_key_pem = private_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) save_to_file(private_key_pem.decode("utf-8"), "mh_private.pem") pub_key = private_key.public_key() pub_key_pem = pub_key.public_bytes( encoding=Encoding.PEM, format=PublicFormat.SubjectPublicKeyInfo) save_to_file(pub_key_pem.decode("utf-8"), "mh_public.pub") code = get_code(pub_key) address = get_addr_from_pubkey(code) save_to_file(address, "mh_address.txt") print("Your Metahash address is %s" % address)
def get_shared_secret(self): be = default_backend() sk = ec.generate_private_key(ec.SECP256R1(), be) pn = sk.public_key().public_numbers() key_agreement = { 1: 2, 3: -25, # Per the spec, "although this is NOT the algorithm actually used" -1: 1, -2: int2bytes(pn.x, 32), -3: int2bytes(pn.y, 32), } resp = self.ctap.client_pin(PinProtocolV1.VERSION, PinProtocolV1.CMD.GET_KEY_AGREEMENT) pk = resp[PinProtocolV1.RESULT.KEY_AGREEMENT] x = bytes2int(pk[-2]) y = bytes2int(pk[-3]) pk = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()).public_key(be) shared_secret = sha256(sk.exchange(ec.ECDH(), pk)) # x-coordinate, 32b return key_agreement, shared_secret
def test_public_bytes_openssh(self, backend): _skip_curve_unsupported(backend, ec.SECP192R1()) _skip_curve_unsupported(backend, ec.SECP256R1()) key_bytes = load_vectors_from_file(os.path.join( "asymmetric", "PEM_Serialization", "ec_public_key.pem"), lambda pemfile: pemfile.read(), mode="rb") key = serialization.load_pem_public_key(key_bytes, backend) ssh_bytes = key.public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH) assert ssh_bytes == ( b"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy" b"NTYAAABBBCS8827s9rUZyxZTi/um01+oIlWrwLHOjQxRU9CDAndom00zVAw5BRrI" b"KtHB+SWD4P+sVJTARSq1mHt8kOIWrPc=") key = ec.generate_private_key(ec.SECP192R1(), backend).public_key() with pytest.raises(ValueError): key.public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH)
def perform_create(self, serializer): zone_error = views.valid_zone(serializer.validated_data['zone_root']) if zone_error: raise InvalidZone(detail=zone_error) status, extra = views.log_usage(self.request.user, extra=1, off_session=True) if status == "error": raise BillingError() priv_key = ec.generate_private_key(curve=ec.SECP256R1, backend=default_backend()) priv_key_bytes = priv_key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption() ).decode() serializer.save( user=self.request.user, last_modified=timezone.now(), zsk_private=priv_key_bytes )
def load_or_create_key(filename): # Create or load a root CA key pair priv_key = None if os.path.isfile(filename): # Load existing key with open(filename, 'rb') as f: priv_key = serialization.load_pem_private_key( data=f.read(), password=None, backend=crypto_be) if priv_key == None: # No private key loaded, generate new one priv_key = ec.generate_private_key(ec.SECP256R1(), crypto_be) # Save private key to file with open(filename, 'wb') as f: pem_key = priv_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) f.write(pem_key) return priv_key
def generateECKeyPair(password): priv_key = ec.generate_private_key(ec.SECP384R1(), default_backend()) pub_key = priv_key.public_key() priv_pem = priv_key.private_bytes(encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption(password)) pub_pem = pub_key.public_bytes(encoding=serialization.Encoding.PEM,format=serialization.PublicFormat.SubjectPublicKeyInfo) fname_pub = "public_key_dhm.pem" fname_priv = "private_key_dhm.pem" try: with open(fname_pub,"w") as pub_file: pub_file.write(pub_pem.decode()) with open(fname_priv,"w") as priv_file: priv_file.write(priv_pem.decode()) except Exception as exc: print("Error occurred while writing key on file") print(exc) return -1 return 1
def generate_self_signed_certificate(common_name, curve, host, private_key=None, days_valid=365): if not private_key: private_key = ec.generate_private_key(curve, default_backend()) public_key = private_key.public_key() now = datetime.datetime.utcnow() subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COMMON_NAME, common_name), ]) cert = x509.CertificateBuilder().subject_name(subject) cert = cert.issuer_name(issuer) cert = cert.public_key(public_key) cert = cert.serial_number(x509.random_serial_number()) cert = cert.not_valid_before(now) cert = cert.not_valid_after(now + datetime.timedelta(days=days_valid)) # TODO: What are we going to do about domain name here? 179 cert = cert.add_extension(x509.SubjectAlternativeName([x509.DNSName(host)]), critical=False) cert = cert.sign(private_key, hashes.SHA512(), default_backend()) return cert, private_key
def test_pkcs12_format(self): """ PKCS12 형식으로 인증서/개인키 저장을 위한 코드 """ logging.debug("----- PKCS12 Test Start -----") # ECC 키 쌍 생성 pri_key = ec.generate_private_key(ec.SECP256K1(), default_backend()) pub_key = pri_key.public_key() logging.debug("Key_Type : %s", type(pri_key)) # 인증서 생성 cert = self._generate_cert(pub_key=pub_key, issuer_key=pri_key, subject_name="test") cert_pem = cert.public_bytes(encoding=serialization.Encoding.DER) key_pem = pri_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption()) # 인증서/개인키를 OpenSSL Key로 변환 crypto = OpenSSL.crypto cert_ssl_key = crypto.load_certificate(type=crypto.FILETYPE_ASN1, buffer=cert_pem) priv_ssl_key = crypto.load_privatekey(type=crypto.FILETYPE_ASN1, buffer=key_pem, passphrase=None) logging.debug("Key_Type : %s", type(priv_ssl_key)) # 변환한 인증서개인키를 PKCS12형식으로 변환 p12 = OpenSSL.crypto.PKCS12() p12.set_privatekey(priv_ssl_key) p12.set_certificate(cert_ssl_key) pfx = p12.export() pfx_b64 = base64.b64encode(pfx, altchars=None) logging.debug("%s", pfx_b64)
def ecdh_handshake(): """ Function that manages the handshake performed with the ECDH algorithm. Returns the derived key (shared secret) """ print("\nHandshake started...") client_private_key = ec.generate_private_key(ec.SECP384R1, default_backend()) client_public_key = client_private_key.public_key() encoded_client_public_key = client_public_key.public_bytes( Encoding.X962, PublicFormat.CompressedPoint) print("Public key received from server") server_public_key, _ = sock.recvfrom(BUFFER_SIZE) #print(server_public_key) print("Public key sent to server") sock.sendto(encoded_client_public_key, (UDP_IP, UDP_PORT)) time.sleep(1) print("Calculating shared key...") shared_key = client_private_key.exchange( ec.ECDH(), ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP384R1(), server_public_key)) #print(shared_key) print("Generating derived key...") derived_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake data', ).derive(shared_key) print("Handshake is finished!") #print(derived_key) return derived_key
def __get_trans(self) -> List[Transaction]: # self.chainbase_address with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s: s.connect(self.chainbase_address) s.sendall(send_handler(MsgType.TYPE_TRANS_READ, b'')) *_, msgtype, content = recv_parser(s) trans = [] if msgtype == MsgType.TYPE_RESPONSE_OK: trans += batch_parser(content) private_key = ec.generate_private_key(ec.SECP256K1, default_backend()) public_key = private_key.public_key() public_key = public_key.public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo) sha = hashlib.sha256() sha.update(public_key) public_key_hash = sha.digest() ipt = TransInput([(TXID(public_key_hash), OUTPUT_INDEX(0))], public_key_hash) fd_ = open('ad1.txt', 'r') for index, line in enumerate(fd_.readlines()): if index == 0: line = line.rstrip() pr, pu = line.split('ENDDING') temp = bytes(pu[2:-1], encoding='utf-8') temp = temp.replace(b'\r\n', b'\n') public_key = temp.replace(b'\\n', b'\n') sha = hashlib.sha256() sha.update(public_key) public_key_hash = sha.digest() break fd_.close() opt = TransOutput([(ASSET(20), public_key_hash)]) tran = Transaction(ipt, opt, 0) tran.ready(private_key) trans.append(tran.b) # result = self.get_miner_credit(public_key_hash, 5) # print(result) print('len = ', len(trans)) return [Transaction.unpack(t) for t in trans]
def _generate_self_signed_cert(key_type): """Generates a self signed certificate""" if key_type == 'rsa': key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend() ) elif key_type == 'ecdsa': key = ec.generate_private_key( ec.SECP256R1(), default_backend() ) else: raise Exception('what') subject = issuer = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, u"NO"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, u"State or Province Name"), x509.NameAttribute(NameOID.LOCALITY_NAME, u"Locality name"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Organization Name"), x509.NameAttribute(NameOID.COMMON_NAME, u"commonName"), ]) cert = x509.CertificateBuilder().subject_name( subject ).issuer_name( issuer ).public_key( key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=10) ).add_extension( x509.SubjectAlternativeName([x509.DNSName(u"testulf")]), critical=False, ).sign(key, hashes.SHA256(), default_backend()) return cert, key
def test_biased_k(self): # n is the order of the p256r1 curve. n = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551 key = ec.generate_private_key(ec.SECP256R1(), backend=default_backend()) d = key.private_numbers().private_value asymkey = AsymmetricKey.put(self.session, 0, 'Test ECDSA K', 0xffff, CAPABILITY.SIGN_ECDSA, key) data = b'Hello World!' digest = hashes.Hash(hashes.SHA256(), backend=default_backend()) digest.update(data) h = int_from_bytes(digest.finalize(), 'big') # The assumption here is that for 1024 runs we should get a distribution # where each single bit is set between 400 and 1024 - 400 times. count = 1024 mincount = 400 bits = [0] * 256 for i in range(0, count): resp = asymkey.sign_ecdsa(data, hash=hashes.SHA256()) # Extract random number k from signature: # k = s^(-1) * (h + d*r) mod n (r, s) = crypto_utils.decode_dss_signature(resp) # Fermat's little theorem: a^(p-1) ≡ 1 (mod p), when p is prime. # s * s^(p-2) ≡ 1 (mod p) s_inv = pow(s, n - 2, n) k = s_inv * (h + d * r) % n for j in range(0, 256): if (k >> j) & 1: bits[j] += 1 for bit in bits: self.assertGreater(bit, mincount) self.assertLess(bit, count - mincount) asymkey.delete()
def make_key(bits=1024, key_type="rsa", elliptic_curve=None): """Generate PEM encoded RSA|EC key. :param int bits: Number of bits if key_type=rsa. At least 1024 for RSA. :param str ec_curve: The elliptic curve to use. :returns: new RSA or ECDSA key in PEM form with specified number of bits or of type ec_curve when key_type ecdsa is used. :rtype: str """ if key_type == 'rsa': if bits < 1024: raise errors.Error("Unsupported RSA key length: {}".format(bits)) key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, bits) elif key_type == 'ecdsa': try: name = elliptic_curve.upper() if name in ('SECP256R1', 'SECP384R1', 'SECP521R1'): _key = ec.generate_private_key( curve=getattr(ec, elliptic_curve.upper(), None)(), backend=default_backend() ) else: raise errors.Error("Unsupported elliptic curve: {}".format(elliptic_curve)) except TypeError: raise errors.Error("Unsupported elliptic curve: {}".format(elliptic_curve)) except UnsupportedAlgorithm as e: raise six.raise_from(e, errors.Error(str(e))) _key_pem = _key.private_bytes( encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption() ) key = crypto.load_privatekey(crypto.FILETYPE_PEM, _key_pem) else: raise errors.Error("Invalid key_type specified: {}. Use [rsa|ecdsa]".format(key_type)) return crypto.dump_privatekey(crypto.FILETYPE_PEM, key)
def generate_csr(domains, key_path, csr_path, key_type=RSA_KEY_TYPE): """ Generate a private key, and a CSR for the given domains using this key. :param domains: the domain names to include in the CSR :type domains: `list` of `str` :param str key_path: path to the private key that will be generated :param str csr_path: path to the CSR that will be generated :param str key_type: type of the key (misc.RSA_KEY_TYPE or misc.ECDSA_KEY_TYPE) """ if key_type == RSA_KEY_TYPE: key = crypto.PKey() key.generate_key(crypto.TYPE_RSA, 2048) elif key_type == ECDSA_KEY_TYPE: with warnings.catch_warnings(): # Ignore a warning on some old versions of cryptography warnings.simplefilter('ignore', category=PendingDeprecationWarning) key = ec.generate_private_key(ec.SECP384R1(), default_backend()) key = key.private_bytes(encoding=Encoding.PEM, format=PrivateFormat.TraditionalOpenSSL, encryption_algorithm=NoEncryption()) key = crypto.load_privatekey(crypto.FILETYPE_PEM, key) else: raise ValueError('Invalid key type: {0}'.format(key_type)) with open(key_path, 'wb') as file_h: file_h.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, key)) req = crypto.X509Req() san = ', '.join('DNS:{0}'.format(item) for item in domains) san_constraint = crypto.X509Extension(b'subjectAltName', False, san.encode('utf-8')) req.add_extensions([san_constraint]) req.set_pubkey(key) req.set_version(2) req.sign(key, 'sha256') with open(csr_path, 'wb') as file_h: file_h.write(crypto.dump_certificate_request(crypto.FILETYPE_ASN1, req))
def key_exchange_listener(key_message): global private_key global derived_key key_message = str(key_message.data) key_message = key_message.split("SPACE") mode = key_message[0] peer_public_key = key_message[1] loaded_public_key = serialization.load_pem_public_key(peer_public_key, backend=default_backend()) private_key = ec.generate_private_key(ec.SECP384R1(), default_backend()) #Creates new private key shared_key = private_key.exchange(ec.ECDH(), loaded_public_key) #Generates a shared key using the local if mode == "32": derived_key = HKDF( #Derives key to be used for decryption from shared key algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend()).derive(shared_key) else: derived_key = HKDF( #Derives key to be used for decryption from shared key algorithm=hashes.SHA256(), length=16, salt=None, info=None, backend=default_backend()).derive(shared_key) public_key = private_key.public_key() #Creates public key from previously created private key serialized_public = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo) pub2.publish(serialized_public) performance = process.cpu_percent() cpu_percent_de.append(performance)
def prepare(self): # Generate a private key for use in the exchange. private_key = ec.generate_private_key(ec.SECP384R1(), self.backend) public_key = private_key.public_key() public_key_bytes = public_key.public_bytes( Encoding.DER, PublicFormat.SubjectPublicKeyInfo) msg = 'pk:{}'.format(binascii.hexlify(public_key_bytes).decode('utf8')) self.send_msg(msg) print('wait for peer_public_key...') while True: received_text = self.receive_msg() received_msgs = re.findall(self.msg_re, received_text) filted_msgs = [] for received_msg in received_msgs: if received_msg[0] != self.sender_name and received_msg[ 2].startswith('pk:'): filted_msgs.append(received_msg) if filted_msgs: content = filted_msgs[-1][2] if is_hex_str(content[3:]): peer_public_key_bytes = bytes.fromhex(content[3:]) peer_public_key = load_der_public_key( peer_public_key_bytes, self.backend) break else: print('[!] incorrect hex_str') time.sleep(5) shared_key = private_key.exchange(ec.ECDH(), peer_public_key) # Perform key derivation. derived_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake data', backend=self.backend).derive(shared_key) secret_key = base64.urlsafe_b64encode(derived_key) self.fernet = Fernet(secret_key)
def test_signer_protected_headers(): payload = "Please take a moment to register today" eck = ec.generate_private_key(ec.SECP256R1(), default_backend()) _key = ECKey().load_key(eck) keys = [_key] _jws = JWS(payload, alg="ES256") protected = dict(header1=u"header1 is protected", header2="header2 is protected too", a=1) _jwt = _jws.sign_compact(keys, protected=protected) exp_protected = protected.copy() exp_protected['alg'] = 'ES256' enc_header, enc_payload, sig = _jwt.split('.') assert json.loads(b64d( enc_header.encode("utf-8")).decode("utf-8")) == exp_protected assert b64d(enc_payload.encode("utf-8")).decode("utf-8") == payload _pub_key = ECKey().load_key(eck.public_key()) _rj = JWS(alg='ES256') info = _rj.verify_compact(_jwt, [_pub_key]) assert info == payload
def __handle_sender_pub(self, rqst, s): sender_dh_pub_key_bytes = base64.b64decode(rqst.public_key) sender_dh_pub_key = utils.deserialize_public_key( sender_dh_pub_key_bytes) # generate our own DH key rcver_dh_private_key = ec.generate_private_key(ec.SECP384R1(), default_backend()) # compute shared key shared_key = utils.generate_dh_key(rcver_dh_private_key, sender_dh_pub_key) # cached sender_dh_pub_key_bytes # since we will have to verify signature of public key in the future protocol msg self.conn_info[s] = { 'shared_dh': shared_key, 'expect': ClientToClient.SENDER_IDENTITY, 'rcver_dh_private': rcver_dh_private_key, 'sender_dh_pub_bytes': sender_dh_pub_key_bytes } # send DH public key back self.__send_dh_pub(rcver_dh_private_key, ClientToClient.RECVER_PUB, s) logger.debug('__handle_sender_pub: Send dh pub as receiver ' + self.name)
def create_pair(self, algorithm): if algorithm == ALGORITHM.RSA_2048: private_key = rsa.generate_private_key(0x10001, 2048, default_backend()) elif algorithm == ALGORITHM.RSA_3072: private_key = rsa.generate_private_key(0x10001, 3072, default_backend()) elif algorithm == ALGORITHM.RSA_4096: private_key = rsa.generate_private_key(0x10001, 4096, default_backend()) else: ec_curve = ALGORITHM.to_curve(algorithm) private_key = ec.generate_private_key(ec_curve, default_backend()) builder = x509.CertificateBuilder() name = x509.Name( [x509.NameAttribute(NameOID.COMMON_NAME, u"Test Attestation Certificate")] ) builder = builder.subject_name(name) builder = builder.issuer_name(name) one_day = datetime.timedelta(1, 0, 0) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after(datetime.datetime.today() + one_day) builder = builder.serial_number(int(uuid.uuid4())) builder = builder.public_key(private_key.public_key()) certificate = builder.sign(private_key, hashes.SHA256(), default_backend()) attkey = AsymmetricKey.put( self.session, 0, "Test Create Pair", 0xFFFF, CAPABILITY.SIGN_ATTESTATION_CERTIFICATE, private_key, ) certobj = attkey.put_certificate( "Test Create Pair", 0xFFFF, CAPABILITY.NONE, certificate ) self.assertEqual(certificate.public_bytes(Encoding.DER), certobj.get()) return attkey, certobj, certificate
def test_rsa_cert_new_ecdsa_key(self): """Generates a PKCS#7 renewal request from an rsa certificate with a new ecdsa key""" cert, key = _generate_self_signed_cert('rsa') new_key = ec.generate_private_key( ec.SECP256R1(), default_backend() ) csr = pkcs7csr.create_pkcs7csr(cert, key, new_key) verify_result, raw_inner_csr = _verify_pkcs7_signature(csr) inner_csr = x509.load_der_x509_csr(raw_inner_csr, default_backend()) decoded_inner_csr = decoder.decode(raw_inner_csr, asn1Spec=rfc2314.CertificationRequest()) encoded_inner_csr = encoder.encode(decoded_inner_csr[0]['certificationRequestInfo'] ['attributes'][0]['vals'][0]) self.assertEqual(verify_result, 0) self.assertEqual(inner_csr.is_signature_valid, True) self.assertEqual( new_key.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo), inner_csr.public_key().public_bytes(Encoding.DER, PublicFormat.SubjectPublicKeyInfo)) self.assertEqual(cert.public_bytes(Encoding.DER), encoded_inner_csr)
def client(message, encryption): client_private_key = ec.generate_private_key(ec.SECP384R1(), default_backend()) client_public_key = client_private_key.public_key() connected_socket = connect_to_server() if encryption is True: server_public_key = client_exchange_keys(connected_socket, client_public_key) if server_public_key: shared_key = client_private_key.exchange(ec.ECDH(), server_public_key) derived_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b'handshake data', backend=default_backend() ).derive(shared_key) f = Fernet(base64.urlsafe_b64encode(derived_key)) if message == "": message = b"arrays start at 0. anyone who disagrees is a heretic." encrypted_data = f.encrypt(message) connected_socket.sendall(encrypted_data) else: connected_socket.sendall(message)
def generate_ec_key(path: Path, key_size=256) -> ec.EllipticCurvePrivateKey: """Generates an EC private key and saves it to the given path as PEM. :param path: The path to write the PEM-serialized key to. :param key_size: The EC key size. :return: The generated private key. """ curve = getattr(ec, f"SECP{key_size}R1") private_key = ec.generate_private_key(curve()) pem = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) path.touch(KEY_FILE_MODE) if not path.exists() else path.chmod(KEY_FILE_MODE) with open(path, "wb") as pem_out: pem_out.write(pem) return private_key
def salsaEncypt(message, serial_peer_public_key): private_key = ec.generate_private_key(ec.SECP384R1(), default_backend()) #Generates private key public_key = private_key.public_key() #Generates public key from private key serial_public_key = public_key.public_bytes(encoding=serialization.Encoding.PEM,format=serialization.PublicFormat.SubjectPublicKeyInfo) #Serializes public key so it can be sent as a ROS message peer_public_key = serialization.load_pem_public_key(serial_peer_public_key, backend=default_backend()) #Deserializes the public key from the peer so it can be used to derive shared key shared_key = private_key.exchange(ec.ECDH(), peer_public_key) #Shared key generated from local private key and the peer's public key derived_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=None, backend=default_backend()).derive(shared_key) #Key to be used to encrypt the data is dericed using HKDF cipher = Salsa20.new(key=derived_key) #A new Salsa20 cipher object is created using the derived key msg = cipher.nonce + cipher.encrypt(message) #The ROS message is encrypted and the cipher's nonce is added to the beginning of the message return serial_public_key +"SPACE"+ msg #Return public key and encrypted message seperated with 'SPACE'
def post_build(self, pkt, pay): s = self.tls_session if self.ecdh_Yc == "": 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)) # else, we assume that the user wrote the client_kx_privkey by himself if self.ecdh_Yclen is None: self.ecdh_Yclen = len(self.ecdh_Yc) 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() return pkcs_i2osp(self.ecdh_Yclen, 1) + self.ecdh_Yc + pay
def _gen_key(self): if self.key_type is None: self.key_type = KeyType(KeyType.RSA, 2048) if self.key_type.key_type == KeyType.RSA: self.private_key = rsa.generate_private_key( public_exponent=65537, key_size=self.key_type.option, backend=default_backend()) elif self.key_type.key_type == KeyType.ECDSA: if self.key_type.option == 'p521': curve = ec.SECP521R1() elif self.key_type.option == 'p384': curve = ec.SECP384R1() elif self.key_type.option == 'p256': curve = ec.SECP256R1() else: curve = ec.SECP256R1() self.private_key = ec.generate_private_key(curve, default_backend()) else: raise ClientBadData self._public_key_from_private()
def setUp(self): """Set up a CertificateSigningRequest.""" proto = load_csr(TestSubject.config) proto.output_path = NamedTemporaryFile().name proto.key_info.key_type = KeyType.RSA self.rsa_csr = CertificateSigningRequestBuilder.from_proto(proto) self.rsa_private_key = rsa.generate_private_key( public_exponent=65537, key_size=2048 ) proto.key_info.key_type = KeyType.DSA self.dsa_csr = CertificateSigningRequestBuilder.from_proto(proto) self.dsa_private_key = dsa.generate_private_key( key_size=2048, ) proto.key_info.key_type = KeyType.EC self.ec_csr = CertificateSigningRequestBuilder.from_proto(proto) self.ec_private_key = ec.generate_private_key( ec.SECP256R1(), )
def load_key_file(self): self.private_key = ec.generate_private_key( ec.SECP384R1(), default_backend()) self.public_key = self.private_key.public_key() self.public_key_bytes = self.public_key.public_bytes( Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) self.signing_key = rsa.generate_private_key( public_exponent=65537, key_size=2048, backend=default_backend()) self.verification_key = self.signing_key.public_key() with open("./final_keyfile/team2_key.pem", "rb") as f: self.team2_signing_key = load_pem_private_key(f.read(), password=None, backend=default_backend()) self.team2_verification_key = self.signing_key.public_key() self.team2_verification_key_bytes = self.team2_verification_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo) with open("./final_keyfile/20194_root_cert.pem", "rb") as f: self.root_cert = x509.load_pem_x509_certificate(f.read(), default_backend()) self.root_pubk = self.root_cert.public_key() with open("./final_keyfile/team2_cert.pem", "rb") as f: self.team2_certification_bytes = f.read() self.team2_cert = x509.load_pem_x509_certificate(self.team2_certification_bytes, default_backend()) one_day = datetime.timedelta(1, 0, 0) builder = x509.CertificateBuilder() builder = builder.public_key(self.verification_key) builder = builder.subject_name( x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, u'20194.2.56.78'), ])) builder = builder.issuer_name(self.team2_cert.subject) builder = builder.serial_number(x509.random_serial_number()) builder = builder.not_valid_before(datetime.datetime.today() - one_day) builder = builder.not_valid_after( datetime.datetime.today() + (one_day * 30)) self.cert = builder.sign(private_key=self.team2_signing_key, algorithm=hashes.SHA256(), backend=default_backend()) self.certification_bytes = self.cert.public_bytes(Encoding.PEM) self.signature = self.signing_key.sign(self.public_key_bytes, padding.PSS( mgf=padding.MGF1(hashes.SHA256()), salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
def test_csr(self): key = ec.generate_private_key(ec.SECP384R1(), default_backend()) csr = cu.create_csr( key, 'i am dummy test', 'US', 'CA', 'MPK', 'FB', 'magma', '*****@*****.**', ) self.assertTrue(csr.is_signature_valid) public_key_bytes = key.public_key().public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH, ) csr_public_key_bytes = csr.public_key().public_bytes( serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH, ) self.assertEqual(public_key_bytes, csr_public_key_bytes)
def generate_der_keys(password=None): password = examine_password(password) private_key = ec.generate_private_key( ec.SECP256K1(), default_backend() ) serialized_private = private_key.private_bytes( encoding=serialization.Encoding.DER, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.BestAvailableEncryption(password) ) pri_key_string = Encoder.bytes_to_base64_str(serialized_private) logger.debug("pri_key_string:%s" % pri_key_string) puk = private_key.public_key() serialized_public = puk.public_bytes( encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo ) pub_key_string = Encoder.bytes_to_base64_str(serialized_public) logger.debug("pub_key_string:%s" % pub_key_string) return pri_key_string, pub_key_string