コード例 #1
0
    def to_string(self, remote_key=None, remote_ip=None):
        """
        Sign and encrypt this response.

        :param remote_key: Encrypt response to this key
        :param remote_ip: If no remote_key, look up a key for this remote_ip

        :type remote_key: str or None
        :type remote_ip: str or None

        :rtype: str
        """
        sign_key = self._config.keys.private_key
        self._logger.debug("Signing response using key {!r}".format(sign_key))
        jws = jose.sign(self._data, sign_key.jwk, alg=self._config.jose_alg)
        signed_claims = {'v1': jose.serialize_compact(jws)}
        self._logger.debug("Signed response: {!r}".format(signed_claims))
        encrypt_key = remote_key
        if not encrypt_key:
            # default to the first key found using the remote_ip in case no key was supplied
            ip_keys = self._config.keys.lookup_by_ip(remote_ip)
            if not ip_keys:
                self._logger.warning(
                    "Found no key for IP {!r}, can't encrypt response:\n{!r}".
                    format(remote_ip, self._data))
                raise EduIDAPIError(
                    "No API Key found - can't encrypt response")
            encrypt_key = ip_keys[0]
        self._logger.debug("Encrypting claims to key {!r}".format(encrypt_key))
        jwe = jose.encrypt(signed_claims, encrypt_key.jwk)
        return jose.serialize_compact(jwe)
コード例 #2
0
ファイル: tests.py プロジェクト: TiVoMaker/jose
 def test_jws_signature_mismatch_error(self):
     jwk = {'k': 'password'}
     jws = jose.sign(claims, jwk)
     try:
         jose.verify(jose.JWS(jws.header, jws.payload, 'asd'), jwk)
     except ValueError as e:
         self.assertEqual(e.message, 'Mismatched signatures')
コード例 #3
0
 def test_jws_signature_mismatch_error(self):
     jwk = {'k': 'password'}
     jws = jose.sign(claims, jwk)
     try:
         jose.verify(jose.JWS(jws.header, jws.payload, 'asd'), jwk)
     except jose.Error as e:
         self.assertEqual(e.message, 'Mismatched signatures')
コード例 #4
0
ファイル: tests.py プロジェクト: TiVoMaker/jose
    def test_jws_asym(self):
        algs = ('RS256', 'RS384', 'RS512')

        for alg in algs:
            st = jose.serialize_compact(jose.sign(claims, rsa_priv_key, alg=alg))
            jwt = jose.verify(jose.deserialize_compact(st), rsa_pub_key)
            self.assertEqual(jwt.claims, claims)
コード例 #5
0
    def to_string(self, remote_key = None, remote_ip = None):
        """
        Sign and encrypt this response.

        :param remote_key: Encrypt response to this key
        :param remote_ip: If no remote_key, look up a key for this remote_ip

        :type remote_key: str or None
        :type remote_ip: str or None

        :rtype: str
        """
        sign_key = self._config.keys.private_key
        self._logger.debug("Signing response using key {!r}".format(sign_key))
        jws = jose.sign(self._data, sign_key.jwk, alg = self._config.jose_alg)
        signed_claims = {'v1': jose.serialize_compact(jws)}
        self._logger.debug("Signed response: {!r}".format(signed_claims))
        encrypt_key = remote_key
        if not encrypt_key:
            # default to the first key found using the remote_ip in case no key was supplied
            ip_keys = self._config.keys.lookup_by_ip(remote_ip)
            if not ip_keys:
                self._logger.warning("Found no key for IP {!r}, can't encrypt response:\n{!r}".format(
                    remote_ip, self._data
                ))
                raise EduIDAPIError("No API Key found - can't encrypt response")
            encrypt_key = ip_keys[0]
        self._logger.debug("Encrypting claims to key {!r}".format(encrypt_key))
        jwe = jose.encrypt(signed_claims, encrypt_key.jwk)
        return jose.serialize_compact(jwe)
コード例 #6
0
ファイル: request.py プロジェクト: SUNET/eduid-api
 def __init__(self, claims, logger, config, alg = 'RS256'):
     self._logger = logger
     self._config = config
     self._request_result = None
     self._api_key = None
     self._claims = claims
     jws = jose.sign(claims, self._config.keys.private_key.jwk, alg=alg)
     self.signed_claims = {'v1': jose.serialize_compact(jws)}
コード例 #7
0
ファイル: tests.py プロジェクト: jaimeperez/jose
    def test_jws_sym(self):
        algs = ('HS256', 'HS384', 'HS512',)
        jwk = {'k': 'password'}

        for alg in algs:
            st = jose.serialize_compact(jose.sign(claims, jwk, alg=alg))
            jwt = jose.verify(jose.deserialize_compact(st), jwk, alg)

            self.assertEqual(jwt.claims, claims)
コード例 #8
0
    def test_jws_sym(self):
        algs = ('HS256', 'HS384', 'HS512',)
        jwk = {'k': 'password'}

        for alg in algs:
            st = jose.serialize_compact(jose.sign(claims, jwk, alg=alg))
            jwt = jose.verify(jose.deserialize_compact(st), jwk, alg)

            self.assertEqual(jwt.claims, claims)
コード例 #9
0
 def test_jws_invalid_algorithm_error(self):
     sign_alg = 'HS256'
     verify_alg = 'RS256'
     jwk = {'k': 'password'}
     jws = jose.sign(claims, jwk, alg=sign_alg)
     try:
         jose.verify(jose.JWS(jws.header, jws.payload, 'asd'), jwk,
                     verify_alg)
     except jose.Error as e:
         self.assertEqual(e.message, 'Invalid algorithm')
コード例 #10
0
ファイル: tests.py プロジェクト: jaimeperez/jose
 def test_jws_invalid_algorithm_error(self):
     sign_alg = 'HS256'
     verify_alg = 'RS256'
     jwk = {'k': 'password'}
     jws = jose.sign(claims, jwk, alg=sign_alg)
     try:
         jose.verify(jose.JWS(jws.header, jws.payload, 'asd'), jwk,
                     verify_alg)
     except jose.Error as e:
         self.assertEqual(e.message, 'Invalid algorithm')
コード例 #11
0
ファイル: views.py プロジェクト: johanlundberg/eduid-webapp
def get_freja_state(user):
    current_app.logger.debug('Getting state for user {!s}.'.format(user))
    try:
        proofing_state = current_app.proofing_statedb.get_state_by_eppn(
            user.eppn)
        expire_time = current_app.config['FREJA_EXPIRE_TIME_HOURS']
        if helpers.is_proofing_state_expired(proofing_state, expire_time):
            current_app.proofing_statedb.remove_state(proofing_state)
            current_app.stats.count(name='freja.proofing_state_expired')
            raise DocumentDoesNotExist(reason='freja proofing state expired')
    except DocumentDoesNotExist:
        return {}
    # Return request data
    current_app.logger.debug(
        'Returning request data for user {!s}'.format(user))
    current_app.stats.count(name='freja.proofing_state_returned')
    opaque_data = helpers.create_opaque_data(proofing_state.nonce,
                                             proofing_state.token)
    valid_until = helpers.get_proofing_state_valid_until(
        proofing_state, expire_time)
    request_data = {
        "iarp": current_app.config['FREJA_IARP'],
        "exp": int(valid_until.astimezone(UTC()).strftime('%s')) *
        1000,  # Milliseconds since 1970 in UTC
        "proto": current_app.config['FREJA_RESPONSE_PROTOCOL'],
        "opaque": opaque_data
    }
    jwk = {'k': current_app.config['FREJA_JWK_SECRET'].decode('hex')}
    jws_header = {
        'alg': current_app.config['FREJA_JWS_ALGORITHM'],
        'kid': current_app.config['FREJA_JWS_KEY_ID'],
    }
    jws = jose.sign(request_data,
                    jwk,
                    add_header=jws_header,
                    alg=current_app.config['FREJA_JWS_ALGORITHM'])
    return {'iaRequestData': jose.serialize_compact(jws)}
コード例 #12
0
ファイル: jose-request.py プロジェクト: vanrein/ods-rpc
		'surfnet.nl',
	],
}

#
# The request header reveals information about the signature
#
reqhdr = {
	'cty': 'application/json',
	'kid': '*****@*****.**',
	'timestamp': time.time (),
}

#
# Following demonstration code signs, maps to a dictionary and maps that to JSON
#
reqhdr ['kid'] = sharedkey ['kid']
tobesent = jose.sign (request, sharedkey, add_header = reqhdr)
tobesent = tobesent._asdict ()
tobesent = json.dumps (tobesent, indent=3)
#
# End of demonstration code
#

print '-----BEGIN TO BE SENT-----'
print 'Content-type: application/jws+json'
print
print tobesent
print '-----END TO BE SENT-----'

コード例 #13
0
ファイル: x509.py プロジェクト: bifurcation/pyjose
MIICBjCCAW+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAxMQswCQYDVQQGEwJVUzEN
MAsGA1UEAxMEYXNkZjETMBEGCSqGSIb3DQEJARMEYXNkZjAeFw0xMzA4MjIyMTMx
NTNaFw0xNDA4MjIyMTMxNTNaMDExCzAJBgNVBAYTAlVTMQ0wCwYDVQQDEwRhc2Rm
MRMwEQYJKoZIhvcNAQkBEwRhc2RmMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQCZdrbHbZ87wBILsrQvJLB50Eg77XGzmvUUsI0eB+7Q+a4qhin1LfOwm1NdHYzY
ZR/GSLPxJPl0Jni/sbCmA6Zf94Z/FHRJMBGPbcqCehF6GD1ECKOY9fGL37U9Ue7+
gbcwvm5nTmdkE9AlmCoZe8MJDJXDq3JeAqtaY9dvx4guawIDAQABoy4wLDAMBgNV
HRMEBTADAQH/MAsGA1UdDwQEAwIC9DAPBgNVHREECDAGgQRhc2RmMA0GCSqGSIb3
DQEBBQUAA4GBACNbRRnq5utziHBiUAh7z87Mgm9EzsNOz/tYRqbiHYqNpHiYAaCV
0puGCKeB+kU/kIqFI0nQ4aWjZDQmtgPj39oI2EuzL0c+J3ux9NhiE5YIg2Bkrf2z
f56W5ExLLyiBerztpkt430HoDmoK13wBr+nzEX8JIeD+KFvlcizUHEM0
"""

payload = "Shall I compare the to a summer's day?"

# Test sign / verify with jwk
jws1 = jose.sign({ "alg":"RS256", "jwk": jwk_pub }, [jwk_priv], payload )
ver1 = jose.verify(jws1, [])
print jws1
print
print ver1
print

# Test sign / verify with x5c
jws2 = jose.sign({ "alg":"RS256", "x5c": [cert] }, [jwk_priv], payload )
ver2 = jose.verify(jws1, [])
print jws2
print
print ver2
print
コード例 #14
0
    # key = b"""-----BEGIN PRIVATE KEY-----
    # MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgsegINAr5xcE48BiD
    # yfXjsfQmEk1ReGtD7bSuKsKx04CgCgYIKoZIzj0DAQehRANCAASauMCp36D8FOF1
    # 5OGI1+fe5oeRoCbY5yGQ2Jk0Gi9P92ksyvC8LK7JDqtzKfEf18UsScYc+NWffEtt
    # v413G73q
    # -----END PRIVATE KEY-----"""
    # k = {'k': 'password'}
    #
    # signed = jws.sign(data, k, algorithm='ES256')
    # print(signed)
    # data = jws.verify(signed, k, algorithms='ES256')
    # print(data)



    jwk = {'k': 'password'}

    jws = jose.sign(data, jwk, alg='HS256')
    # JWS(header='eyJhbGciOiAiSFMyNTYifQ',
    # payload='eyJpc3MiOiAiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsICJzdWIiOiA0MiwgImV4cCI6IDEzOTU2NzQ0Mjd9',
    # signature='WYApAiwiKd-eDClA1fg7XFrnfHzUTgrmdRQY4M19Vr8')

    # issue the compact serialized version to the clients. this is what will be
    # transported along with requests to target systems.

    jwt = jose.serialize_compact(jws)
    # 'eyJhbGciOiAiSFMyNTYifQ.eyJpc3MiOiAiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsICJzdWIiOiA0MiwgImV4cCI6IDEzOTU2NzQ0Mjd9.WYApAiwiKd-eDClA1fg7XFrnfHzUTgrmdRQY4M19Vr8'

    jose.verify(jose.deserialize_compact(jwt), jwk, 'HS256')
    # JWT(header={u'alg': u'HS256'}, claims={u'iss': u'http://www.example.com', u'sub': 42, u'exp': 1395674427})
コード例 #15
0
 def _sign_and_encrypt(self, claims, priv_jwk, server_jwk, alg='RS256'):
     jws = jose.sign(claims, priv_jwk, alg=alg)
     signed_claims = {'v1': jose.serialize_compact(jws)}
     jwe = jose.encrypt(signed_claims, server_jwk)
     return jwe
コード例 #16
0
ファイル: zipcrit.py プロジェクト: bifurcation/pyjose
print serialize_compact(jwe1)
print

print "Decrypted, decompressed JWE:"
print dec1
print

# Criticality test

payload = "Some day you may pass validation.  Today is not that day."
jws_header1 = {"alg": "HS256", "crit": ["alg"]}
jws_header2 = {"alg": "HS256", "true_rings": 1, "crit": ["true_rings"]}
keys = [{"kty": "oct", "k": "i-ueSNQgcr0q7auC8YUrYg"}]

# Test 1: Should fail on sign
try:
    jws1 = jose.sign(jws_header1, keys, payload)
    ver1 = jose.verify(jws1, keys)
except Exception as e:
    print e
print

# Test 2: Should fail on verify

try:
    jws2 = jose.sign(jws_header2, keys, payload)
    ver2 = jose.verify(jws2, keys)
except Exception as e:
    print e
print
コード例 #17
0
    print "Error: %s" % e
    exit()

# JWT sign - Sign token using the private key External
claims = {
    'from': 'mindthebyte',
    'exp': int(time()) + 3600,
    'secret': secret,
}
print "\t< claims to be signed: " + str(claims)
print "\t    |"
print "\t< Sing token signature (claims, private external key) >"
print "\t    |"
try:
    jwk = {'k': 'password'}
    jws = jose.sign(claims, jwk, alg='HS256')
    # JWS(header='eyJhbGciOiAiSFMyNTYifQ',
    # payload='eyJpc3MiOiAiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsICJzdWIiOiA0MiwgImV4cCI6IDEzOTU2NzQ0Mjd9',
    # signature='WYApAiwiKd-eDClA1fg7XFrnfHzUTgrmdRQY4M19Vr8')
    # issue the compact serialized version to the clients. this is what will be
    # transported along with requests to target systems.
    jwt = jose.serialize_compact(jws)
    # 'eyJhbGciOiAiSFMyNTYifQ.eyJpc3MiOiAiaHR0cDovL3d3dy5leGFtcGxlLmNvbSIsICJzdWIiOiA0MiwgImV4cCI6IDEzOTU2NzQ0Mjd9.WYApAiwiKd-eDClA1fg7XFrnfHzUTgrmdRQY4M19Vr8'
    print "\t   OK"
    print "\t    |"
except:
    print "\tError signing token! "
    e = sys.exc_info()[0]
    print "Error: %s" % e
    exit()
コード例 #18
0
MIICBjCCAW+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAxMQswCQYDVQQGEwJVUzEN
MAsGA1UEAxMEYXNkZjETMBEGCSqGSIb3DQEJARMEYXNkZjAeFw0xMzA4MjIyMTMx
NTNaFw0xNDA4MjIyMTMxNTNaMDExCzAJBgNVBAYTAlVTMQ0wCwYDVQQDEwRhc2Rm
MRMwEQYJKoZIhvcNAQkBEwRhc2RmMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQCZdrbHbZ87wBILsrQvJLB50Eg77XGzmvUUsI0eB+7Q+a4qhin1LfOwm1NdHYzY
ZR/GSLPxJPl0Jni/sbCmA6Zf94Z/FHRJMBGPbcqCehF6GD1ECKOY9fGL37U9Ue7+
gbcwvm5nTmdkE9AlmCoZe8MJDJXDq3JeAqtaY9dvx4guawIDAQABoy4wLDAMBgNV
HRMEBTADAQH/MAsGA1UdDwQEAwIC9DAPBgNVHREECDAGgQRhc2RmMA0GCSqGSIb3
DQEBBQUAA4GBACNbRRnq5utziHBiUAh7z87Mgm9EzsNOz/tYRqbiHYqNpHiYAaCV
0puGCKeB+kU/kIqFI0nQ4aWjZDQmtgPj39oI2EuzL0c+J3ux9NhiE5YIg2Bkrf2z
f56W5ExLLyiBerztpkt430HoDmoK13wBr+nzEX8JIeD+KFvlcizUHEM0
"""

payload = "Shall I compare the to a summer's day?"

# Test sign / verify with jwk
jws1 = jose.sign({"alg": "RS256", "jwk": jwk_pub}, [jwk_priv], payload)
ver1 = jose.verify(jws1, [])
print(jws1)
print()
print(ver1)
print()

# Test sign / verify with x5c
jws2 = jose.sign({"alg": "RS256", "x5c": [cert]}, [jwk_priv], payload)
ver2 = jose.verify(jws1, [])
print(jws2)
print()
print(ver2)
print()
コード例 #19
0
 def _sign_and_encrypt(self, claims, priv_jwk, server_jwk, alg = 'RS256'):
     jws = jose.sign(claims, priv_jwk, alg=alg)
     signed_claims = {'v1': jose.serialize_compact(jws)}
     jwe = jose.encrypt(signed_claims, server_jwk)
     return jwe
コード例 #20
0
ファイル: quickstart.py プロジェクト: bifurcation/pyjose
# Encrypt into the JSON serialization
jwe1 = jose.encrypt(jwe_header, keys, plaintext)
dec1 = jose.decrypt(jwe1, keys)
print jwe1
print dec1
print

# Encrypt into the compact serialization
jwe2 = serialize_compact( \
        jose.encrypt(jwe_header, keys, plaintext, protect="*"))
dec2 = jose.decrypt(jwe2, keys)
print jwe2
print dec2
print

# Sign into the JSON serialization
jws1 = jose.sign(jws_header, keys, plaintext)
ver1 = jose.verify(jws1, keys)
print jws1
print ver1
print

# Sign into the compact serialization
jws2 = serialize_compact( \
        jose.sign(jws_header, keys, plaintext, protect="*"))
ver2 = jose.verify(jws2, keys)
print jws2
print ver2
print
コード例 #21
0
ファイル: zipcrit.py プロジェクト: bifurcation/pyjose
print

print "Decrypted, decompressed JWE:"
print dec1
print


# Criticality test

payload = "Some day you may pass validation.  Today is not that day."
jws_header1 = { "alg":"HS256", "crit": ["alg"] }
jws_header2 = { "alg":"HS256", "true_rings": 1, "crit": ["true_rings"] }
keys = [{ "kty":"oct", "k":"i-ueSNQgcr0q7auC8YUrYg" }]

# Test 1: Should fail on sign
try:
    jws1 = jose.sign(jws_header1, keys, payload)
    ver1 = jose.verify(jws1, keys)
except Exception as e:
    print e
print

# Test 2: Should fail on verify

try:
    jws2 = jose.sign(jws_header2, keys, payload)
    ver2 = jose.verify(jws2, keys)
except Exception as e:
    print e
print