Ejemplo n.º 1
0
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
    # Protected by default
    protected["alg"] = "ES256"
    assert _rj.protected_headers() == protected
Ejemplo n.º 2
0
def test_verify_json_missing_key():
    ec_key = ECKey().load_key(P256())
    sym_key = SYMKey(key=b"My hollow echo chamber", alg="HS384")

    protected_headers_1 = {"foo": "bar", "alg": "ES256"}
    unprotected_headers_1 = {"abc": "xyz"}
    protected_headers_2 = {"foo": "bar", "alg": "HS384"}
    unprotected_headers_2 = {"abc": "zeb"}
    payload = "hello world"
    _jwt = JWS(msg=payload).sign_json(
        headers=[
            (protected_headers_1, unprotected_headers_1),
            (protected_headers_2, unprotected_headers_2),
        ],
        keys=[ec_key, sym_key],
    )

    # Only the EC key
    vkeys = [ECKey().load_key(ec_key.public_key())]
    with pytest.raises(NoSuitableSigningKeys):
        JWS().verify_json(_jwt, keys=vkeys)

    assert JWS().verify_json(_jwt, keys=vkeys, at_least_one=True)

    # Only the SYM key
    with pytest.raises(NoSuitableSigningKeys):
        JWS().verify_json(_jwt, keys=[sym_key])

    assert JWS().verify_json(_jwt, keys=[sym_key], at_least_one=True)

    # With both
    assert JWS().verify_json(_jwt, keys=[vkeys[0], sym_key])
Ejemplo n.º 3
0
def test_key_from_jwk_dict_ec():
    key = ECKey().load(full_path("570-ec-sect571r1-keypair.pem"))
    assert key.has_private_key()
    jwk = key.serialize(private=True)
    _key = key_from_jwk_dict(jwk)
    assert isinstance(_key, ECKey)
    assert _key.has_private_key()
Ejemplo n.º 4
0
def test_verify_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)
    protectedHeader, enc_payload, sig = _jwt.split(".")
    data = dict(
        payload=enc_payload,
        signatures=[
            dict(
                header=dict(alg=u"ES256", jwk=_key.serialize()),
                protected=protectedHeader,
                signature=sig,
            )
        ],
    )

    # _pub_key = ECKey().load_key(eck.public_key())
    _jws = JWS()
    assert _jws.verify_json(json.dumps(data)) == payload
Ejemplo n.º 5
0
def test_signer_es(ec_func, alg):
    payload = "Please take a moment to register today"
    eck = ec.generate_private_key(ec_func(), default_backend())
    keys = [ECKey().load_key(eck)]
    _jws = JWS(payload, alg=alg)
    _jwt = _jws.sign_compact(keys)

    _pubkey = ECKey().load_key(eck.public_key())
    _rj = JWS(alg=alg)
    info = _rj.verify_compact(_jwt, [_pubkey])
    assert info == payload
Ejemplo n.º 6
0
def pem2ec(filename: str,
           kid: Optional[str] = None,
           private: bool = False,
           passphrase: Optional[str] = None) -> JWK:
    """Convert EC key from PEM to JWK"""
    if private:
        key = import_private_key_from_file(filename, passphrase)
    else:
        key = import_public_key_from_file(filename)
    jwk = ECKey(kid=kid)
    jwk.load_key(key)
    return jwk
Ejemplo n.º 7
0
def test_verify_json_flattened_syntax():
    key = ECKey().load_key(P256())
    protected_headers = {"foo": "bar"}
    unprotected_headers = {"abc": "xyz"}
    payload = "hello world"
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key],
                                                   flatten=True)

    vkeys = [ECKey().load_key(key.public_key())]
    assert JWS().verify_json(_jwt, keys=vkeys)
Ejemplo n.º 8
0
def test_signer_es256_verbose():
    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")
    _jwt = _jws.sign_compact(keys)

    _pubkey = ECKey().load_key(eck.public_key())
    _rj = JWS(alg="ES256")
    info = _rj.verify_compact_verbose(_jwt, [_pubkey])
    assert info["msg"] == payload
    assert info["key"] == _pubkey
Ejemplo n.º 9
0
def test_verify_json():
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    key = ECKey().load_key(eck)
    payload = "hello world"
    unprotected_headers = {"abc": "xyz"}
    protected_headers = {"foo": "bar"}
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key])

    vkeys = [ECKey().load_key(eck.public_key())]
    assert JWS().verify_json(_jwt, keys=vkeys)
Ejemplo n.º 10
0
def test_cmp_rsa_ec():
    _key1 = RSAKey()
    _key1.load_key(import_rsa_key_from_cert_file(CERT))

    _key2 = ECKey(**ECKEY)

    assert _key1 != _key2
Ejemplo n.º 11
0
def test_verify_json():
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    key = ECKey().load_key(eck)
    payload = "hello world"
    unprotected_headers = {"abc": "xyz"}
    protected_headers = {"foo": "bar"}
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key])

    vkeys = [ECKey().load_key(eck.public_key())]
    _jws = JWS()
    assert _jws.verify_json(_jwt, keys=vkeys)
    _protected = _jws.protected_headers()
    assert set(_protected.keys()) == {"foo", "alg"}
    assert _protected["foo"] == protected_headers["foo"]
    # alg is always protected by default
    assert _protected["alg"] == "ES256"
Ejemplo n.º 12
0
def test_sign_json_dont_flatten_if_multiple_signatures():
    key = ECKey().load_key(P256())
    unprotected_headers = {"foo": "bar"}
    _jwt = JWS(msg="hello world", alg="ES256").sign_json(
        headers=[(None, unprotected_headers), (None, {
            "abc": "xyz"
        })],
        keys=[key],
        flatten=True,
    )
    assert "signatures" in json.loads(_jwt)
def test_get_key():
    ec_key = generate_private_key(NIST2SEC['P-256'], default_backend())
    asym_private_key = ECKey(priv_key=ec_key)
    asym_public_key = ECKey(pub_key=asym_private_key.pub_key)
    key = SYMKey(key='mekmitasdigoatfo', kid='xyzzy')

    assert asym_private_key.private_key()
    assert asym_private_key.public_key()

    assert asym_public_key.private_key() is None
    assert asym_private_key.public_key()

    assert key.key
Ejemplo n.º 14
0
def read_cosekey(filename: str, private: bool = True) -> CoseKey:
    """Read key and return CoseKey"""
    if filename.endswith(".json"):
        with open(filename, "rt") as jwk_file:
            jwk_dict = json.load(jwk_file)
    elif filename.endswith(".key"):
        key = import_private_key_from_pem_file(filename)
        jwk = ECKey()
        jwk.load_key(key)
        jwk_dict = jwk.serialize(private=private)
    elif filename.endswith(".crt"):
        if private:
            raise ValueError("No private keys in certificates")
        key = import_public_key_from_cert_file(filename)
        jwk = ECKey()
        jwk.load_key(key)
        jwk_dict = jwk.serialize(private=private)
    else:
        raise ValueError("Unknown key format")
    return cosekey_from_jwk_dict(jwk_dict, private)
Ejemplo n.º 15
0
def test_get_key():
    ec_key = new_ec_key("P-256")
    asym_private_key = ECKey(priv_key=ec_key.priv_key)
    asym_public_key = ECKey(pub_key=asym_private_key.pub_key)
    key = SYMKey(key="mekmitasdigoatfo", kid="xyzzy")

    assert asym_private_key.private_key()
    assert asym_private_key.public_key()

    assert asym_public_key.private_key() is None
    assert asym_private_key.public_key()

    assert key.key
Ejemplo n.º 16
0
def test_sign_json_dont_include_empty_unprotected_headers():
    key = ECKey().load_key(P256())
    protected_headers = {"foo": "bar"}
    _jwt = JWS(msg="hello world",
               alg="ES256").sign_json(headers=[(protected_headers, None)],
                                      keys=[key])
    json_jws = json.loads(_jwt)
    assert "header" not in json_jws["signatures"][0]
    jws_protected_headers = json.loads(
        b64d_enc_dec(json_jws["signatures"][0]["protected"]))
    assert set(protected_headers.items()).issubset(
        set(jws_protected_headers.items()))
Ejemplo n.º 17
0
def test_sign_json_dont_include_empty_protected_headers():
    key = ECKey().load_key(P256())
    unprotected_headers = {"foo": "bar"}
    _jwt = JWS(msg="hello world",
               alg="ES256").sign_json(headers=[(None, unprotected_headers)],
                                      keys=[key])
    json_jws = json.loads(_jwt)
    jws_protected_headers = json.loads(
        b64d_enc_dec(json_jws["signatures"][0]["protected"]))
    assert jws_protected_headers == {"alg": "ES256"}
    jws_unprotected_headers = json_jws["signatures"][0]["header"]
    assert unprotected_headers == jws_unprotected_headers
Ejemplo n.º 18
0
def test_sign_json_flattened_syntax():
    key = ECKey().load_key(P256())
    protected_headers = {"foo": "bar"}
    unprotected_headers = {"abc": "xyz"}
    payload = "hello world"
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key],
                                                   flatten=True)
    json_jws = json.loads(_jwt)
    assert "signatures" not in json_jws

    assert b64d_enc_dec(json_jws["payload"]) == payload
    assert json_jws["header"] == unprotected_headers
    assert json.loads(b64d_enc_dec(json_jws["protected"])) == protected_headers
Ejemplo n.º 19
0
def test_sign_json():
    eck = ec.generate_private_key(ec.SECP256R1(), default_backend())
    key = ECKey().load_key(eck)
    payload = "hello world"
    unprotected_headers = {"abc": "xyz"}
    protected_headers = {"foo": "bar"}
    _jwt = JWS(msg=payload, alg="ES256").sign_json(headers=[
        (protected_headers, unprotected_headers)
    ],
                                                   keys=[key])
    jwt = json.loads(_jwt)
    assert b64d_enc_dec(jwt["payload"]) == payload
    assert len(jwt["signatures"]) == 1
    assert jwt["signatures"][0]["header"] == unprotected_headers
    assert json.loads(b64d_enc_dec(
        jwt["signatures"][0]["protected"])) == protected_headers
Ejemplo n.º 20
0
def pem_to_jwk_dict(pem_data: str):
    """Read PEM certificate and return JWK dictionary"""
    public_key = import_public_key_from_pem_data(pem_data)
    if isinstance(public_key, rsa.RSAPublicKey):
        jwk = RSAKey().load_key(public_key)
    elif isinstance(public_key, ec.EllipticCurvePublicKey):
        jwk = ECKey().load_key(public_key)
    else:
        raise ValueError("Unknown key type")
    jwk_dict = jwk.serialize()
    cert = x509.load_pem_x509_certificate(pem_data.encode(), default_backend())
    fp = cert.fingerprint(hashes.SHA256())
    jwk_dict["kid"] = b64e(fp[:8]).decode()
    jwk_dict["x5t#S256"] = b64e(fp).decode()
    jwk_dict["x5a"] = {
        "subject": cert.subject.rfc4514_string(),
        "issuer": cert.issuer.rfc4514_string(),
        "serial": cert.serial_number,
    }
    return jwk_dict
Ejemplo n.º 21
0
def test_is_jws_recognize_flattened_json_serialized_jws():
    key = ECKey().load_key(P256())
    jws = JWS(msg="hello world", alg="ES256").sign_json([key], flatten=True)
    assert JWS().is_jws(jws)
Ejemplo n.º 22
0
def test_load_pem_file_ec():
    key = ECKey().load(full_path("570-ec-sect571r1-keypair.pem"))
    assert key.has_private_key()
def test_create_eckey():
    ec_key = generate_private_key(NIST2SEC['P-256'], default_backend())
    ec = ECKey(priv_key=ec_key)
    exp_key = ec.serialize()
    assert _eq(list(exp_key.keys()), ["y", "x", "crv", "kty"])
Ejemplo n.º 24
0
def test_is_jws_recognize_compact_jws():
    key = ECKey().load_key(P256())
    jws = JWS(msg="hello world", alg="ES256").sign_compact([key])
    assert JWS().is_jws(jws)
def test_cmp_eq_ec():
    ec_key = generate_private_key(NIST2SEC['P-256'], default_backend())
    _key1 = ECKey(priv_key=ec_key)
    _key2 = ECKey(priv_key=ec_key)

    assert _key1 == _key2
    assert msg == plain


def test_rsa_with_kid():
    encryption_keys = [RSAKey(use="enc", pub_key=pub_key, kid="some-key-id")]
    jwe = JWE("some content", alg="RSA-OAEP", enc="A256CBC-HS512")
    jwe.encrypt(keys=encryption_keys, kid="some-key-id")


if __name__ == "__main__":
    test_rsa_with_kid()

# Test ECDH-ES

alice = ec.generate_private_key(ec.SECP256R1(), default_backend())
eck_alice = ECKey(priv_key=alice)
bob = ec.generate_private_key(ec.SECP256R1(), default_backend())
eck_bob = ECKey(priv_key=bob)


def test_ecdh_encrypt_decrypt_direct_key():
    # Alice starts of
    jwenc = JWE_EC(plain, alg="ECDH-ES", enc="A128GCM")
    cek, encrypted_key, iv, params, ret_epk = jwenc.enc_setup(plain,
                                                              key=eck_bob)

    kwargs = {
        'params': params,
        'cek': cek,
        'iv': iv,
        'encrypted_key': encrypted_key
Ejemplo n.º 27
0
def test_import_export_eckey():
    _key = ECKey(**ECKEY)
    _key.deserialize()
    assert _eq(list(_key.keys()), ["y", "x", "d", "crv", "kty"])
    assert _key.key_len() == 521
Ejemplo n.º 28
0
def test_cmp_neq_ec():
    ec_key = new_ec_key("P-256")
    _key1 = ECKey(priv_key=ec_key.priv_key)
    _key2 = ECKey(**ECKEY)

    assert _key1 != _key2
Ejemplo n.º 29
0
def test_cmp_eq_ec():
    ec_key = new_ec_key("P-256")
    _key1 = ECKey(priv_key=ec_key.priv_key)
    _key2 = ECKey(priv_key=ec_key.priv_key)

    assert _key1 == _key2