Example #1
0
 def loads_public_key(cls, obj):
     curve = cls.DSS_CURVES[obj['crv']]()
     public_numbers = EllipticCurvePublicNumbers(
         base64_to_int(obj['x']),
         base64_to_int(obj['y']),
         curve,
     )
     return public_numbers.public_key(default_backend())
Example #2
0
 def load_public_key(self):
     curve = self.DSS_CURVES[self._dict_data['crv']]()
     public_numbers = EllipticCurvePublicNumbers(
         base64_to_int(self._dict_data['x']),
         base64_to_int(self._dict_data['y']),
         curve,
     )
     return public_numbers.public_key(default_backend())
Example #3
0
    def __init__(self, x, y, d=None, kid=None, curve=None):
        super(EllipticCurveKey, self).__init__()

        self._kid = kid or str(uuid.uuid4())
        self._default_algo = _curve_to_default_algo[curve]
        curve_cls = _kv_crv_to_crypto_cls[curve]

        public_numbers = EllipticCurvePublicNumbers(x, y, curve_cls())
        self._public_key = public_numbers.public_key(default_backend())
        self._private_key = None
        if d is not None:
            private_numbers = EllipticCurvePrivateNumbers(d, public_numbers)
            self._private_key = private_numbers.private_key(default_backend())
    def loads(self, obj):
        for k in ['crv', 'x', 'y']:
            if k not in obj:
                raise ValueError('Not a elliptic curve key')

        curve = self.DSS_CURVES[obj['crv']]()
        public_numbers = EllipticCurvePublicNumbers(
            base64_to_int(obj['x']),
            base64_to_int(obj['y']),
            curve,
        )
        if 'd' in obj:
            private_numbers = EllipticCurvePrivateNumbers(
                base64_to_int(obj['d']), public_numbers)
            return private_numbers.private_key(default_backend())
        return public_numbers.public_key(default_backend())
Example #5
0
def cryptography_ec2_public_key(
        credential_public_key: EC2CredentialPublicKey) -> PublicKey:
    x = int.from_bytes(credential_public_key.x, 'big')
    y = int.from_bytes(credential_public_key.y, 'big')

    curve = None
    if credential_public_key.crv.name == 'P_256': curve = SECP256R1()
    elif credential_public_key.crv.name == 'P_384': curve = SECP384R1()
    elif credential_public_key.crv.name == 'P_521': curve = SECP521R1()
    else:
        raise UnimplementedError(
            'Unsupported cryptography EC2 curve {}'.format(
                credential_public_key.crv.name))

    ecpn = EllipticCurvePublicNumbers(x, y, curve)
    return ecpn.public_key(default_backend())
Example #6
0
def cryptography_ec2_public_key(
        credential_public_key: EC2CredentialPublicKey) -> EC2PublicKey:
    """Convert an `EC2CredentialPublicKey` into a cryptography `EC2PublicKey`.

    Args:
      credential_public_key (EC2CredentialPublicKey): The key to convert.

    Returns:
      A cryptography `EC2PublicKey`.

    Raises:
      UnimplementedError: If the conversion logic for the given type of
        CredentialPublicKey has not been implemented.
      PublicKeyConversionError: If the provided key could not be converted
        into a valid cryptography `EC2PublicKey`.
    """
    x = int.from_bytes(credential_public_key.x, 'big')
    y = int.from_bytes(credential_public_key.y, 'big')

    curve: Optional[Union[SECP256R1, SECP384R1, SECP521R1]] = None
    if credential_public_key.crv.name == 'P_256': curve = SECP256R1()
    elif credential_public_key.crv.name == 'P_384': curve = SECP384R1()
    elif credential_public_key.crv.name == 'P_521': curve = SECP521R1()
    else:
        raise UnimplementedError(
            'Unsupported cryptography EC2 curve {}'.format(
                credential_public_key.crv.name))

    assert curve is not None

    ecpn = EllipticCurvePublicNumbers(x, y, curve)

    try:
        return ecpn.public_key(default_backend())
    except ValueError:
        raise PublicKeyConversionError('Invalid EC2 public key')
Example #7
0
# Using OpenSSL backend for "cryptography".
BACK_END = openssl.backend

# Convert the base64url components to integers.
x_bin = base64url_decode(x_base64url)
y_bin = base64url_decode(y_base64url)

x_hex = binascii.hexlify(x_bin)
y_hex = binascii.hexlify(y_bin)

print("X: " + x_hex.decode("ascii"))
print("Y: " + y_hex.decode("ascii"))

# Convert the base64url components to integers.
x = int.from_bytes(x_bin, byteorder="big")
y = int.from_bytes(y_bin, byteorder="big")

# Acquire the public key from the public components -
public_numbers = EllipticCurvePublicNumbers(x, y, ECC_CURVE)
public_key = public_numbers.public_key(backend=BACK_END)

public_key_pem = public_key.public_bytes(Encoding.PEM,
                                         PublicFormat.SubjectPublicKeyInfo)
with open("public_key.pem", "wb") as f:
    f.write(public_key_pem)

public_key_der = public_key.public_bytes(Encoding.DER,
                                         PublicFormat.SubjectPublicKeyInfo)
with open("public_key.der", "wb") as f:
    f.write(public_key_der)
Example #8
0
handshake_messages = client_hello.subprotocol_messages[0].to_bytes() + TlsHandshakeMessage(TlsHandshakeTypeByte.SERVER_HELLO, server_hello).to_bytes() + TlsHandshakeMessage(TlsHandshakeTypeByte.CERTIFICATE, certs).to_bytes() + TlsHandshakeMessage(TlsHandshakeTypeByte.SERVER_KEY_EXCHANGE, serverkey).to_bytes() + TlsHandshakeMessage(TlsHandshakeTypeByte.SERVER_DONE, b"").to_bytes() + clientkey.subprotocol_messages[0].to_bytes()

def prf(secret, label, seed, size):
  seed = label + seed
  a = seed
  r = b""
  while len(r) < size:
    a = hmac.new(secret, a, sha384).digest()
    r += hmac.new(secret, a+seed, sha384).digest()
  return r[:size]

from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicNumbers
x = int(clientkey.subprotocol_messages[0].handshake_data[2:2+32].hex(), 16)
y = int(clientkey.subprotocol_messages[0].handshake_data[2+32:2+2*32].hex(), 16)
c = EllipticCurvePublicNumbers(x,y,ec.SECP256R1())
c = c.public_key(default_backend())
premaster = privkey.exchange(ec.ECDH(), c)
mastersecret = prf(premaster, b"extended master secret", sha384(handshake_messages).digest(), 48)
print("randoms")
print(client_random.hex())
print(server_random.hex())
print("premaster then master")
print(premaster.hex())
print(mastersecret.hex())

mac_key_length = 0
iv_length = 4
key_mat = 32
key_block = prf(mastersecret, b"key expansion", server_random+client_random, 2*mac_key_length + 2*key_mat + 2*iv_length)

clikey = key_block[2*mac_key_length:2*mac_key_length+key_mat]
Example #9
0
signature_r_bin = binascii.unhexlify(signature_r_hex)
signature_s_bin = binascii.unhexlify(signature_s_hex)
signature_r = int.from_bytes(signature_r_bin, "big")
signature_s = int.from_bytes(signature_s_bin, "big")
# Create a DER signature.
signature_der = encode_dss_signature(signature_r, signature_s)

# Convert to_be_signed from hex string to a byte array.
to_be_signed = binascii.unhexlify(to_be_signed_hex)

# Acquire the public key in two ways -
# From the private key -
public_key_from_private_key = private_key.public_key()
# From the public components -
public_numbers = EllipticCurvePublicNumbers(x, y, ECC_CURVE)
public_key_from_public_numbers = public_numbers.public_key(backend=BACK_END)
# Make sure the two are identical.
assert(public_key_from_private_key.public_numbers() == public_key_from_public_numbers.public_numbers())

# Check signature.
signature_valid = True
try:
    public_key_from_public_numbers.verify(signature_der, to_be_signed, ec.ECDSA(hashes.SHA256()))
except InvalidSignature:
    signature_valid = False

if signature_valid:
    print("The signature is valid!")
else:
    print("The signature is NOT valid.")