def test_signatures(self, backend, vector): hash_type = _HASH_TYPES[vector['digest_algorithm']] curve_type = ec._CURVE_TYPES[vector['curve']] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePublicNumbers( vector['x'], vector['y'], curve_type() ).public_key(backend) signature = encode_dss_signature(vector['r'], vector['s']) key.verify( signature, vector['message'], ec.ECDSA(hash_type()) )
def test_load_ssh_public_key_ecdsa_nist_p256(self, backend): _skip_curve_unsupported(backend, ec.SECP256R1()) ssh_key = ( b"ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAy" b"NTYAAABBBGG2MfkHXp0UkxUyllDzWNBAImsvt5t7pFtTXegZK2WbGxml8zMrgWi5" b"teIg1TO03/FD9hbpBFgBeix3NrCFPls= root@cloud-server-01") key = load_ssh_public_key(ssh_key, backend) assert isinstance(key, ec.EllipticCurvePublicKey) expected_x = int( "44196257377740326295529888716212621920056478823906609851236662550" "785814128027", 10) expected_y = int( "12257763433170736656417248739355923610241609728032203358057767672" "925775019611", 10) assert key.public_numbers() == ec.EllipticCurvePublicNumbers( expected_x, expected_y, ec.SECP256R1())
def test_signature_failures(self, backend, vector): hash_type = _HASH_TYPES[vector['digest_algorithm']] curve_type = ec._CURVE_TYPES[vector['curve']] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePublicNumbers(vector['x'], vector['y'], curve_type()).public_key(backend) signature = encode_dss_signature(vector['r'], vector['s']) verifier = key.verifier(signature, ec.ECDSA(hash_type())) verifier.update(vector['message']) if vector["fail"] is True: with pytest.raises(exceptions.InvalidSignature): verifier.verify() else: verifier.verify()
def _init_shared_secret(self): be = default_backend() sk = ec.generate_private_key(ec.SECP256R1(), be) pn = sk.public_key().public_numbers() key_agreement = { 1: 2, -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_fromPrivateBlobECDSA(self): """ A private EC key is correctly generated from a private key blob. """ from cryptography.hazmat.primitives.asymmetric import ec publicNumbers = ec.EllipticCurvePublicNumbers( x=keydata.ECDatanistp256['x'], y=keydata.ECDatanistp256['y'], curve=ec.SECP256R1()) ecblob = ( common.NS(keydata.ECDatanistp256['curve']) + common.NS(keydata.ECDatanistp256['curve'][-8:]) + common.NS(publicNumbers.encode_point()) + common.MP(keydata.ECDatanistp256['privateValue']) ) eckey = keys.Key._fromString_PRIVATE_BLOB(ecblob) self.assertFalse(eckey.isPublic()) self.assertEqual(keydata.ECDatanistp256, eckey.data())
def encapsulate(self, peer_cose_key): 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), } x = bytes2int(peer_cose_key[-2]) y = bytes2int(peer_cose_key[-3]) pk = ec.EllipticCurvePublicNumbers(x, y, ec.SECP256R1()).public_key(be) shared_secret = self.kdf(sk.exchange(ec.ECDH(), pk)) # x-coordinate, 32b return key_agreement, shared_secret
def __init__(self, msg=None, data=None, filename=None, password=None, vals=None, file_obj=None, validate_point=True): self.verifying_key = None self.signing_key = None if file_obj is not None: self._from_private_key(file_obj, password) return if filename is not None: self._from_private_key_file(filename, password) return if (msg is None) and (data is not None): msg = Message(data) if vals is not None: self.signing_key, self.verifying_key = vals else: if msg is None: raise SSHException('Key object may not be empty') if msg.get_text() != 'ecdsa-sha2-nistp256': raise SSHException('Invalid key') curvename = msg.get_text() if curvename != 'nistp256': raise SSHException("Can't handle curve of type %s" % curvename) pointinfo = msg.get_binary() if pointinfo[0:1] != four_byte: raise SSHException('Point compression is being used: %s' % binascii.hexlify(pointinfo)) curve = ec.SECP256R1() numbers = ec.EllipticCurvePublicNumbers( x=inflate_long(pointinfo[1:1 + curve.key_size // 8], always_positive=True), y=inflate_long(pointinfo[1 + curve.key_size // 8:], always_positive=True), curve=curve) self.verifying_key = numbers.public_key(backend=default_backend()) self.size = 256
def recover_public_key(digest, signature, i, message=None): """ Recover the public key from the the signature """ # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily curve = ecdsa.SECP256k1.curve G = ecdsa.SECP256k1.generator order = ecdsa.SECP256k1.order yp = i % 2 r, s = ecdsa.util.sigdecode_string(signature, order) # 1.1 x = r + (i // 2) * order # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified. # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve. alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p() beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p()) y = beta if (beta - yp) % 2 == 0 else curve.p() - beta # 1.4 Constructor of Point is supposed to check if nR is at infinity. R = ecdsa.ellipticcurve.Point(curve, x, y, order) # 1.5 Compute e e = ecdsa.util.string_to_number(digest) # 1.6 Compute Q = r^-1(sR - eG) Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G) if SECP256K1_MODULE == "cryptography" and message is not None: if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover sigder = encode_dss_signature(r, s) public_key = ec.EllipticCurvePublicNumbers(Q._Point__x, Q._Point__y, ec.SECP256K1()).public_key( default_backend()) public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256())) return public_key else: # Not strictly necessary, but let's verify the message for paranoia's sake. if not ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1).verify_digest( signature, digest, sigdecode=ecdsa.util.sigdecode_string): # pragma: no cover return None # pragma: no cover return ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1) # pragma: no cover
def _verify_signature_with_pubkey(self, signed_info_c14n, raw_signature, key_value, signature_alg): if "ecdsa-" in signature_alg: ec_key_value = self._find(key_value, "ECKeyValue", namespace="dsig11") named_curve = self._find(ec_key_value, "NamedCurve", namespace="dsig11") public_key = self._find(ec_key_value, "PublicKey", namespace="dsig11") key_data = b64decode(public_key.text)[1:] x = bytes_to_long(key_data[:len(key_data)//2]) y = bytes_to_long(key_data[len(key_data)//2:]) curve_class = self.known_ecdsa_curves[named_curve.get("URI")] key = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()).public_key(backend=default_backend()) dss_signature = self._encode_dss_signature(raw_signature, key.key_size) key.verify( dss_signature, data=signed_info_c14n, signature_algorithm=ec.ECDSA( self._get_signature_digest_method(signature_alg) ), ) elif "dsa-" in signature_alg: dsa_key_value = self._find(key_value, "DSAKeyValue") p = self._get_long(dsa_key_value, "P") q = self._get_long(dsa_key_value, "Q") g = self._get_long(dsa_key_value, "G", require=False) y = self._get_long(dsa_key_value, "Y") pn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g)) key = pn.public_key(backend=default_backend()) # TODO: supply meaningful key_size_bits for signature length assertion dss_signature = self._encode_dss_signature(raw_signature, len(raw_signature) * 8 / 2) key.verify(dss_signature, data=signed_info_c14n, algorithm=self._get_signature_digest_method(signature_alg)) elif "rsa-" in signature_alg: rsa_key_value = self._find(key_value, "RSAKeyValue") modulus = self._get_long(rsa_key_value, "Modulus") exponent = self._get_long(rsa_key_value, "Exponent") key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key(backend=default_backend()) key.verify(raw_signature, data=signed_info_c14n, padding=PKCS1v15(), algorithm=self._get_signature_digest_method(signature_alg)) else: raise NotImplementedError()
def get_pubkey(self): """Get the public key of an asymmetric key""" msg = struct.pack('!H', self.id) ret = self.session.send_secure_cmd(COMMAND.GET_PUBKEY, msg) algo = six.indexbytes(ret, 0) raw_key = ret[1:] if algo in [ALGO.RSA_2048, ALGO.RSA_3072, ALGO.RSA_4096]: num = int_from_bytes(raw_key, 'big') pubkey = rsa.RSAPublicNumbers(e=0x10001, n=num) elif algo in [ALGO.EC_P224, ALGO.EC_P256, ALGO.EC_P384, ALGO.EC_P521, ALGO.EC_K256, ALGO.EC_BP256, ALGO.EC_BP384, ALGO.EC_BP512]: clen = len(raw_key) // 2 x = int_from_bytes(raw_key[:clen], 'big') y = int_from_bytes(raw_key[clen:], 'big') curve = ALGO.to_curve(algo) pubkey = ec.EllipticCurvePublicNumbers(curve=curve(), x=x, y=y) elif algo in [ALGO.EC_ED25519]: return Ed25519PublicKey(raw_key) return pubkey.public_key(backend=default_backend())
def from_point(cls, x, y, network=network.default, compressed=True, backend=default_backend()): """Create a public key from its point coordinates. A public key is a point on an elliptic curve, i.e. a pair (x, y) that satisfies the curve equation. """ public_numbers = ec.EllipticCurvePublicNumbers(x, y, network.curve) try: key = public_numbers.public_key(backend) except ValueError: raise InvalidPoint() return cls(key, network, compressed)
def _ecdh(cls, curve: 'CoseCurve', private_key: 'EC2', public_key: 'EC2') -> bytes: if curve == curves.P256(): curve_instance = SECP256R1() elif curve == curves.P384(): curve_instance = SECP384R1() elif curve == curves.P521(): curve_instance = SECP521R1() else: raise CoseIllegalCurve() d_value = int(hexlify(private_key.d), 16) x_value = int(hexlify(public_key.x), 16) y_value = int(hexlify(public_key.y), 16) d = ec.derive_private_key(d_value, curve_instance, default_backend()) p = ec.EllipticCurvePublicNumbers(x_value, y_value, curve_instance) p = p.public_key(default_backend()) shared_key = d.exchange(ECDH(), p) return shared_key
def test_with_numbers(self, backend, vector, hash_type): curve_type = ec._CURVE_TYPES[vector['curve']] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePrivateNumbers( vector['d'], ec.EllipticCurvePublicNumbers( vector['x'], vector['y'], curve_type() ) ).private_key(backend) assert key priv_num = key.private_numbers() assert priv_num.private_value == vector['d'] assert priv_num.public_numbers.x == vector['x'] assert priv_num.public_numbers.y == vector['y'] assert curve_type().name == priv_num.public_numbers.curve.name
def test_signing_with_example_keys(self, backend, vector, hash_type): curve_type = ec._CURVE_TYPES[vector['curve']] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePrivateNumbers( vector['d'], ec.EllipticCurvePublicNumbers(vector['x'], vector['y'], curve_type())).private_key(backend) assert key pkey = key.public_key() assert pkey signer = key.signer(ec.ECDSA(hash_type())) signer.update(b"YELLOW SUBMARINE") signature = signer.finalize() verifier = pkey.verifier(signature, ec.ECDSA(hash_type())) verifier.update(b"YELLOW SUBMARINE") verifier.verify()
def test_load_ssh_public_key_ecdsa_nist_p521(self, backend): _skip_curve_unsupported(backend, ec.SECP521R1()) ssh_key = ( b"ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1" b"MjEAAACFBAGTrRhMSEgF6Ni+PXNz+5fjS4lw3ypUILVVQ0Av+0hQxOx+MyozELon" b"I8NKbrbBjijEs1GuImsmkTmWsMXS1j2A7wB4Kseh7W9KA9IZJ1+TMrzWUEwvOOXi" b"wT23pbaWWXG4NaM7vssWfZBnvz3S174TCXnJ+DSccvWBFnKP0KchzLKxbg== " b"root@cloud-server-01") key = load_ssh_public_key(ssh_key, backend) expected_x = int( "54124123120178189598842622575230904027376313369742467279346415219" "77809037378785192537810367028427387173980786968395921877911964629" "142163122798974160187785455", 10) expected_y = int( "16111775122845033200938694062381820957441843014849125660011303579" "15284560361402515564433711416776946492019498546572162801954089916" "006665939539407104638103918", 10) assert key.public_numbers() == ec.EllipticCurvePublicNumbers( expected_x, expected_y, ec.SECP521R1())
def pubobjToKey(self, pubkey, session): t = session.getAttributeValue(pubkey, [PyKCS11.CKA_KEY_TYPE])[0] if t == PyKCS11.CKK_RSA: (modulus, pubexp) = session.getAttributeValue( pubkey, [PyKCS11.CKA_MODULUS, PyKCS11.CKA_PUBLIC_EXPONENT] ) n = bytes(modulus) e = bytes(pubexp) key = rsa.RSAPublicNumbers( e=int(b2a_hex(e), 16), n=int(b2a_hex(n), 16) ) elif t == PyKCS11.CKK_EC: (param, point) = session.getAttributeValue( pubkey, [PyKCS11.CKA_EC_PARAMS, PyKCS11.CKA_EC_POINT] ) param = bytes(param) point = point[1:] if point[0] == 0x81: point = point[1:] self.assertEqual(point[0] + 1, len(point)) point = bytes(point[1:]) # length byte if param == P256_PARAMS: curve = ec.SECP256R1() clen = 32 elif param == P384_PARAMS: curve = ec.SECP384R1() clen = 48 elif param == P521_PARAMS: curve = ec.SECP521R1() clen = 66 else: print("no curve.. %d - %d" % (len(param), len(P256_PARAMS))) return x = point[1 : 1 + len(point) // 2] y = point[1 + len(point) // 2 :] key = ec.EllipticCurvePublicNumbers( curve=curve, x=int(b2a_hex(x), 16), y=int(b2a_hex(y), 16) ) return key.public_key(backend=default_backend())
def shared_secret(private_key: 'CK', public_key: 'CK') -> bytes: """ Compute the shared secret. """ if public_key.crv == X25519: d = X25519PrivateKey.from_private_bytes(private_key.d) x = X25519PublicKey.from_public_bytes(public_key.x) elif public_key.crv == X448: d = X448PrivateKey.from_private_bytes(private_key.d) x = X448PublicKey.from_public_bytes(public_key.x) elif public_key.crv == P256: d = ec.derive_private_key(int(hexlify(private_key.d), 16), SECP256R1(), default_backend()) x = ec.EllipticCurvePublicNumbers(int(hexlify(public_key.x), 16), int(hexlify(public_key.y), 16), SECP256R1()) else: raise CoseIllegalCurve(f"{public_key.crv} is unsupported") secret = d.exchange(x) return secret
def check_signature(self, message, signature): byte_message = pickle.dumps(message) if message['sender_address'] == "system": return True if not message['sender_address'] == self.generate_address(message['public_key']): print("Sender Address isn't the same as the generate addresss") return False pub = ec.EllipticCurvePublicNumbers( message['public_key'].x, message['public_key'].y, self.CURVE ).public_key(default_backend()) try: pub.verify(signature, byte_message, self.SIGNATURE_ALGORITHM) except cryptography.exceptions.InvalidSignature: return False else: return True
def get_key(url, key_id): print('\nRequesting key with id = ' + key_id) try: rsp = requests.get('%s/keys/%s' % (url, key_id)) except: return Fail.NODE_OFFLINE if rsp.status_code != 200: print(rsp.text) return Fail.KEY_GET key = rsp.json() print('Received:\n' + json.dumps(key, indent=2)) # Construct public key x = int.from_bytes(b64url_decode_without_padding(key['pub_key']['x']), 'big') y = int.from_bytes(b64url_decode_without_padding(key['pub_key']['y']), 'big') return ec.EllipticCurvePublicNumbers(x, y, ec.SECP256K1()).public_key( default_backend())
def test_load_ssh_public_key_ecdsa_nist_p384(self, backend): _skip_curve_unsupported(backend, ec.SECP384R1()) ssh_key = ( b"ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAz" b"ODQAAABhBMzucOm9wbwg4iMr5QL0ya0XNQGXpw4wM5f12E3tWhdcrzyGHyel71t1" b"4bvF9JZ2/WIuSxUr33XDl8jYo+lMQ5N7Vanc7f7i3AR1YydatL3wQfZStQ1I3rBa" b"qQtRSEU8Tg== root@cloud-server-01" ) key = load_ssh_public_key(ssh_key, backend) expected_x = int( "31541830871345183397582554827482786756220448716666815789487537666" "592636882822352575507883817901562613492450642523901", 10 ) expected_y = int( "15111413269431823234030344298767984698884955023183354737123929430" "995703524272335782455051101616329050844273733614670", 10 ) assert key.public_numbers() == ec.EllipticCurvePublicNumbers( expected_x, expected_y, ec.SECP384R1() )
def public_numbers(self): set_func, get_func, group = ( self._backend._ec_key_determine_group_get_set_funcs(self._ec_key) ) point = self._backend._lib.EC_KEY_get0_public_key(self._ec_key) self._backend.openssl_assert(point != self._backend._ffi.NULL) with self._backend._tmp_bn_ctx() as bn_ctx: bn_x = self._backend._lib.BN_CTX_get(bn_ctx) bn_y = self._backend._lib.BN_CTX_get(bn_ctx) res = get_func(group, point, bn_x, bn_y, bn_ctx) self._backend.openssl_assert(res == 1) x = self._backend._bn_to_int(bn_x) y = self._backend._bn_to_int(bn_y) return ec.EllipticCurvePublicNumbers( x=x, y=y, curve=self._curve )
def public_to_key(obj): key = None if obj.type == TPM2_ALG.RSA: b = obj.unique.rsa.buffer n = int.from_bytes(b, byteorder="big") e = obj.parameters.rsaDetail.exponent if e == 0: e = 65537 nums = rsa.RSAPublicNumbers(e, n) key = nums.public_key(backend=default_backend()) elif obj.type == TPM2_ALG.ECC: curve = _get_curve(obj.parameters.eccDetail.curveID) if curve is None: raise ValueError( f"unsupported curve: {obj.parameters.eccDetail.curveID}") x = int.from_bytes(obj.unique.ecc.x, byteorder="big") y = int.from_bytes(obj.unique.ecc.y, byteorder="big") nums = ec.EllipticCurvePublicNumbers(x, y, curve()) key = nums.public_key(backend=default_backend()) else: raise ValueError(f"unsupported key type: {obj.type}") return key
def __init__(self, crv: str, x: str, y: str, d: Optional[str] = None, **ignore) -> None: if crv not in self.CURVES.keys(): raise InvalidKey(f'Unknown curve: "{crv}".') self._private = None self._public = None curve = self.CURVES[crv] x_coord = b64_to_int(x) y_coord = b64_to_int(y) public = ec.EllipticCurvePublicNumbers(x_coord, y_coord, curve) self._public: EC_PUBLIC = public.public_key(default_backend()) if d: private_value = b64_to_int(d) private = ec.EllipticCurvePrivateNumbers(private_value, public) self._private: EC_PRIVATE = private.private_key(default_backend())
def _verify_signature_with_pubkey(self, signed_info_c14n, raw_signature, key_value, signature_alg): if "ecdsa-" in signature_alg: ec_key_value = self._find(key_value, "ECKeyValue", namespace="ds11") named_curve = self._find(ec_key_value, "NamedCurve", namespace="ds11") public_key = self._find(ec_key_value, "PublicKey", namespace="ds11") key_data = b64decode(public_key.text)[1:] x = bytes_to_long(key_data[:len(key_data)//2]) y = bytes_to_long(key_data[len(key_data)//2:]) curve_class = self.known_ecdsa_curves[named_curve.get("URI")] key = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()).public_key(backend=default_backend()) verifier = key.verifier(raw_signature, ec.ECDSA(self._get_signature_digest_method(signature_alg))) elif "dsa-" in signature_alg: dsa_key_value = self._find(key_value, "DSAKeyValue") p = self._get_long(dsa_key_value, "P") q = self._get_long(dsa_key_value, "Q") g = self._get_long(dsa_key_value, "G", require=False) y = self._get_long(dsa_key_value, "Y") pn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g)) key = pn.public_key(backend=default_backend()) def as_der_sequence(r, s): return long_to_bytes(0x30) + long_to_bytes(len(r) + len(s)) + r + s def as_der_integer(i): return long_to_bytes(0x02) + long_to_bytes(len(i)) + i sig_as_der_seq = as_der_sequence(as_der_integer(raw_signature[:len(raw_signature)//2]), as_der_integer(raw_signature[len(raw_signature)//2:])) verifier = key.verifier(sig_as_der_seq, self._get_signature_digest_method(signature_alg)) elif "rsa-" in signature_alg: rsa_key_value = self._find(key_value, "RSAKeyValue") modulus = self._get_long(rsa_key_value, "Modulus") exponent = self._get_long(rsa_key_value, "Exponent") key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key(backend=default_backend()) verifier = key.verifier(raw_signature, padding=PKCS1v15(), algorithm=self._get_signature_digest_method(signature_alg)) else: raise NotImplementedError() verifier.update(signed_info_c14n) verifier.verify()
def _verify_signature_with_pubkey(self, signed_info_c14n, raw_signature, key_value, signature_alg): if "ecdsa-" in signature_alg: ec_key_value = self._find(key_value, "ECKeyValue", namespace="dsig11") named_curve = self._find(ec_key_value, "NamedCurve", namespace="dsig11") public_key = self._find(ec_key_value, "PublicKey", namespace="dsig11") key_data = b64decode(public_key.text)[1:] x = bytes_to_long(key_data[:len(key_data)//2]) y = bytes_to_long(key_data[len(key_data)//2:]) curve_class = self.known_ecdsa_curves[named_curve.get("URI")] key = ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_class()).public_key(backend=default_backend()) key.verify(raw_signature, data=signed_info_c14n, signature_algorithm=ec.ECDSA(self._get_signature_digest_method(signature_alg))) elif "dsa-" in signature_alg: dsa_key_value = self._find(key_value, "DSAKeyValue") p = self._get_long(dsa_key_value, "P") q = self._get_long(dsa_key_value, "Q") g = self._get_long(dsa_key_value, "G", require=False) y = self._get_long(dsa_key_value, "Y") pn = dsa.DSAPublicNumbers(y=y, parameter_numbers=dsa.DSAParameterNumbers(p=p, q=q, g=g)) key = pn.public_key(backend=default_backend()) from asn1crypto.algos import DSASignature sig_as_der_seq = DSASignature.from_p1363(raw_signature).dump() key.verify(sig_as_der_seq, data=signed_info_c14n, algorithm=self._get_signature_digest_method(signature_alg)) elif "rsa-" in signature_alg: rsa_key_value = self._find(key_value, "RSAKeyValue") modulus = self._get_long(rsa_key_value, "Modulus") exponent = self._get_long(rsa_key_value, "Exponent") key = rsa.RSAPublicNumbers(e=exponent, n=modulus).public_key(backend=default_backend()) key.verify(raw_signature, data=signed_info_c14n, padding=PKCS1v15(), algorithm=self._get_signature_digest_method(signature_alg)) else: raise NotImplementedError()
def test_signature_failures(self, backend, subtests): vectors = load_vectors_from_file( os.path.join("asymmetric", "ECDSA", "FIPS_186-3", "SigVer.rsp"), load_fips_ecdsa_signing_vectors, ) for vector in vectors: with subtests.test(): hash_type = _HASH_TYPES[vector["digest_algorithm"]] curve_type = ec._CURVE_TYPES[vector["curve"]] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePublicNumbers( vector["x"], vector["y"], curve_type()).public_key(backend) signature = encode_dss_signature(vector["r"], vector["s"]) if vector["fail"] is True: with pytest.raises(exceptions.InvalidSignature): key.verify(signature, vector["message"], ec.ECDSA(hash_type())) else: key.verify(signature, vector["message"], ec.ECDSA(hash_type()))
def _process_jwk(self, jwk_dict): if not jwk_dict.get('kty') == 'EC': raise JWKError("Incorrect key type. Expected: 'EC', Received: %s" % jwk_dict.get('kty')) if not all(k in jwk_dict for k in ['x', 'y', 'crv']): raise JWKError('Mandatory parameters are missing') x = base64_to_long(jwk_dict.get('x')) y = base64_to_long(jwk_dict.get('y')) curve = { 'P-256': ec.SECP256R1, 'P-384': ec.SECP384R1, 'P-521': ec.SECP521R1, }[jwk_dict['crv']] public = ec.EllipticCurvePublicNumbers(x, y, curve()) if 'd' in jwk_dict: d = base64_to_long(jwk_dict.get('d')) private = ec.EllipticCurvePrivateNumbers(d, public) return private.private_key(self.cryptography_backend()) else: return public.public_key(self.cryptography_backend())
def test_signing_with_example_keys(self, backend, vector, hash_type): curve_type = ec._CURVE_TYPES[vector["curve"]] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePrivateNumbers( vector["d"], ec.EllipticCurvePublicNumbers(vector["x"], vector["y"], curve_type()), ).private_key(backend) assert key pkey = key.public_key() assert pkey with pytest.warns(CryptographyDeprecationWarning): signer = key.signer(ec.ECDSA(hash_type())) signer.update(b"YELLOW SUBMARINE") signature = signer.finalize() with pytest.warns(CryptographyDeprecationWarning): verifier = pkey.verifier(signature, ec.ECDSA(hash_type())) verifier.update(b"YELLOW SUBMARINE") verifier.verify()
def test_signing_with_example_keys(self, backend, subtests): vectors = itertools.product( load_vectors_from_file( os.path.join( "asymmetric", "ECDSA", "FIPS_186-3", "KeyPair.rsp" ), load_fips_ecdsa_key_pair_vectors, ), _HASH_TYPES.values(), ) for vector, hash_type in vectors: with subtests.test(): curve_type = ec._CURVE_TYPES[vector["curve"]] _skip_ecdsa_vector(backend, curve_type, hash_type) key = ec.EllipticCurvePrivateNumbers( vector["d"], ec.EllipticCurvePublicNumbers( vector["x"], vector["y"], curve_type() ), ).private_key(backend) assert key pkey = key.public_key() assert pkey with pytest.warns(CryptographyDeprecationWarning): signer = key.signer(ec.ECDSA(hash_type())) signer.update(b"YELLOW SUBMARINE") signature = signer.finalize() with pytest.warns(CryptographyDeprecationWarning): verifier = pkey.verifier(signature, ec.ECDSA(hash_type())) verifier.update(b"YELLOW SUBMARINE") verifier.verify()
def test_private_numbers_eq(self): pub = ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1()) priv = ec.EllipticCurvePrivateNumbers(1, pub) assert priv == ec.EllipticCurvePrivateNumbers( 1, ec.EllipticCurvePublicNumbers(1, 2, ec.SECP192R1()))