예제 #1
0
def test_cmp_rsa_ec():
    _key1 = RSAKey()
    _key1.load_key(import_rsa_key_from_cert_file(CERT))

    _key2 = ECKey(**ECKEY)

    assert _key1 != _key2
예제 #2
0
def test_key_from_jwk_dict_rsa():
    rsa_key = new_rsa_key()
    jwk = rsa_key.serialize(private=True)
    _key = key_from_jwk_dict(jwk)
    assert isinstance(_key, RSAKey)
    assert _key.has_private_key()
    _key2 = RSAKey(**jwk)
    assert isinstance(_key2, RSAKey)
    assert _key2.has_private_key()
예제 #3
0
def test_serialize_rsa_pub_key():
    rsakey = RSAKey(
        pub_key=import_public_rsa_key_from_file(full_path("rsa.pub")))
    assert rsakey.d == ""

    d_rsakey = rsakey.serialize(private=True)
    restored_key = RSAKey(**d_rsakey)

    assert restored_key == rsakey
def test_thumbprint_7638_example():
    key = RSAKey(
        n=
        '0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw',
        e='AQAB',
        alg='RS256',
        kid='2011-04-29')
    thumbprint = key.thumbprint('SHA-256')
    assert thumbprint == b'NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs'
def test_encrypt_decrypt_rsa_cbc():
    _key = RSAKey(pub_key=pub_key)
    _jwe0 = JWE(plain, alg="RSA1_5", enc="A128CBC-HS256")

    jwt = _jwe0.encrypt([_key])

    _jwe1 = factory(jwt, alg="RSA1_5", enc="A128CBC-HS256")
    _dkey = RSAKey(priv_key=priv_key)
    msg = _jwe1.decrypt(jwt, [_dkey])

    assert msg == plain
예제 #6
0
def test_signer_ps384():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS384")
    _jwt = _jws.sign_compact(keys)

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = JWS(alg="PS384")
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
예제 #7
0
def pem2rsa(filename: str,
            kid: Optional[str] = None,
            private: bool = False,
            passphrase: Optional[str] = None) -> JWK:
    """Convert RSA key from PEM to JWK"""
    if private:
        key = import_private_rsa_key_from_file(filename, passphrase)
    else:
        key = import_public_rsa_key_from_file(filename)
    jwk = RSAKey(kid=kid)
    jwk.load_key(key)
    return jwk
예제 #8
0
def test_signer_ps512():
    payload = "Please take a moment to register today"
    # Key has to be big enough  > 512+512+2
    _pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS512")
    _jwt = _jws.sign_compact(keys)

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = factory(_jwt, alg="PS512")
    info = _rj.verify_compact(_jwt, vkeys)
    assert info == payload
    assert _rj.verify_alg("PS512")
예제 #9
0
def test_cmp_rsa():
    _key1 = RSAKey()
    _key1.load_key(import_rsa_key_from_cert_file(CERT))

    _key2 = RSAKey()
    _key2.load_key(import_rsa_key_from_cert_file(CERT))

    assert _key1 == _key2
예제 #10
0
def test_signer_ps256_fail():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="PS256")
    _jwt = _jws.sign_compact(keys)[:-5] + "abcde"

    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    _rj = JWS(alg="PS256")
    try:
        _rj.verify_compact(_jwt, vkeys)
    except BadSignature:
        pass
    else:
        assert False
def test_str():
    _j = RSAKey(alg="RS512", use='sig', n=N, e=E)
    s = '{}'.format(_j)
    assert s.startswith("{") and s.endswith("}")
    sp = s.replace("'", '"')
    _d = json.loads(sp)
    assert set(_d.keys()) == {'alg', 'use', 'n', 'e', 'kty'}
예제 #12
0
def test_str():
    _j = RSAKey(alg="RS512", use="sig", n=N, e=E)
    s = "{}".format(_j)
    assert s.startswith("{") and s.endswith("}")
    sp = s.replace("'", '"')
    _d = json.loads(sp)
    assert set(_d.keys()) == {"alg", "use", "n", "e", "kty"}
예제 #13
0
def test_mismatch_alg_and_key():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg="ES256")
    with pytest.raises(NoSuitableSigningKeys):
        _jws.sign_compact(keys)
예제 #14
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-r",
                        dest="rsa_file",
                        help="File containing a RSA key")
    parser.add_argument("-k",
                        dest="hmac_key",
                        help="If using a HMAC algorithm this is the key")
    parser.add_argument("-i", dest="kid", help="key id")
    parser.add_argument("-j", dest="jwk", help="JSON Web Key")
    parser.add_argument("-J", dest="jwks", help="JSON Web Keys")
    parser.add_argument("-u", dest="jwks_url", help="JSON Web Keys URL")
    parser.add_argument("-f", dest="msg", help="The message")
    parser.add_argument(
        "-q",
        dest="quiet",
        help="Quiet mode -- only show the RAW but prettified JSON",
        action="store_true",
    )

    args = parser.parse_args()

    if args.kid:
        _kid = args.kid
    else:
        _kid = ""

    keys = []
    if args.rsa_file:
        keys.append(RSAKey(key=import_rsa_key(args.rsa_file), kid=_kid))
    if args.hmac_key:
        keys.append(SYMKey(key=args.hmac_key, kid=_kid))

    if args.jwk:
        _key = key_from_jwk_dict(open(args.jwk).read())
        keys.append(_key)

    if args.jwks:
        _iss = KeyIssuer()
        _iss.import_jwks(open(args.jwks).read())
        keys.extend(_iss.all_keys())

    if args.jwks_url:
        _kb = KeyBundle(source=args.jwks_url)
        keys.extend(_kb.get())

    if not args.msg:  # If nothing specified assume stdin
        message = sys.stdin.read()
    elif args.msg == "-":
        message = sys.stdin.read()
    else:
        if os.path.isfile(args.msg):
            message = open(args.msg).read().strip("\n")
        else:
            message = args.msg

    message = message.strip()
    message = message.strip('"')
    process(message, keys, args.quiet)
예제 #15
0
def test_dj_usage():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg="RS256")
    sjwt = _jws.sign_compact(keys)
    _jwt = factory(sjwt)
    assert _jwt.jwt.headers["alg"] == "RS256"
예제 #16
0
def test_extra_headers_1():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg="RS256")
    sjwt = _jws.sign_compact(keys, foo="bar")
    _jwt = factory(sjwt)
    assert set(_jwt.jwt.headers.keys()) == {"alg", "foo"}
예제 #17
0
def test_extra_headers_3():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _jws = JWS(payload, alg='RS256')
    _jws.set_header_claim('foo', 'bar')
    sjwt = _jws.sign_compact(keys, abc=123)
    _jwt = factory(sjwt)
    assert set(_jwt.jwt.headers.keys()) == {'alg', 'foo', 'abc'}
예제 #18
0
def test_factory_verify_alg():
    pkey = import_private_rsa_key_from_file(full_path("./size2048.key"))
    payload = "Please take a moment to register today"
    keys = [RSAKey(priv_key=pkey)]
    _signer = JWS(payload, alg="RS256")
    _signer.set_header_claim("foo", "bar")
    _jws = _signer.sign_compact(keys, abc=123)
    _verifier = factory(_jws)
    assert _verifier.jwt.verify_headers(alg="RS512") is False
예제 #19
0
def test_rs256_rm_signature():
    payload = "Please take a moment to register today"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    keys = [RSAKey(priv_key=_pkey)]
    # keys[0]._keytype = "private"
    _jws = JWS(payload, alg="RS256")
    _jwt = _jws.sign_compact(keys)

    p = _jwt.split(".")
    _jwt = ".".join(p[:-1])

    vkeys = [RSAKey(key=_pkey.public_key())]
    _rj = JWS()
    try:
        _ = _rj.verify_compact(_jwt, vkeys)
    except WrongNumberOfParts:
        pass
    else:
        assert False
예제 #20
0
def decrypt_from_jwe(jwe):
    RSA_KEY = settings.UNITICKET_JWT_RSA_KEY_PATH
    JWE_ALG = settings.UNITICKET_JWE_ALG
    JWE_ENC = settings.UNITICKET_JWE_ENC

    priv_key = import_private_rsa_key_from_file(RSA_KEY)
    _decryptor = factory(jwe, alg=JWE_ALG, enc=JWE_ENC)
    _dkey = RSAKey(priv_key=priv_key)
    msg = _decryptor.decrypt(jwe, [_dkey])
    return msg
예제 #21
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
예제 #22
0
 def keys() -> list:
     """
     gives you the keys in a quite usable way
     """
     # Asymmetric
     if settings.JWTAUTH_KEY and settings.JWTAUTH_CERT:
         public = settings.JWTAUTH_CERT
         private = settings.JWTAUTH_KEY
         keys = [RSAKey(priv_key=private)]
     # Symmetric
     else:
         keys = [SYMKey(key=settings.JWTAUTH_KEY)]
     return keys
def test_rsa_pubkey_verify_x509_thumbprint():
    cert = "MIID0jCCArqgAwIBAgIBSTANBgkqhkiG9w0BAQQFADCBiDELMAkGA1UEBhMCREUxEDAOBgNVBAgTB0JhdmF" \
           "yaWExEzARBgNVBAoTCkJpb0lEIEdtYkgxLzAtBgNVBAMTJkJpb0lEIENsaWVudCBDZXJ0aWZpY2F0aW9uIE" \
           "F1dGhvcml0eSAyMSEwHwYJKoZIhvcNAQkBFhJzZWN1cml0eUBiaW9pZC5jb20wHhcNMTUwNDE1MTQ1NjM4W" \
           "hcNMTYwNDE0MTQ1NjM4WjBfMQswCQYDVQQGEwJERTETMBEGA1UEChMKQmlvSUQgR21iSDE7MDkGA1UEAxMy" \
           "QmlvSUQgT3BlbklEIENvbm5lY3QgSWRlbnRpdHkgUHJvdmlkZXIgQ2VydGlmaWNhdGUwggEiMA0GCSqGSIb" \
           "3DQEBAQUAA4IBDwAwggEKAoIBAQC9aFETmU6kDfMBPKM2OfI5eedO3XP12Ci0hDC99bdzUUIhDZG34PQqcH" \
           "89gVWGthJv5w3kqpdSrxfPCFMsBdnyk1VCuXmLgXS8s4oBtt1c9iM0J8X6Z+5subS3Xje8fu55Csh0JXNfo" \
           "y29rCY/O6y0fNignegg0KS4PHv5T+agFmaG4rxCQV9/kd8tlo/HTyVPsuSPDgsXxisIVqur9aujYwdCoAZU" \
           "8OU+5ccMLNIhpWJn+xNjgDRr4L9nxAYKc9vy+f7EoH3LT24B71zazZsQ78vpocz98UT/7vdgS/IYXFniPuU" \
           "fblja7cq31bUoySDx6FYrtfCSUxNhaZSX8mppAgMBAAGjbzBtMAkGA1UdEwQCMAAwHQYDVR0OBBYEFOfg3f" \
           "/ewBLK5SkcBEXusD62OlzaMB8GA1UdIwQYMBaAFCQmdD+nVcVLaKt3vu73XyNgpPEpMAsGA1UdDwQEAwIDi" \
           "DATBgNVHSUEDDAKBggrBgEFBQcDAjANBgkqhkiG9w0BAQQFAAOCAQEAKQjhcL/iGhy0549hEHRQArJXs1im" \
           "7W244yE+TSChdMWKe2eWvEhc9wX1aVV2mNJM1ZNeYSgfoK6jjuXaHiSaIJEUcW1wVM3rDywi2a9GKzOFgrW" \
           "pVbpXQ05LSE7qEEWRmSpIMyKTitUalNpNA6cOML5hiuUTfZbw7OvPwbnbSYYL674gEA2sW5AhPiCr9dVnMn" \
           "/UK2II40802zdXUOvIxWeXpcsCxxZMjp/Ir2jIZWOEjlAXQVGr2oBfL/be/o5WXpaqWSfPRBZV8htRIf0vT" \
           "lGx7xR8FPWDYmcj4o/tKoNC1AchjOnCwwE/mj4hgtoAsHNmYXF0oZXk7cozqYDqKQ=="
    rsa_key = RSAKey(x5c=[cert], x5t="KvHXVspLmjWC6cPDIIVMHlJjN-c")
    assert rsa_key.pub_key

    with pytest.raises(DeSerializationNotPossible):
        RSAKey(x5c=[cert], x5t="abcdefgh")  # incorrect thumbprint
예제 #24
0
def test_serialize_rsa_priv_key():
    rsakey = RSAKey(
        priv_key=import_private_rsa_key_from_file(full_path("rsa.key")))
    assert rsakey.d

    d_rsakey = rsakey.serialize(private=True)
    restored_key = RSAKey(**d_rsakey)

    assert restored_key == rsakey
    assert rsakey.has_private_key()
    assert restored_key.has_private_key()
예제 #25
0
def test_dump_jwk():
    kb = KeyBundle()
    kb.append(RSAKey(pub_key=import_rsa_key_from_cert_file(CERT)))
    jwks = kb.jwks()

    _wk = json.loads(jwks)
    assert list(_wk.keys()) == ["keys"]
    assert len(_wk["keys"]) == 1
    assert set(_wk["keys"][0].keys()) == {"kty", "e", "n"}

    kb2 = KeyBundle(_wk)

    assert len(kb2) == 1
    key = kb2.get("rsa")[0]
    assert key.kty == "RSA"
    assert isinstance(key.public_key(), rsa.RSAPublicKey)
예제 #26
0
def test_kspec():
    _ckey = import_rsa_key_from_cert_file(CERT)
    _key = RSAKey()
    _key.load_key(_ckey)

    jwk = _key.serialize()
    assert jwk["kty"] == "RSA"
    assert jwk["e"] == JWK_0["keys"][0]["e"]
    assert jwk["n"] == JWK_0["keys"][0]["n"]

    assert not _key.has_private_key()
예제 #27
0
    def import_keys(self, keyspec):
        """
        The client needs it's own set of keys. It can either dynamically
        create them or load them from local storage.
        This method can also fetch other entities keys provided the
        URL points to a JWKS.

        :param keyspec:
        """
        for where, spec in keyspec.items():
            if where == 'file':
                for typ, files in spec.items():
                    if typ == 'rsa':
                        for fil in files:
                            _key = RSAKey(
                                key=import_private_rsa_key_from_file(fil),
                                use='sig')
                            _bundle = KeyBundle()
                            _bundle.append(_key)
                            self.keyjar.add_kb('', _bundle)
            elif where == 'url':
                for iss, url in spec.items():
                    _bundle = KeyBundle(source=url)
                    self.keyjar.add_kb(iss, _bundle)
예제 #28
0
def token_request(request):
    logger.debug(f'{request.headers}: {request.POST}')

    id_token = {
        "sub": "Microsoft:[email protected]",
        "nonce": "ITyym7MixGzWnTp4AMFimVk5",
        "at_hash": "a_jseUswllpYcJVPYEcj5w",
        "sid": "3dd91e80-ec4b-4cca-af44-58dfdd0544cb",
        "aud": "2c43a070-425f-4613-859c-d234ec7d71af",
        "exp": 1615749924,
        "iat": 1615746324,
        "iss": ISSUER
    }
    jwt_id_token = Message(**id_token)
    keys = [RSAKey(**JWK_PRIVATE)]
    signed_jwt_id_token = jwt_id_token.to_jwt(keys, "RS256")

    return JsonResponse({
        'access_token': 'sadasd',
        'id_token': signed_jwt_id_token,
        'token_type': 'bearer',
        'expires_in': 3600,
        'scope': 'openid profile'
    })
예제 #29
0
def test_pick_alg_dont_get_alg_from_single_key_if_already_specified():
    expected_alg = "RS512"
    _pkey = import_private_rsa_key_from_file(PRIV_KEY)
    vkeys = [RSAKey(pub_key=_pkey.public_key())]
    alg = JWS(alg=expected_alg)._pick_alg(vkeys)
    assert alg == expected_alg
예제 #30
0
def test_extract_rsa_from_cert_2():
    _ckey = import_rsa_key_from_cert_file(CERT)
    _key = RSAKey()
    _key.load_key(_ckey)

    assert _ckey.public_numbers().n == base64_to_long(_key.n)