Exemplo n.º 1
0
 def test_thumbprint(self):
     '''
     nose2 jose.tests.test_jwk.TestJwk.test_thumbprint
     '''
     jwk = Jwk(**JWK_THUMBPRINT.jwk_data)
     self.assertEqual(
         jwk.thumbprint(),
         JWK_THUMBPRINT.thumbprint_value_b64)
Exemplo n.º 2
0
 def __init__(self, identifier, jku, jwkset=None):
     self.identifier = identifier 
     self.jku = jku 
     self.jwkset = jwkset or JwkSet(
         keys=[
             Jwk.generate(KeyTypeEnum.RSA),
             Jwk.generate(KeyTypeEnum.EC),
             Jwk.generate(KeyTypeEnum.OCT),
         ]   
     )   
Exemplo n.º 3
0
Arquivo: pbes2.py Projeto: hdknr/jose
def wrap_command():
    parser = ArgumentParser(description='PBES2 Key Derivation')
    parser.add_argument('command', help="wrap")
    parser.add_argument('password')
    parser.add_argument('cek', nargs='?', default=None, type=basestring)
    parser.add_argument('key_len', nargs='?', default=16, type=int)
    parser.add_argument('-f', '--foo')
    parser.add_argument('-s', '--salt', dest="salt", action="store",
                        default=None, help='base64salt')
    parser.add_argument('-a', '--alg', dest="alg", action="store",
                        default='HS256', help='HS256|HS384|HS512')
    parser.add_argument('-c', '--count', dest="count",
                        action="store", type=int,
                        default=1024, help='KDF2 counter')
    args = parser.parse_args()

    wrapper = dict(
        HS256=KeyEncEnum.PBES2_HS384_A192KW,
        HS348=KeyEncEnum.PBES2_HS384_A192KW,
        HS512=KeyEncEnum.PBES2_HS512_A256KW,
    )[args.alg].encryptor

    if args.cek:
        cek = base64.base64url_decode(args.cek)
    else:
        cek = Random.get_random_bytes(args.key_len)

    jwk = Jwk(kty=keys.KeyTypeEnum.OCT)
    if args.password == 'random':
        jwk.k = base64.base64url_encode(
            Random.get_random_bytes(wrapper.key_length()))
    elif args.password.startswith('b64url:'):
        jwk.k = args.password[6:]
    else:
        jwk.k = base64.base64url_encode(args.password)

    salt = args.salt or base64.base64url_encode(
        Random.get_random_bytes(wrapper.key_length()))

    assert len(jwk.key.shared_key) == wrapper.key_length()

    kek = wrapper.derive(jwk, salt, args.count)
    cek_ci = wrapper.encrypt(kek, cek)

    print "share key(b64url)=", base64.base64url_encode(jwk.k),
    print "cek(b64url)=", base64.base64url_encode(cek)
    print "salt(b64url)=", base64.base64url_encode(salt),
    print "kek(b64url)=", base64.base64url_encode(kek),
    print "warapped cek(b64url)=", base64.base64url_encode(cek_ci),
    print "key length=", args.key_len,
    print "alg=", args.alg, wrapper.__name__,
    print "count=", args.count
Exemplo n.º 4
0
    def test_serialize(self):
        '''
        nose2 jose.tests.test_jwk.TestJwk.test_serialize
        '''

        data = ''' { "kty":"RSA" } '''

        jwk = Jwk.from_json(data)
        self.assertEquals(jwk.kty, KeyTypeEnum.RSA)
        self.assertIsNone(jwk.use)

        data = jwk.to_json()
        jwk2 = Jwk.from_json(data)
        self.assertEquals(jwk.kty, jwk2.kty)
        self.assertEquals(jwk.use, jwk2.use)
Exemplo n.º 5
0
 def test_generate(self):
     '''
     nose2 jose.tests.test_jwk.TestJwk.test_generate
     '''
     for name, kty in KeyTypeEnum.__members__.items():
         jwk = Jwk.generate(kty=kty, kid="hoge")
         print jwk.to_json(indent=2)
Exemplo n.º 6
0
Arquivo: ec.py Projeto: hdknr/jose
    def provide(cls, enc, jwk, jwe, cek=None, iv=None, *args, **kwargs):
        if cls._KEY_WRAP is None and cek is not None:
            #: CEK must be None for ECDH_ES
            return None

        jwe.apu = jwe.apu or "TODO:RANDOM APU"
        jwe.apv = jwe.apv or "TODO:RANDOM APv"

        if cek:
            pass
        else:
            cek, iv = enc.encryptor.create_key_iv()

        #: parmeters for ECDH
        epk = Jwk.generate(kty=KeyTypeEnum.EC)      # new adhoc key
        agr = epk.key.agreement_to(jwk.key)
        klen = cls.digest_key_bitlength(enc)
        algid = jwe.alg.value if cls._KEY_WRAP else enc.value
        other_info = cls.other_info(algid, jwe.apu, jwe.apv, klen)

        #: create or derived key
        key, cek_ci = cls.create_key(agr, klen, other_info, cek)
        cek = cek if cls._KEY_WRAP else key

        jwe.epk = epk.public_jwk

        return (cek, iv, cek_ci, key)
Exemplo n.º 7
0
Arquivo: az.py Projeto: hdknr/connect
        def run(self, params, **options):
            authority  = Authority.objects.get(id=params.id[0])
            jku = authority.auth_metadata_object.jwks_uri or \
                AuthorityKeyResource.url(
                    authority.identifier, 
                    tenant=authority.tenant, id=params.jkuid)

            jwkset = JwkSet(
                keys=[Jwk.generate(kty=params.kty[0])])
            jwkset.save(authority, jku)
Exemplo n.º 8
0
    def test_algs(self):
        ''' nose2 jose.tests.test_jws.TestJwsMessage.test_algs'''


        for alg in SigDict.values():
            alg = SigEnum.create(alg)

            signer = "https://%s.com" % alg.name
            jku = signer + "/jwkset"
            jwk = Jwk.generate(alg.key_type)

            plaintext = "This is a message to be signed by %s" % alg.value

            signature = alg.signer.sign(jwk, plaintext)
            self.assertTrue(alg.signer.verify(jwk, plaintext, signature))
            print alg.value, jwk.kty.value, len(signature), _BE(signature)
Exemplo n.º 9
0
Arquivo: jwk.py Projeto: hdknr/jose
 def run(self, args):
     super(CreateCommand, self).run(args)
     jwk = Jwk.generate(**self.inits)
     jwk.add_to(args.id, args.jku)
Exemplo n.º 10
0
 def _create_jwk(self, owner, jku, alg):
     #        jwk = Jwk.get_or_create_from(
     #         owner, jku, alg.key_type, kid=None)
     jwk = Jwk.generate(alg.key_type)
     return jwk
Exemplo n.º 11
0
Arquivo: rsa.py Projeto: hdknr/jose
        ret = cls._cipher.new(jwk.key.private_key).decrypt(cek_ci, _sentinel)
        if ret == _sentinel:
            return None
        return ret


class RSA_OAEP(RsaKeyEncryptor):
    _cipher = PKCS1_OAEP

    @classmethod
    def decrypt(cls, jwk, cek_ci, *args, **kwargs):
        return cls._cipher.new(jwk.key.private_key).decrypt(cek_ci)

if __name__ == '__main__':
    from jose.jwe import Jwe
    from jose.jwa.keys import KeyTypeEnum

    jwk = Jwk.generate(kty=KeyTypeEnum.RSA)
    jwe = Jwe.from_json('{"alg": "RSA1_5", "enc": "A128CBC-HS256"}')
    cek, iv, cek_ci, kek = jwe.provide_key(jwk)

    print("CEK", base64.base64url_encode(cek))
    print("IV", base64.base64url_encode(iv))
    print("CEK_CI", base64.base64url_encode(cek_ci))

    cek2 = jwe.agree_key(jwk, cek_ci)
    print("CEK2", base64.base64url_encode(cek_ci))
    print("IV", base64.base64url_encode(iv))

    assert(cek == cek2)
Exemplo n.º 12
0
Arquivo: hmac.py Projeto: hdknr/jose
    @property
    def private_key(self):
        return self.material

    @property
    def public_key(self):
        return self.material

    @property
    def is_private(self):
        return self.material is not None

    @property
    def is_public(self):
        return self.material is not None

    @property
    def shared_key(self):
        return self.material

    def thumbprint_fields(self):
        return ['k', 'kty', ]

if __name__ == '__main__':
    from jose.jwa.keys import KeyTypeEnum
    jwk = Jwk.generate(kty=KeyTypeEnum.create('oct'))
    assert len(jwk.key.shared_key) == 200

    jwk = Jwk.generate(kty=KeyTypeEnum.create('oct'), length=32)
    assert len(jwk.key.shared_key) == 32
Exemplo n.º 13
0
    def test_jws_appendix_a4(self):
        header_str = '{"alg":"ES512"}'
        header_oct = [
            123, 34, 97, 108, 103, 34,
            58, 34, 69, 83, 53, 49, 50, 34, 125]
        self.assertEqual(
            [isinstance(i, int) and i or ord(i[:1]) for i in b(header_str)],
            header_oct)

        header_b64 = 'eyJhbGciOiJFUzUxMiJ9'
        self.assertEqual(
            base64.base64url_encode(header_str), b(header_b64))

        payload_str = "Payload"
        payload_oct = [
            80, 97, 121, 108, 111, 97, 100,
        ]
        self.assertEqual(
            [isinstance(i, int) and i or ord(i[:1]) for i in b(payload_str)],
            payload_oct)

        payload_b64 = "UGF5bG9hZA"
        self.assertEqual(
            base64.base64url_encode(payload_str), b(payload_b64))

        signing_input_b64 = ".".join([header_b64, payload_b64])
        signing_input_oct = [
            101, 121, 74, 104, 98, 71, 99,
            105, 79, 105, 74, 70, 85, 122, 85,
            120, 77, 105, 74, 57, 46, 85, 71,
            70, 53, 98, 71, 57, 104, 90, 65]
        self.assertEqual(_ilist(signing_input_b64), signing_input_oct)

        jwk_str = '''
 {"kty":"EC",
  "crv":"P-521",
  "x":"AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk",
  "y":"ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2",
  "d":"AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C"
 }'''

        from jose.jwk import Jwk
        jwk = Jwk.from_json(jwk_str)

        import hashlib

        # Sign
        pri = jwk.key.private_key_tuple

        self.assertEqual(pri[0], 521)
        self.assertEqual(
            pri[1],
            base64.long_from_b64(
                'AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPAxerEzgdRhajnu0ferB0d53vM9mE15j2C')  # NOQA
        )

        digest = int(hashlib.new('sha512',
                                 b(signing_input_b64)).hexdigest(), 16)
        signature = jwk.key.sign_longdigest(digest)
        self.assertEqual(type(signature), tuple)
        #: This signature changes everytime.
        self.assertTrue(isinstance(signature, tuple))
        self.assertEqual(len(signature), 2)

        # Verify
        pub = jwk.key.public_key_tuple
        self.assertEqual(pub[0], 521)
        self.assertEqual(pub[1],
            base64.long_from_b64(
                "AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk"  # NOQA
            )
        )
        self.assertEqual(pub[2],
            base64.long_from_b64(
                "ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDly79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2"  # NOQA
            )
        )

        self.assertTrue(jwk.key.verify_longdigest(digest, signature))

        sig_jws_oct = (
            [1, 220, 12, 129, 231, 171, 194, 209, 232, 135, 233,
             117, 247, 105, 122, 210, 26, 125, 192, 1, 217, 21, 82,
             91, 45, 240, 255, 83, 19, 34, 239, 71, 48, 157, 147,
             152, 105, 18, 53, 108, 163, 214, 68, 231, 62, 153, 150,
             106, 194, 164, 246, 72, 143, 138, 24, 50, 129, 223, 133,
             206, 209, 172, 63, 237, 119, 109],
            [0, 111, 6, 105, 44, 5, 41, 208, 128, 61, 152, 40, 92,
             61, 152, 4, 150, 66, 60, 69, 247, 196, 170, 81, 193,
             199, 78, 59, 194, 169, 16, 124, 9, 143, 42, 142, 131,
             48, 206, 238, 34, 175, 83, 203, 220, 159, 3, 107, 155,
             22, 27, 73, 111, 68, 68, 21, 238, 144, 229, 232, 148,
             188, 222, 59, 242, 103]
        )

        sig_jws_b64 = ''.join([
            'AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZq',
            'wqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8Kp',
            'EHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn',
        ])

        sig_jws_str = base64.base64url_decode(sig_jws_b64)
        self.assertEqual(len(sig_jws_str), 66 * 2)
        from Crypto.Util.number import bytes_to_long
        sig_jws_tuple = (bytes_to_long(sig_jws_str[:66]),
                         bytes_to_long(sig_jws_str[66:]),)

        self.assertTrue(jwk.key.verify_longdigest(digest, sig_jws_tuple))
Exemplo n.º 14
0
    def test_jws_appendix_a4(self):
        ''' nose2 jose.tests.test_jws.TestJws.test_jws_appendix_a4'''

        #: Data
        header_b64 = 'eyJhbGciOiJFUzUxMiJ9'
        payload_b64 = "UGF5bG9hZA"
        signature_b64 = ''.join([
            'AdwMgeerwtHoh-l192l60hp9wAHZFVJbLfD_UxMi70cwnZOYaRI1bKPWROc-mZZq',
            'wqT2SI-KGDKB34XO0aw_7XdtAG8GaSwFKdCAPZgoXD2YBJZCPEX3xKpRwcdOO8Kp',
            'EHwJjyqOgzDO7iKvU8vcnwNrmxYbSW9ERBXukOXolLzeO_Jn',
        ])

        jws = Jws.from_b64u(header_b64)
        self.assertIsNotNone(jws)
        self.assertEqual(jws.alg, SigEnum.ES512)

        jwk_dict = {
            "kty": "EC",
            "crv": "P-521",
            "x": "".join([
                "AekpBQ8ST8a8VcfVOTNl353vSrDCLL",
                "JXmPk06wTjxrrjcBpXp5EOnYG_NjFZ",
                "6OvLFV1jSfS9tsz4qUxcWceqwQGk",
            ]),
            "y": "".join([
                "ADSmRA43Z1DSNx_RvcLI87cdL07l6j",
                "QyyBXMoxVg_l2Th-x3S1WDhjDly79a",
                "jL4Kkd0AZMaZmh9ubmf63e3kyMj2",
            ]),
            "d": "".join([
                "AY5pb7A0UFiB3RELSD64fTLOSV_jaz",
                "dF7fLYyuTw8lOfRhWg6Y6rUrPAxerE",
                "zgdRhajnu0ferB0d53vM9mE15j2C"
            ])}

        from Crypto.Util.number import bytes_to_long

        #: Key
        jwk = Jwk(**jwk_dict)
        pub_jwk = jwk.public_jwk
        self.assertEqual(
            pub_jwk.key.public_key._pub[1],
            (
                bytes_to_long(base64.base64url_decode(jwk_dict['x'])),
                bytes_to_long(base64.base64url_decode(jwk_dict['y'])),
            )
        )

        # Verify
        jws_token = ".".join([header_b64, payload_b64, signature_b64])
        msg = Message.from_token(jws_token, sender=None, receiver=None)
        self.assertIsNotNone(msg)
        self.assertEqual(len(msg.signatures), 1)
        self.assertEqual(msg.signatures[0].signature, signature_b64)

        from jose.jwa.ec import EcdsaSigner
        sigbytes = base64.base64url_decode(msg.signatures[0].signature)
        self.assertEqual(len(sigbytes), 132)
        (r, s) = EcdsaSigner.decode_signature(sigbytes)

        R = [
            1, 220, 12, 129, 231, 171, 194, 209, 232, 135, 233,
            117, 247, 105, 122, 210, 26, 125, 192, 1, 217, 21, 82,
            91, 45, 240, 255, 83, 19, 34, 239, 71, 48, 157, 147,
            152, 105, 18, 53, 108, 163, 214, 68, 231, 62, 153, 150,
            106, 194, 164, 246, 72, 143, 138, 24, 50, 129, 223, 133,
            206, 209, 172, 63, 237, 119, 109]

        S = [
            0, 111, 6, 105, 44, 5, 41, 208, 128, 61, 152, 40, 92,
            61, 152, 4, 150, 66, 60, 69, 247, 196, 170, 81, 193,
            199, 78, 59, 194, 169, 16, 124, 9, 143, 42, 142, 131,
            48, 206, 238, 34, 175, 83, 203, 220, 159, 3, 107, 155,
            22, 27, 73, 111, 68, 68, 21, 238, 144, 229, 232, 148,
            188, 222, 59, 242, 103]

        self.assertEqual(r, bytes_to_long("".join(chr(i) for i in R)))
        self.assertEqual(s, bytes_to_long("".join(chr(i) for i in S)))

        print jwk.to_json(indent=2)
        self.assertTrue(msg.signatures[0].verify(
                        msg.payload, jwk=jwk))
Exemplo n.º 15
0
Arquivo: gcm.py Projeto: hdknr/jose
    encs = ['A128GCM', 'A192GCM', 'A256GCM']
    algs = ['A128GCMKW', 'A192GCMKW', 'A256GCMKW']

    for e in encs:
        enc = EncEnum.create(e).encryptor
        cek, iv = enc.create_key_iv()
        assert len(cek) == enc._KEY_LEN
        assert len(iv) == enc._IV_LEN
        print(enc.__name__)
        print("CEK =", base64.urlsafe_b64encode(cek))
        print("IV=", base64.urlsafe_b64encode(iv))

    import itertools
    from jose.jwk import Jwk
    from jose.jwe import Jwe
    jwk = Jwk.generate(kty="oct")
    for a, e in list(itertools.product(algs, encs)):
        jwe = Jwe(
            alg=KeyEncEnum.create(a),
            enc=EncEnum.create(e),
        )
        cek, iv, cek_ci, kek = jwe.provide_key(jwk)

        print("alg=", a, "enc=", e)
        print("CEK=", base64.base64url_encode(cek))
        print("IV=", base64.base64url_encode(iv))
        print("CEK_CI=", base64.base64url_encode(cek_ci))
        print("Jwe.iv=",  jwe.iv)
        print("Jwe.tag=",  jwe.tag)

        cek2 = jwe.agree_key(jwk, cek_ci)
Exemplo n.º 16
0
    def test_rs256(self):
        ''' nose2 jose.tests.test_jws.TestJws.test_rs256'''
        ''' JWS A.2
        '''

        octes = [123, 34, 97, 108, 103, 34, 58,
                 34, 82, 83, 50, 53, 54, 34, 125]

        jws_str = ''.join(chr(i) for i in octes)
        self.assertEqual(jws_str, '{"alg":"RS256"}')
        jws_new = Jws.from_json(jws_str)
        self.assertEqual(jws_new.alg, SigEnum.RS256)

        b64_header = base64.base64url_encode(jws_str)
        self.assertEqual(b64_header, 'eyJhbGciOiJSUzI1NiJ9')

        b64_payload = ''.join([
            'eyJpc3MiOiJqb2UiLA0KICJleHAiOj',
            'EzMDA4MTkzODAsDQogImh0dHA6Ly9leGFt',
            'cGxlLmNvbS9pc19yb290Ijp0cnVlfQ'])
        payload = base64.base64url_decode(b64_payload)

        jwt_new = Jwt.from_json(payload)
        self.assertEqual(jwt_new.iss, "joe")
        self.assertEqual(jwt_new.exp, 1300819380)
        self.assertEqual(jwt_new['http://example.com/is_root'], True)

        s_input = [
            101, 121, 74, 104, 98, 71, 99,
            105, 79, 105, 74, 83, 85, 122, 73,
            49, 78, 105, 74, 57, 46, 101, 121,
            74, 112, 99, 51, 77, 105, 79, 105,
            74, 113, 98, 50, 85, 105, 76, 65,
            48, 75, 73, 67, 74, 108, 101, 72,
            65, 105, 79, 106, 69, 122, 77, 68,
            65, 52, 77, 84, 107, 122, 79, 68,
            65, 115, 68, 81, 111, 103, 73, 109,
            104, 48, 100, 72, 65, 54, 76,
            121, 57, 108, 101, 71, 70, 116, 99,
            71, 120, 108, 76, 109, 78, 118,
            98, 83, 57, 112, 99, 49, 57, 121, 98,
            50, 57, 48, 73, 106, 112, 48,
            99, 110, 86, 108, 102, 81]

        s_input_str = "".join(chr(i) for i in s_input)
        self.assertEqual(
            s_input_str, ".".join([b64_header, b64_payload]))

        pri_json_dict = {
            "kty": "RSA",
            "n": "".join([
                "ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddx",
                "HmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMs",
                "D1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSH",
                "SXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdV",
                "MTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8",
                "NAco9_h9iaGNj8q2ethFkMLs91kzk2PAcDTW9gb54h4FRWyuXpoQ"]),
            "e": "AQAB",
            "d": "".join([
                "Eq5xpGnNCivDflJsRQBXHx1hdR1k6Ulwe2JZD50LpXyWPEAeP88vLNO97I",
                "jlA7_GQ5sLKMgvfTeXZx9SE-7YwVol2NXOoAJe46sui395IW_GO-pWJ1O0",
                "BkTGoVEn2bKVRUCgu-GjBVaYLU6f3l9kJfFNS3E0QbVdxzubSu3Mkqzjkn",
                "439X0M_V51gfpRLI9JYanrC4D4qAdGcopV_0ZHHzQlBjudU2QvXt4ehNYT",
                "CBr6XCLQUShb1juUO1ZdiYoFaFQT5Tw8bGUl_x_jTj3ccPDVZFD9pIuhLh",
                "BOneufuBiB4cS98l2SR_RQyGWSeWjnczT0QU91p1DhOVRuOopznQ"]),
        }

        jwk = Jwk(**pri_json_dict)
        self.assertTrue(jwk.key.is_private)
        signer = jws_new.alg.signer

        from jose.jwa.rsa import RS256
        self.assertEqual(signer, RS256)

        sig_calc = signer.sign(jwk, s_input_str)

        sig = [
            112, 46, 33, 137, 67, 232, 143,
            209, 30, 181, 216, 45, 191, 120, 69,
            243, 65, 6, 174, 27, 129, 255, 247,
            115, 17, 22, 173, 209, 113, 125,
            131, 101, 109, 66, 10, 253, 60,
            150, 238, 221, 115, 162, 102, 62, 81,
            102, 104, 123, 0, 11, 135, 34, 110, 1, 135, 237, 16, 115, 249, 69,
            229, 130, 173, 252, 239, 22, 216, 90, 121, 142, 232, 198, 109, 219,
            61, 184, 151, 91, 23, 208, 148, 2, 190, 237, 213, 217, 217, 112, 7,
            16, 141, 178, 129, 96, 213, 248, 4, 12, 167, 68, 87, 98, 184, 31,
            190, 127, 249, 217, 46, 10, 231,
            111, 36, 242, 91, 51, 187, 230, 244,
            74, 230, 30, 177, 4, 10, 203, 32, 4, 77, 62, 249, 18, 142, 212, 1,
            48, 121, 91, 212, 189, 59, 65, 238,
            202, 208, 102, 171, 101, 25, 129,
            253, 228, 141, 247, 127, 55, 45, 195, 139, 159, 175, 221, 59, 239,
            177, 139, 93, 163, 204, 60, 46, 176, 47, 158, 58, 65, 214, 18, 202,
            173, 21, 145, 18, 115, 160, 95, 35,
            185, 232, 56, 250, 175, 132, 157,
            105, 132, 41, 239, 90, 30, 136, 121, 130, 54, 195, 212, 14, 96, 69,
            34, 165, 68, 200, 242, 122, 122, 45,
            184, 6, 99, 209, 108, 247, 202,
            234, 86, 222, 64, 92, 178, 33, 90, 69, 178, 194, 85, 102, 181, 90,
            193, 167, 72, 160, 112, 223, 200,
            163, 42, 70, 149, 67, 208, 25, 238, 251, 71]

        self.assertEqual(sig, [ord(i) for i in sig_calc])

        b64_sig = "".join([
            'cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7',
            'AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4',
            'BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K',
            '0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv',
            'hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB',
            'p0igcN_IoypGlUPQGe77Rw'])

        self.assertEqual(b64_sig, base64.base64url_encode(sig_calc))

        ##########################
        # implementation
        jws_impl = Jws(alg='RS256')
        msg = Message(payload=_BE(payload))
        msg.signatures.append(Signature(_protected=jws_impl))

        token = msg.serialize_compact(jwk=jwk)
        items = token.split('.')
        self.assertEqual(len(msg.signatures), 1)
        self.assertEqual(msg.signatures[0]._protected.alg.value, 'RS256')
        self.assertEqual(len(items), 3)
        self.assertEqual(msg.signatures[0].protected, items[0])
        self.assertEqual(msg.payload, items[1])
        self.assertEqual(msg.signatures[0].signature, items[2])

        #: restore token
        msg2 = Message.from_token(token, sender=None, receiver=None)
        self.assertEqual(len(msg2.signatures), 1)
        self.assertEqual(msg2.payload, _BE(payload))
        self.assertEqual(msg2.payload, msg.payload)

        self.assertEqual(len(msg2.signatures), 1)
        self.assertEqual(msg2.signatures[0]._protected.alg.value, 'RS256')
        self.assertEqual(msg2.signatures[0].protected, items[0])
        self.assertEqual(msg2.payload, items[1])
        self.assertEqual(msg2.signatures[0].signature, items[2])

        #: verify message
        s = msg2.signatures[0]
        self.assertTrue(s.verify(msg2.payload, jwk=jwk))

        #: wrong key fails
        new_jwk = Jwk.generate(KeyTypeEnum.RSA)
        self.assertFalse(s.verify(msg2.payload, jwk=new_jwk))

        #: Json Serialization
        json_str = msg.serialize_json(jwk, indent=2)

        msg3 = Message.from_token(json_str)
        self.assertEqual(len(msg3.signatures), 1)
        self.assertTrue(
            msg3.signatures[0].verify(msg3.payload, jwk.public_jwk))
        self.assertFalse(
            msg3.signatures[0].verify(msg3.payload, new_jwk.public_jwk))
Exemplo n.º 17
0
 def __init__(self, token):
     self.id_token = IdToken.from_b64u(token.split('.')[1])
     self.jwk = Jwk.from_json(self.id_token.sub_jwk)