jwcrypto-0.2.1/0000775000175000017500000000000012575550334016022 5ustar puiterwijkpuiterwijk00000000000000jwcrypto-0.2.1/jwcrypto.egg-info/0000775000175000017500000000000012575550334021375 5ustar puiterwijkpuiterwijk00000000000000jwcrypto-0.2.1/jwcrypto.egg-info/dependency_links.txt0000664000175000017500000000000112575550333025442 0ustar puiterwijkpuiterwijk00000000000000 jwcrypto-0.2.1/jwcrypto.egg-info/top_level.txt0000664000175000017500000000001112575550333024116 0ustar puiterwijkpuiterwijk00000000000000jwcrypto jwcrypto-0.2.1/jwcrypto.egg-info/PKG-INFO0000664000175000017500000000100212575550333022462 0ustar puiterwijkpuiterwijk00000000000000Metadata-Version: 1.1 Name: jwcrypto Version: 0.2.1 Summary: Implementation of JOSE Web standards Home-page: https://github.com/simo5/jwcrypto Author: JWCrypto Project Contributors Author-email: simo@redhat.com License: LGPLv3+ Description: UNKNOWN Platform: UNKNOWN Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Intended Audience :: Developers Classifier: Topic :: Security Classifier: Topic :: Software Development :: Libraries :: Python Modules jwcrypto-0.2.1/jwcrypto.egg-info/SOURCES.txt0000664000175000017500000000047312575550333023264 0ustar puiterwijkpuiterwijk00000000000000LICENSE MANIFEST.in README.md setup.py jwcrypto/__init__.py jwcrypto/common.py jwcrypto/jwe.py jwcrypto/jwk.py jwcrypto/jws.py jwcrypto/jwt.py jwcrypto/tests-cookbook.py jwcrypto/tests.py jwcrypto.egg-info/PKG-INFO jwcrypto.egg-info/SOURCES.txt jwcrypto.egg-info/dependency_links.txt jwcrypto.egg-info/top_level.txtjwcrypto-0.2.1/setup.cfg0000664000175000017500000000007312575550334017643 0ustar puiterwijkpuiterwijk00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 jwcrypto-0.2.1/README.md0000664000175000017500000000061612540045220017265 0ustar puiterwijkpuiterwijk00000000000000JWCrypto ======== An implementation of the JOSE Working Group documents: RFC 7515 - JSON Web Signature (JWS) RFC 7516 - JSON Web Encryption (JWE) RFC 7517 - JSON Web Key (JWK) RFC 7518 - JSON Web Algorithms (JWA) RFC 7519 - JSON Web Token (JWT) RFC 7520 - Examples of Protecting Content Using JSON Object Signing and Encryption (JOSE) Documentation ============= http://jwcrypto.readthedocs.org jwcrypto-0.2.1/jwcrypto/0000775000175000017500000000000012575550334017703 5ustar puiterwijkpuiterwijk00000000000000jwcrypto-0.2.1/jwcrypto/tests-cookbook.py0000664000175000017500000012607112540045220023213 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from jwcrypto.common import base64url_decode, base64url_encode from jwcrypto.common import json_decode, json_encode from jwcrypto import jwk from jwcrypto import jws from jwcrypto import jwe import unittest # Based on: RFC 7520 EC_Public_Key_3_1 = { "kty": "EC", "kid": "bilbo.baggins@hobbiton.example", "use": "sig", "crv": "P-521", "x": "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9" "A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt", "y": "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVy" "SsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1"} EC_Private_Key_3_2 = { "kty": "EC", "kid": "bilbo.baggins@hobbiton.example", "use": "sig", "crv": "P-521", "x": "AHKZLLOsCOzz5cY97ewNUajB957y-C-U88c3v13nmGZx6sYl_oJXu9" "A5RkTKqjqvjyekWF-7ytDyRXYgCF5cj0Kt", "y": "AdymlHvOiLxXkEhayXQnNCvDX4h9htZaCJN34kfmC6pV5OhQHiraVy" "SsUdaQkAgDPrwQrJmbnX9cwlGfP-HqHZR1", "d": "AAhRON2r9cqXX1hg-RoI6R1tX5p2rUAYdmpHZoC1XNM56KtscrX6zb" "KipQrCW9CGZH3T4ubpnoTKLDYJ_fF3_rJt"} RSA_Public_Key_3_3 = { "kty": "RSA", "kid": "bilbo.baggins@hobbiton.example", "use":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-4d9b-471b-bfd6-eef314bc7037", "use": "sig", "alg": "HS256", "k": "hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg"} Symmetric_Key_Enc_3_6 = { "kty": "oct", "kid": "1e571774-2e08-40da-8308-e8d68773842d", "use": "enc", "alg": "A256GCM", "k": "AAPapAv4LbFbiVawEjagUBluYqN5rhna-8nuldDvOx8"} Payload_plaintext_b64_4 = \ "SXTigJlzIGEgZGFuZ2Vyb3VzIGJ1c2luZXNzLCBGcm9kbywgZ29pbmcgb3V0IH" + \ "lvdXIgZG9vci4gWW91IHN0ZXAgb250byB0aGUgcm9hZCwgYW5kIGlmIHlvdSBk" + \ "b24ndCBrZWVwIHlvdXIgZmVldCwgdGhlcmXigJlzIG5vIGtub3dpbmcgd2hlcm" + \ "UgeW91IG1pZ2h0IGJlIHN3ZXB0IG9mZiB0by4" # 4.1 JWS_Protected_Header_4_1_2 = \ "eyJhbGciOiJSUzI1NiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZX" + \ "hhbXBsZSJ9" JWS_Signature_4_1_2 = \ "MRjdkly7_-oTPTS3AXP41iQIGKa80A0ZmTuV5MEaHoxnW2e5CZ5NlKtainoFmK" + \ "ZopdHM1O2U4mwzJdQx996ivp83xuglII7PNDi84wnB-BDkoBwA78185hX-Es4J" + \ "IwmDLJK3lfWRa-XtL0RnltuYv746iYTh_qHRD68BNt1uSNCrUCTJDt5aAE6x8w" + \ "W1Kt9eRo4QPocSadnHXFxnt8Is9UzpERV0ePPQdLuW3IS_de3xyIrDaLGdjluP" + \ "xUAhb6L2aXic1U12podGU0KLUQSE_oI-ZnmKJ3F4uOZDnd6QZWJushZ41Axf_f" + \ "cIe8u9ipH84ogoree7vjbU5y18kDquDg" JWS_compact_4_1_3 = \ "%s.%s.%s" % (JWS_Protected_Header_4_1_2, Payload_plaintext_b64_4, JWS_Signature_4_1_2) JWS_general_4_1_3 = { "payload": Payload_plaintext_b64_4, "signatures": [{ "protected": JWS_Protected_Header_4_1_2, "signature": JWS_Signature_4_1_2}]} JWS_flattened_4_1_3 = { "payload": Payload_plaintext_b64_4, "protected": JWS_Protected_Header_4_1_2, "signature": JWS_Signature_4_1_2} # 4.2 JWS_Protected_Header_4_2_2 = \ "eyJhbGciOiJQUzM4NCIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZX" + \ "hhbXBsZSJ9" JWS_Signature_4_2_2 = \ "cu22eBqkYDKgIlTpzDXGvaFfz6WGoz7fUDcfT0kkOy42miAh2qyBzk1xEsnk2I" + \ "pN6-tPid6VrklHkqsGqDqHCdP6O8TTB5dDDItllVo6_1OLPpcbUrhiUSMxbbXU" + \ "vdvWXzg-UD8biiReQFlfz28zGWVsdiNAUf8ZnyPEgVFn442ZdNqiVJRmBqrYRX" + \ "e8P_ijQ7p8Vdz0TTrxUeT3lm8d9shnr2lfJT8ImUjvAA2Xez2Mlp8cBE5awDzT" + \ "0qI0n6uiP1aCN_2_jLAeQTlqRHtfa64QQSUmFAAjVKPbByi7xho0uTOcbH510a" + \ "6GYmJUAfmWjwZ6oD4ifKo8DYM-X72Eaw" JWS_compact_4_2_3 = \ "%s.%s.%s" % (JWS_Protected_Header_4_2_2, Payload_plaintext_b64_4, JWS_Signature_4_2_2) JWS_general_4_2_3 = { "payload": Payload_plaintext_b64_4, "signatures": [{ "protected": JWS_Protected_Header_4_2_2, "signature": JWS_Signature_4_2_2}]} JWS_flattened_4_2_3 = { "payload": Payload_plaintext_b64_4, "protected": JWS_Protected_Header_4_2_2, "signature": JWS_Signature_4_2_2} # 4.3 JWS_Protected_Header_4_3_2 = \ "eyJhbGciOiJFUzUxMiIsImtpZCI6ImJpbGJvLmJhZ2dpbnNAaG9iYml0b24uZX" + \ "hhbXBsZSJ9" JWS_Signature_4_3_2 = \ "AE_R_YZCChjn4791jSQCrdPZCNYqHXCTZH0-JZGYNlaAjP2kqaluUIIUnC9qvb" + \ "u9Plon7KRTzoNEuT4Va2cmL1eJAQy3mtPBu_u_sDDyYjnAMDxXPn7XrT0lw-kv" + \ "AD890jl8e2puQens_IEKBpHABlsbEPX6sFY8OcGDqoRuBomu9xQ2" JWS_compact_4_3_3 = \ "%s.%s.%s" % (JWS_Protected_Header_4_3_2, Payload_plaintext_b64_4, JWS_Signature_4_3_2) JWS_general_4_3_3 = { "payload": Payload_plaintext_b64_4, "signatures": [{ "protected": JWS_Protected_Header_4_3_2, "signature": JWS_Signature_4_3_2}]} JWS_flattened_4_3_3 = { "payload": Payload_plaintext_b64_4, "protected": JWS_Protected_Header_4_3_2, "signature": JWS_Signature_4_3_2} # 4.4 JWS_Protected_Header_4_4_2 = \ "eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LW" + \ "VlZjMxNGJjNzAzNyJ9" JWS_Signature_4_4_2 = "s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0" JWS_compact_4_4_3 = \ "%s.%s.%s" % (JWS_Protected_Header_4_4_2, Payload_plaintext_b64_4, JWS_Signature_4_4_2) JWS_general_4_4_3 = { "payload": Payload_plaintext_b64_4, "signatures": [{ "protected": JWS_Protected_Header_4_4_2, "signature": JWS_Signature_4_4_2}]} JWS_flattened_4_4_3 = { "payload": Payload_plaintext_b64_4, "protected": JWS_Protected_Header_4_4_2, "signature": JWS_Signature_4_4_2} # 4.5 - TBD, see Issue #4 # 4.6 JWS_Protected_Header_4_6_2 = "eyJhbGciOiJIUzI1NiJ9" JWS_Unprotected_Header_4_6_2 = {"kid": "018c0ae5-4d9b-471b-bfd6-eef314bc7037"} JWS_Signature_4_6_2 = "bWUSVaxorn7bEF1djytBd0kHv70Ly5pvbomzMWSOr20" JWS_general_4_6_3 = { "payload": Payload_plaintext_b64_4, "signatures": [{ "protected": JWS_Protected_Header_4_6_2, "header": JWS_Unprotected_Header_4_6_2, "signature": JWS_Signature_4_6_2}]} JWS_flattened_4_6_3 = { "payload": Payload_plaintext_b64_4, "protected": JWS_Protected_Header_4_6_2, "header": JWS_Unprotected_Header_4_6_2, "signature": JWS_Signature_4_6_2} # 4.7 JWS_Unprotected_Header_4_7_2 = {"alg": "HS256", "kid": "018c0ae5-4d9b-471b-bfd6-eef314bc7037"} JWS_Signature_4_7_2 = "xuLifqLGiblpv9zBpuZczWhNj1gARaLV3UxvxhJxZuk" JWS_general_4_7_3 = { "payload": Payload_plaintext_b64_4, "signatures": [{ "header": JWS_Unprotected_Header_4_7_2, "signature": JWS_Signature_4_7_2}]} JWS_flattened_4_7_3 = { "payload": Payload_plaintext_b64_4, "header": JWS_Unprotected_Header_4_7_2, "signature": JWS_Signature_4_7_2} # 4.8 JWS_Protected_Header_4_8_2 = "eyJhbGciOiJSUzI1NiJ9" JWS_Unprotected_Header_4_8_2 = {"kid": "bilbo.baggins@hobbiton.example"} JWS_Signature_4_8_2 = \ "MIsjqtVlOpa71KE-Mss8_Nq2YH4FGhiocsqrgi5NvyG53uoimic1tcMdSg-qpt" + \ "rzZc7CG6Svw2Y13TDIqHzTUrL_lR2ZFcryNFiHkSw129EghGpwkpxaTn_THJTC" + \ "glNbADko1MZBCdwzJxwqZc-1RlpO2HibUYyXSwO97BSe0_evZKdjvvKSgsIqjy" + \ "tKSeAMbhMBdMma622_BG5t4sdbuCHtFjp9iJmkio47AIwqkZV1aIZsv33uPUqB" + \ "BCXbYoQJwt7mxPftHmNlGoOSMxR_3thmXTCm4US-xiNOyhbm8afKK64jU6_TPt" + \ "QHiJeQJxz9G3Tx-083B745_AfYOnlC9w" JWS_Unprotected_Header_4_8_3 = {"alg": "ES512", "kid": "bilbo.baggins@hobbiton.example"} JWS_Signature_4_8_3 = \ "ARcVLnaJJaUWG8fG-8t5BREVAuTY8n8YHjwDO1muhcdCoFZFFjfISu0Cdkn9Yb" + \ "dlmi54ho0x924DUz8sK7ZXkhc7AFM8ObLfTvNCrqcI3Jkl2U5IX3utNhODH6v7" + \ "xgy1Qahsn0fyb4zSAkje8bAWz4vIfj5pCMYxxm4fgV3q7ZYhm5eD" JWS_Protected_Header_4_8_4 = \ "eyJhbGciOiJIUzI1NiIsImtpZCI6IjAxOGMwYWU1LTRkOWItNDcxYi1iZmQ2LW" + \ "VlZjMxNGJjNzAzNyJ9" JWS_Signature_4_8_4 = "s0h6KThzkfBBBkLspW1h84VsJZFTsPPqMDA7g1Md7p0" JWS_general_4_8_5 = { "payload": Payload_plaintext_b64_4, "signatures": [ {"protected": JWS_Protected_Header_4_8_2, "header": JWS_Unprotected_Header_4_8_2, "signature": JWS_Signature_4_8_2}, {"header": JWS_Unprotected_Header_4_8_3, "signature": JWS_Signature_4_8_3}, {"protected": JWS_Protected_Header_4_8_4, "signature": JWS_Signature_4_8_4}]} class Cookbook08JWSTests(unittest.TestCase): def test_4_1_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) protected = \ base64url_decode(JWS_Protected_Header_4_1_2).decode('utf-8') pub_key = jwk.JWK(**RSA_Public_Key_3_3) pri_key = jwk.JWK(**RSA_Private_Key_3_4) S = jws.JWS(payload=plaintext) S.add_signature(pri_key, None, protected) self.assertEqual(JWS_compact_4_1_3, S.serialize(compact=True)) S.deserialize(json_encode(JWS_general_4_1_3), pub_key) S.deserialize(json_encode(JWS_flattened_4_1_3), pub_key) def test_4_2_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) protected = \ base64url_decode(JWS_Protected_Header_4_2_2).decode('utf-8') pub_key = jwk.JWK(**RSA_Public_Key_3_3) pri_key = jwk.JWK(**RSA_Private_Key_3_4) S = jws.JWS(payload=plaintext) S.add_signature(pri_key, None, protected) # Can't compare signature with reference because RSASSA-PSS uses # random nonces every time a signature is generated. sig = S.serialize() S.deserialize(sig, pub_key) # Just deserialize each example form S.deserialize(JWS_compact_4_2_3, pub_key) S.deserialize(json_encode(JWS_general_4_2_3), pub_key) S.deserialize(json_encode(JWS_flattened_4_2_3), pub_key) def test_4_3_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) protected = \ base64url_decode(JWS_Protected_Header_4_3_2).decode('utf-8') pub_key = jwk.JWK(**EC_Public_Key_3_1) pri_key = jwk.JWK(**EC_Private_Key_3_2) S = jws.JWS(payload=plaintext) S.add_signature(pri_key, None, protected) # Can't compare signature with reference because ECDSA uses # random nonces every time a signature is generated. sig = S.serialize() S.deserialize(sig, pub_key) # Just deserialize each example form S.deserialize(JWS_compact_4_3_3, pub_key) S.deserialize(json_encode(JWS_general_4_3_3), pub_key) S.deserialize(json_encode(JWS_flattened_4_3_3), pub_key) def test_4_4_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) protected = \ base64url_decode(JWS_Protected_Header_4_4_2).decode('utf-8') key = jwk.JWK(**Symmetric_Key_MAC_3_5) S = jws.JWS(payload=plaintext) S.add_signature(key, None, protected) sig = S.serialize(compact=True) S.deserialize(sig, key) self.assertEqual(sig, JWS_compact_4_4_3) # Just deserialize each example form S.deserialize(JWS_compact_4_4_3, key) S.deserialize(json_encode(JWS_general_4_4_3), key) S.deserialize(json_encode(JWS_flattened_4_4_3), key) def test_4_6_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) protected = \ base64url_decode(JWS_Protected_Header_4_6_2).decode('utf-8') header = json_encode(JWS_Unprotected_Header_4_6_2) key = jwk.JWK(**Symmetric_Key_MAC_3_5) S = jws.JWS(payload=plaintext) S.add_signature(key, None, protected, header) sig = S.serialize() S.deserialize(sig, key) self.assertEqual(json_decode(sig), JWS_flattened_4_6_3) # Just deserialize each example form S.deserialize(json_encode(JWS_general_4_6_3), key) S.deserialize(json_encode(JWS_flattened_4_6_3), key) def test_4_7_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) header = json_encode(JWS_Unprotected_Header_4_7_2) key = jwk.JWK(**Symmetric_Key_MAC_3_5) S = jws.JWS(payload=plaintext) S.add_signature(key, None, None, header) sig = S.serialize() S.deserialize(sig, key) self.assertEqual(json_decode(sig), JWS_flattened_4_7_3) # Just deserialize each example form S.deserialize(json_encode(JWS_general_4_7_3), key) S.deserialize(json_encode(JWS_flattened_4_7_3), key) def test_4_8_signing(self): plaintext = base64url_decode(Payload_plaintext_b64_4) S = jws.JWS(payload=plaintext) # 4_8_2 protected = \ base64url_decode(JWS_Protected_Header_4_8_2).decode('utf-8') header = json_encode(JWS_Unprotected_Header_4_8_2) pri_key = jwk.JWK(**RSA_Private_Key_3_4) S.add_signature(pri_key, None, protected, header) # 4_8_3 header = json_encode(JWS_Unprotected_Header_4_8_3) pri_key = jwk.JWK(**EC_Private_Key_3_2) S.add_signature(pri_key, None, None, header) # 4_8_4 protected = \ base64url_decode(JWS_Protected_Header_4_8_4).decode('utf-8') sym_key = jwk.JWK(**Symmetric_Key_MAC_3_5) S.add_signature(sym_key, None, protected) sig = S.serialize() # Can't compare signature with reference because ECDSA uses # random nonces every time a signature is generated. rsa_key = jwk.JWK(**RSA_Public_Key_3_3) ec_key = jwk.JWK(**EC_Public_Key_3_1) S.deserialize(sig, rsa_key) S.deserialize(sig, ec_key) S.deserialize(sig, sym_key) # Just deserialize each example form S.deserialize(json_encode(JWS_general_4_8_5), rsa_key) S.deserialize(json_encode(JWS_general_4_8_5), ec_key) S.deserialize(json_encode(JWS_general_4_8_5), sym_key) # 5.0 Payload_plaintext_5 = \ b"You can trust us to stick with you through thick and " + \ b"thin\xe2\x80\x93to the bitter end. And you can trust us to " + \ b"keep any secret of yours\xe2\x80\x93closer than you keep it " + \ b"yourself. But you cannot trust us to let you face trouble " + \ b"alone, and go off without a word. We are your friends, Frodo." # 5.1 RSA_key_5_1_1 = { "kty": "RSA", "kid": "frodo.baggins@hobbiton.example", "use": "enc", "n": "maxhbsmBtdQ3CNrKvprUE6n9lYcregDMLYNeTAWcLj8NnPU9XIYegT" "HVHQjxKDSHP2l-F5jS7sppG1wgdAqZyhnWvXhYNvcM7RfgKxqNx_xAHx" "6f3yy7s-M9PSNCwPC2lh6UAkR4I00EhV9lrypM9Pi4lBUop9t5fS9W5U" "NwaAllhrd-osQGPjIeI1deHTwx-ZTHu3C60P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kpEEnlDmZvDu_k8O" + \ "WzJv7eZVEqiWKdyVzFhPpiyQU28GLOpRc2VbVbK4dQKPdNTjPPEmRqcaGeTWZV" + \ "yeSUvf5k59yJZxRuSvWFf6KrNtmRdZ8R4mDOjHSrM_s8uwIFcqt4r5GX8TKaI0" + \ "zT5CbL5Qlw3sRc7u_hg0yKVOiRytEAEs3vZkcfLkP6nbXdC_PkMdNS-ohP78T2" + \ "O6_7uInMGhFeX4ctHG7VelHGiT93JfWDEQi5_V9UN1rhXNrYu-0fVMkZAKX3VW" + \ "i7lzA6BP430m" JWE_Authentication_Tag_5_1_4 = "kvKuFBXHe5mQr4lqgobAUg" JWE_compact_5_1_5 = \ "%s.%s.%s.%s.%s" % (JWE_Protected_Header_5_1_4, JWE_Encrypted_Key_5_1_3, JWE_IV_5_1_2, JWE_Ciphertext_5_1_4, JWE_Authentication_Tag_5_1_4) JWE_general_5_1_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_1_3}], "protected": JWE_Protected_Header_5_1_4, "iv": JWE_IV_5_1_2, "ciphertext": JWE_Ciphertext_5_1_4, "tag": JWE_Authentication_Tag_5_1_4} JWE_flattened_5_1_5 = { "protected": JWE_Protected_Header_5_1_4, "encrypted_key": JWE_Encrypted_Key_5_1_3, "iv": JWE_IV_5_1_2, "ciphertext": JWE_Ciphertext_5_1_4, "tag": JWE_Authentication_Tag_5_1_4} # 5.2 RSA_key_5_2_1 = { "kty": "RSA", "kid": "samwise.gamgee@hobbiton.example", "use": "enc", "n": "wbdxI55VaanZXPY29Lg5hdmv2XhvqAhoxUkanfzf2-5zVUxa6prHRr" "I4pP1AhoqJRlZfYtWWd5mmHRG2pAHIlh0ySJ9wi0BioZBl1XP2e-C-Fy" "XJGcTy0HdKQWlrfhTm42EW7Vv04r4gfao6uxjLGwfpGrZLarohiWCPnk" "Nrg71S2CuNZSQBIPGjXfkmIy2tl_VWgGnL22GplyXj5YlBLdxXp3XeSt" "sqo571utNfoUTU8E4qdzJ3U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imbM8zVOw" JWE_Authentication_Tag_5_2_4 = "UCGiqJxhBI3IFVdPalHHvA" JWE_compact_5_2_5 = \ "%s.%s.%s.%s.%s" % (JWE_Protected_Header_5_2_4, JWE_Encrypted_Key_5_2_3, JWE_IV_5_2_2, JWE_Ciphertext_5_2_4, JWE_Authentication_Tag_5_2_4) JWE_general_5_2_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_2_3}], "protected": JWE_Protected_Header_5_2_4, "iv": JWE_IV_5_2_2, "ciphertext": JWE_Ciphertext_5_2_4, "tag": JWE_Authentication_Tag_5_2_4} JWE_flattened_5_2_5 = { "protected": JWE_Protected_Header_5_2_4, "encrypted_key": JWE_Encrypted_Key_5_2_3, "iv": JWE_IV_5_2_2, "ciphertext": JWE_Ciphertext_5_2_4, "tag": JWE_Authentication_Tag_5_2_4} # 5.3 - PBES2-* not implemented yet # Payload_plaintext_5_3_1 = json_encode({ # "keys": [ # {"kty": "oct", # "kid": "77c7e2b8-6e13-45cf-8672-617b5b45243a", # "use": "enc", # "alg": "A128GCM", # "k": "XctOhJAkA-pD9Lh7ZgW_2A"}, # {"kty": "oct", # "kid": "81b20965-8332-43d9-a468-82160ad91ac8", # "use": "enc", # "alg": "A128KW", # "k": "GZy6sIZ6wl9NJOKB-jnmVQ"}, # {"kty": "oct", # "kid": "18ec08e1-bfa9-4d95-b205-2b4dd1d4321d", # "use": "enc", # "alg": "A256GCMKW", # "k": "qC57l_uxcm7Nm3K-ct4GFjx8tM1U8CZ0NLBvdQstiS8"}]}) # # Password_5_3_1 = "entrap_o\xe2\x80\x93peter_long\xe2\x80\x93credit_tun" # # JWE_IV_5_3_2 = "VBiCzVHNoLiR3F4V82uoTQ" # # JWE_Encrypted_Key_5_3_3 = \ # "d3qNhUWfqheyPp4H8sjOWsDYajoej4c5Je6rlUtFPWdgtURtmeDV1g" # # JWE_Protected_Header_5_3_4 = \ # "eyJhbGciOiJQQkVTMi1IUzUxMitBMjU2S1ciLCJwMnMiOiI4UTFTemluYXNSM3" + \ # "hjaFl6NlpaY0hBIiwicDJjIjo4MTkyLCJjdHkiOiJqd2stc2V0K2pzb24iLCJl" + \ # "bmMiOiJBMTI4Q0JDLUhTMjU2In0" # # JWE_Ciphertext_5_3_4 = \ # "23i-Tb1AV4n0WKVSSgcQrdg6GRqsUKxjruHXYsTHAJLZ2nsnGIX86vMXqIi6IR" + \ # "sfywCRFzLxEcZBRnTvG3nhzPk0GDD7FMyXhUHpDjEYCNA_XOmzg8yZR9oyjo6l" + \ # "TF6si4q9FZ2EhzgFQCLO_6h5EVg3vR75_hkBsnuoqoM3dwejXBtIodN84PeqMb" + \ # "6asmas_dpSsz7H10fC5ni9xIz424givB1YLldF6exVmL93R3fOoOJbmk2GBQZL" + \ # "_SEGllv2cQsBgeprARsaQ7Bq99tT80coH8ItBjgV08AtzXFFsx9qKvC982KLKd" + \ # "PQMTlVJKkqtV4Ru5LEVpBZXBnZrtViSOgyg6AiuwaS-rCrcD_ePOGSuxvgtrok" + \ # "AKYPqmXUeRdjFJwafkYEkiuDCV9vWGAi1DH2xTafhJwcmywIyzi4BqRpmdn_N-" + \ # "zl5tuJYyuvKhjKv6ihbsV_k1hJGPGAxJ6wUpmwC4PTQ2izEm0TuSE8oMKdTw8V" + \ # "3kobXZ77ulMwDs4p" # # JWE_Authentication_Tag_5_3_4 = "0HlwodAhOCILG5SQ2LQ9dg" # # JWE_compact_5_3_5 = \ # "%s.%s.%s.%s.%s" % (JWE_Protected_Header_5_3_4, # JWE_Encrypted_Key_5_3_3, # JWE_IV_5_3_2, # JWE_Ciphertext_5_3_4, # JWE_Authentication_Tag_5_3_4) # # JWE_general_5_3_5 = { # "recipients": [{ # "encrypted_key": JWE_Encrypted_Key_5_3_3}], # "protected": JWE_Protected_Header_5_3_4, # "iv": JWE_IV_5_3_2, # "ciphertext": JWE_Ciphertext_5_3_4, # "tag": JWE_Authentication_Tag_5_3_4} # # JWE_flattened_5_3_5 = { # "protected": JWE_Protected_Header_5_3_4, # "encrypted_key": JWE_Encrypted_Key_5_3_3, # "iv": JWE_IV_5_3_2, # "ciphertext": JWE_Ciphertext_5_3_4, # "tag": JWE_Authentication_Tag_5_3_4} # 5.4 - ECDH-ES key agreement not implemented yet # 5.5 - ECDH-ES key agreement not implemented yet # 5.6 AES_key_5_6_1 = { "kty": "oct", "kid": "77c7e2b8-6e13-45cf-8672-617b5b45243a", "use": "enc", "alg": "A128GCM", "k": "XctOhJAkA-pD9Lh7ZgW_2A"} JWE_IV_5_6_2 = "refa467QzzKx6QAB" JWE_Protected_Header_5_6_3 = \ "eyJhbGciOiJkaXIiLCJraWQiOiI3N2M3ZTJiOC02ZTEzLTQ1Y2YtODY3Mi02MT" + \ "diNWI0NTI0M2EiLCJlbmMiOiJBMTI4R0NNIn0" JWE_Ciphertext_5_6_3 = \ "JW_i_f52hww_ELQPGaYyeAB6HYGcR559l9TYnSovc23XJoBcW29rHP8yZOZG7Y" + \ "hLpT1bjFuvZPjQS-m0IFtVcXkZXdH_lr_FrdYt9HRUYkshtrMmIUAyGmUnd9zM" + \ "DB2n0cRDIHAzFVeJUDxkUwVAE7_YGRPdcqMyiBoCO-FBdE-Nceb4h3-FtBP-c_" + \ "BIwCPTjb9o0SbdcdREEMJMyZBH8ySWMVi1gPD9yxi-aQpGbSv_F9N4IZAxscj5" + \ "g-NJsUPbjk29-s7LJAGb15wEBtXphVCgyy53CoIKLHHeJHXex45Uz9aKZSRSIn" + \ "ZI-wjsY0yu3cT4_aQ3i1o-tiE-F8Ios61EKgyIQ4CWao8PFMj8TTnp" JWE_Authentication_Tag_5_6_3 = "vbb32Xvllea2OtmHAdccRQ" JWE_compact_5_6_4 = \ "%s..%s.%s.%s" % (JWE_Protected_Header_5_6_3, JWE_IV_5_6_2, JWE_Ciphertext_5_6_3, JWE_Authentication_Tag_5_6_3) JWE_general_5_6_4 = { "protected": JWE_Protected_Header_5_6_3, "iv": JWE_IV_5_6_2, "ciphertext": JWE_Ciphertext_5_6_3, "tag": JWE_Authentication_Tag_5_6_3} # 5.7 - A256GCMKW not implemented yet # 5.8 AES_key_5_8_1 = { "kty": "oct", "kid": "81b20965-8332-43d9-a468-82160ad91ac8", "use": "enc", "alg": "A128KW", "k": "GZy6sIZ6wl9NJOKB-jnmVQ"} JWE_IV_5_8_2 = "Qx0pmsDa8KnJc9Jo" JWE_Encrypted_Key_5_8_3 = "CBI6oDw8MydIx1IBntf_lQcw2MmJKIQx" JWE_Protected_Header_5_8_4 = \ "eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC" + \ "04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0" JWE_Ciphertext_5_8_4 = \ "AwliP-KmWgsZ37BvzCefNen6VTbRK3QMA4TkvRkH0tP1bTdhtFJgJxeVmJkLD6" + \ "1A1hnWGetdg11c9ADsnWgL56NyxwSYjU1ZEHcGkd3EkU0vjHi9gTlb90qSYFfe" + \ "F0LwkcTtjbYKCsiNJQkcIp1yeM03OmuiYSoYJVSpf7ej6zaYcMv3WwdxDFl8RE" + \ "wOhNImk2Xld2JXq6BR53TSFkyT7PwVLuq-1GwtGHlQeg7gDT6xW0JqHDPn_H-p" + \ "uQsmthc9Zg0ojmJfqqFvETUxLAF-KjcBTS5dNy6egwkYtOt8EIHK-oEsKYtZRa" + \ "a8Z7MOZ7UGxGIMvEmxrGCPeJa14slv2-gaqK0kEThkaSqdYw0FkQZF" JWE_Authentication_Tag_5_8_4 = "ER7MWJZ1FBI_NKvn7Zb1Lw" JWE_compact_5_8_5 = \ "%s.%s.%s.%s.%s" % (JWE_Protected_Header_5_8_4, JWE_Encrypted_Key_5_8_3, JWE_IV_5_8_2, JWE_Ciphertext_5_8_4, JWE_Authentication_Tag_5_8_4) JWE_general_5_8_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_8_3}], "protected": JWE_Protected_Header_5_8_4, "iv": JWE_IV_5_8_2, "ciphertext": JWE_Ciphertext_5_8_4, "tag": JWE_Authentication_Tag_5_8_4} JWE_flattened_5_8_5 = { "protected": JWE_Protected_Header_5_8_4, "encrypted_key": JWE_Encrypted_Key_5_8_3, "iv": JWE_IV_5_8_2, "ciphertext": JWE_Ciphertext_5_8_4, "tag": JWE_Authentication_Tag_5_8_4} # 5.9 JWE_IV_5_9_2 = "p9pUq6XHY0jfEZIl" JWE_Encrypted_Key_5_9_3 = "5vUT2WOtQxKWcekM_IzVQwkGgzlFDwPi" JWE_Protected_Header_5_9_4 = \ "eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC" + \ "04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIiwiemlwIjoiREVGIn0" JWE_Ciphertext_5_9_4 = \ "HbDtOsdai1oYziSx25KEeTxmwnh8L8jKMFNc1k3zmMI6VB8hry57tDZ61jXyez" + \ "SPt0fdLVfe6Jf5y5-JaCap_JQBcb5opbmT60uWGml8blyiMQmOn9J--XhhlYg0" + \ "m-BHaqfDO5iTOWxPxFMUedx7WCy8mxgDHj0aBMG6152PsM-w5E_o2B3jDbrYBK" + \ "hpYA7qi3AyijnCJ7BP9rr3U8kxExCpG3mK420TjOw" JWE_Authentication_Tag_5_9_4 = "VILuUwuIxaLVmh5X-T7kmA" JWE_compact_5_9_5 = \ "%s.%s.%s.%s.%s" % (JWE_Protected_Header_5_9_4, JWE_Encrypted_Key_5_9_3, JWE_IV_5_9_2, JWE_Ciphertext_5_9_4, JWE_Authentication_Tag_5_9_4) JWE_general_5_9_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_9_3}], "protected": JWE_Protected_Header_5_9_4, "iv": JWE_IV_5_9_2, "ciphertext": JWE_Ciphertext_5_9_4, "tag": JWE_Authentication_Tag_5_9_4} JWE_flattened_5_9_5 = { "protected": JWE_Protected_Header_5_9_4, "encrypted_key": JWE_Encrypted_Key_5_9_3, "iv": JWE_IV_5_9_2, "ciphertext": JWE_Ciphertext_5_9_4, "tag": JWE_Authentication_Tag_5_9_4} # 5.10 AAD_5_10_1 = base64url_encode(json_encode( ["vcard", [["version", {}, "text", "4.0"], ["fn", {}, "text", "Meriadoc Brandybuck"], ["n", {}, "text", ["Brandybuck", "Meriadoc", "Mr.", ""]], ["bday", {}, "text", "TA 2982"], ["gender", {}, "text", "M"]]])) JWE_IV_5_10_2 = "veCx9ece2orS7c_N" JWE_Encrypted_Key_5_10_3 = "4YiiQ_ZzH76TaIkJmYfRFgOV9MIpnx4X" JWE_Protected_Header_5_10_4 = \ "eyJhbGciOiJBMTI4S1ciLCJraWQiOiI4MWIyMDk2NS04MzMyLTQzZDktYTQ2OC" + \ "04MjE2MGFkOTFhYzgiLCJlbmMiOiJBMTI4R0NNIn0" JWE_Ciphertext_5_10_4 = \ "Z_3cbr0k3bVM6N3oSNmHz7Lyf3iPppGf3Pj17wNZqteJ0Ui8p74SchQP8xygM1" + \ "oFRWCNzeIa6s6BcEtp8qEFiqTUEyiNkOWDNoF14T_4NFqF-p2Mx8zkbKxI7oPK" + \ "8KNarFbyxIDvICNqBLba-v3uzXBdB89fzOI-Lv4PjOFAQGHrgv1rjXAmKbgkft" + \ "9cB4WeyZw8MldbBhc-V_KWZslrsLNygon_JJWd_ek6LQn5NRehvApqf9ZrxB4a" + \ "q3FXBxOxCys35PhCdaggy2kfUfl2OkwKnWUbgXVD1C6HxLIlqHhCwXDG59weHr" + \ "RDQeHyMRoBljoV3X_bUTJDnKBFOod7nLz-cj48JMx3SnCZTpbQAkFV" JWE_Authentication_Tag_5_10_4 = "vOaH_Rajnpy_3hOtqvZHRA" JWE_general_5_10_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_10_3}], "protected": JWE_Protected_Header_5_10_4, "iv": JWE_IV_5_10_2, "aad": AAD_5_10_1, "ciphertext": JWE_Ciphertext_5_10_4, "tag": JWE_Authentication_Tag_5_10_4} JWE_flattened_5_10_5 = { "protected": JWE_Protected_Header_5_10_4, "encrypted_key": JWE_Encrypted_Key_5_10_3, "iv": JWE_IV_5_10_2, "aad": AAD_5_10_1, "ciphertext": JWE_Ciphertext_5_10_4, "tag": JWE_Authentication_Tag_5_10_4} # 5.11 JWE_IV_5_11_2 = "WgEJsDS9bkoXQ3nR" JWE_Encrypted_Key_5_11_3 = "jJIcM9J-hbx3wnqhf5FlkEYos0sHsF0H" JWE_Protected_Header_5_11_4 = "eyJlbmMiOiJBMTI4R0NNIn0" JWE_Ciphertext_5_11_4 = \ "lIbCyRmRJxnB2yLQOTqjCDKV3H30ossOw3uD9DPsqLL2DM3swKkjOwQyZtWsFL" + \ "YMj5YeLht_StAn21tHmQJuuNt64T8D4t6C7kC9OCCJ1IHAolUv4MyOt80MoPb8" + \ "fZYbNKqplzYJgIL58g8N2v46OgyG637d6uuKPwhAnTGm_zWhqc_srOvgiLkzyF" + \ "XPq1hBAURbc3-8BqeRb48iR1-_5g5UjWVD3lgiLCN_P7AW8mIiFvUNXBPJK3nO" + \ "WL4teUPS8yHLbWeL83olU4UAgL48x-8dDkH23JykibVSQju-f7e-1xreHWXzWL" + \ "Hs1NqBbre0dEwK3HX_xM0LjUz77Krppgegoutpf5qaKg3l-_xMINmf" JWE_Authentication_Tag_5_11_4 = "fNYLqpUe84KD45lvDiaBAQ" JWE_Unprotected_Header_5_11_5 = { "alg": "A128KW", "kid": "81b20965-8332-43d9-a468-82160ad91ac8"} JWE_general_5_11_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_11_3}], "unprotected": JWE_Unprotected_Header_5_11_5, "protected": JWE_Protected_Header_5_11_4, "iv": JWE_IV_5_11_2, "ciphertext": JWE_Ciphertext_5_11_4, "tag": JWE_Authentication_Tag_5_11_4} JWE_flattened_5_11_5 = { "protected": JWE_Protected_Header_5_11_4, "unprotected": JWE_Unprotected_Header_5_11_5, "encrypted_key": JWE_Encrypted_Key_5_11_3, "iv": JWE_IV_5_11_2, "ciphertext": JWE_Ciphertext_5_11_4, "tag": JWE_Authentication_Tag_5_11_4} # 5.11 JWE_IV_5_12_2 = "YihBoVOGsR1l7jCD" JWE_Encrypted_Key_5_12_3 = "244YHfO_W7RMpQW81UjQrZcq5LSyqiPv" JWE_Ciphertext_5_12_4 = \ "qtPIMMaOBRgASL10dNQhOa7Gqrk7Eal1vwht7R4TT1uq-arsVCPaIeFwQfzrSS" + \ "6oEUWbBtxEasE0vC6r7sphyVziMCVJEuRJyoAHFSP3eqQPb4Ic1SDSqyXjw_L3" + \ "svybhHYUGyQuTmUQEDjgjJfBOifwHIsDsRPeBz1NomqeifVPq5GTCWFo5k_MNI" + \ "QURR2Wj0AHC2k7JZfu2iWjUHLF8ExFZLZ4nlmsvJu_mvifMYiikfNfsZAudISO" + \ "a6O73yPZtL04k_1FI7WDfrb2w7OqKLWDXzlpcxohPVOLQwpA3mFNRKdY-bQz4Z" + \ "4KX9lfz1cne31N4-8BKmojpw-OdQjKdLOGkC445Fb_K1tlDQXw2sBF" JWE_Authentication_Tag_5_12_4 = "e2m0Vm7JvjK2VpCKXS-kyg" JWE_Unprotected_Header_5_12_5 = { "alg": "A128KW", "kid": "81b20965-8332-43d9-a468-82160ad91ac8", "enc": "A128GCM"} JWE_general_5_12_5 = { "recipients": [{ "encrypted_key": JWE_Encrypted_Key_5_12_3}], "unprotected": JWE_Unprotected_Header_5_12_5, "iv": JWE_IV_5_12_2, "ciphertext": JWE_Ciphertext_5_12_4, "tag": JWE_Authentication_Tag_5_12_4} JWE_flattened_5_12_5 = { "unprotected": JWE_Unprotected_Header_5_12_5, "encrypted_key": JWE_Encrypted_Key_5_12_3, "iv": JWE_IV_5_12_2, "ciphertext": JWE_Ciphertext_5_12_4, "tag": JWE_Authentication_Tag_5_12_4} # 5.13 - A256GCMKW not implemented yet # In general we can't compare ciphertexts with the reference because # either the algorithms use random nonces to authenticate the ciphertext # or we randomly genrate the nonce when we create the JWE. # To double check implementation we encrypt/decrypt our own input and then # decrypt the reference and check it against the given plaintext class Cookbook08JWETests(unittest.TestCase): def test_5_1_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_1_4) rsa_key = jwk.JWK(**RSA_key_5_1_1) E = jwe.JWE(plaintext, protected) E.add_recipient(rsa_key) e = E.serialize() E.deserialize(e, rsa_key) self.assertEqual(E.payload, plaintext) E.deserialize(JWE_compact_5_1_5, rsa_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_1_5), rsa_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_1_5), rsa_key) self.assertEqual(E.payload, plaintext) def test_5_2_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_2_4) rsa_key = jwk.JWK(**RSA_key_5_2_1) E = jwe.JWE(plaintext, protected) E.add_recipient(rsa_key) e = E.serialize() E.deserialize(e, rsa_key) self.assertEqual(E.payload, plaintext) E.deserialize(JWE_compact_5_2_5, rsa_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_2_5), rsa_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_2_5), rsa_key) self.assertEqual(E.payload, plaintext) # 5.3 - PBES2-* not implemented yet # def test_5_3_encryption(self): # 5.4 - ECDH-ES key agreement not implemented yet # def test_5_4_encryption(self): # 5.5 - ECDH-ES key agreement not implemented yet # def test_5_5_encryption(self): def test_5_6_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_6_3) aes_key = jwk.JWK(**AES_key_5_6_1) E = jwe.JWE(plaintext, protected) E.add_recipient(aes_key) _ = E.serialize(compact=True) e = E.serialize() E.deserialize(e, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(JWE_compact_5_6_4, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_6_4), aes_key) self.assertEqual(E.payload, plaintext) # 5.7 - AES-GCM key wrapping not implemented yet # def test_5_7_encryption(self): def test_5_8_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_8_4) aes_key = jwk.JWK(**AES_key_5_8_1) E = jwe.JWE(plaintext, protected) E.add_recipient(aes_key) e = E.serialize() E.deserialize(e, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(JWE_compact_5_8_5, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_8_5), aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_8_5), aes_key) self.assertEqual(E.payload, plaintext) def test_5_9_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_9_4) aes_key = jwk.JWK(**AES_key_5_8_1) E = jwe.JWE(plaintext, protected) E.add_recipient(aes_key) e = E.serialize() E.deserialize(e, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(JWE_compact_5_9_5, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_9_5), aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_9_5), aes_key) self.assertEqual(E.payload, plaintext) def test_5_10_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_10_4) aad = base64url_decode(AAD_5_10_1) aes_key = jwk.JWK(**AES_key_5_8_1) E = jwe.JWE(plaintext, protected, aad=aad) E.add_recipient(aes_key) e = E.serialize() E.deserialize(e, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_10_5), aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_10_5), aes_key) self.assertEqual(E.payload, plaintext) def test_5_11_encryption(self): plaintext = Payload_plaintext_5 protected = base64url_decode(JWE_Protected_Header_5_11_4) unprotected = json_encode(JWE_Unprotected_Header_5_11_5) aes_key = jwk.JWK(**AES_key_5_8_1) E = jwe.JWE(plaintext, protected, unprotected) E.add_recipient(aes_key) e = E.serialize() E.deserialize(e, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_11_5), aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_11_5), aes_key) self.assertEqual(E.payload, plaintext) def test_5_12_encryption(self): plaintext = Payload_plaintext_5 unprotected = json_encode(JWE_Unprotected_Header_5_12_5) aes_key = jwk.JWK(**AES_key_5_8_1) E = jwe.JWE(plaintext, None, unprotected) E.add_recipient(aes_key) e = E.serialize() E.deserialize(e, aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_general_5_12_5), aes_key) self.assertEqual(E.payload, plaintext) E.deserialize(json_encode(JWE_flattened_5_12_5), aes_key) self.assertEqual(E.payload, plaintext) # 5.13 - AES-GCM key wrapping not implemented yet # def test_5_13_encryption(self): jwcrypto-0.2.1/jwcrypto/jwt.py0000664000175000017500000001072612540023424021052 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from jwcrypto.common import json_encode from jwcrypto.jws import JWS from jwcrypto.jwe import JWE class JWT(object): """JSON Web token object This object represent a generic token. """ def __init__(self, header=None, claims=None, jwt=None, key=None, algs=None): """Creates a JWT object. :param header: A dict or a JSON string with the JWT Header data. :param claims: A dict or a string withthe JWT Claims data. :param jwt: a 'raw' JWT token :param key: A (:class:`jwcrypto.jwk.JWK`) key to deserialize the token. :param algs: An optional list of allowed algorithms Note: either the header,claims or jwt,key parameters should be provided as a deserialization operation (which occurs if the jwt is provided will wipe any header os claim provided by setting those obtained from the deserialization of the jwt token. """ self._header = None self._claims = None self._token = None self._algs = algs if header: self.header = header if claims: self.claims = claims if jwt is not None: self.deserialize(jwt, key) @property def header(self): if self._header is None: raise KeyError("'header' not set") return self._header @header.setter def header(self, h): if isinstance(h, dict): self._header = json_encode(h) else: self._header = h @property def claims(self): if self._claims is None: raise KeyError("'claims' not set") return self._claims @claims.setter def claims(self, c): if isinstance(c, dict): self._claims = json_encode(c) else: self._claims = c @property def token(self): return self._token @token.setter def token(self, t): if isinstance(t, JWS) or isinstance(t, JWE) or isinstance(t, JWT): self._token = t else: raise TypeError("Invalid token type, must be one of JWS,JWE,JWT") def make_signed_token(self, key): """Signs the payload. Creates a JWS token with the header as the JWS protected header and the claims as the payload. See (:class:`jwcrypto.jws.JWS`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk.JWK`) key. """ t = JWS(self.claims) t.add_signature(key, protected=self.header) self.token = t def make_encrypted_token(self, key): """Encrypts the payload. Creates a JWE token with the header as the JWE protected header and the claims as the plaintext. See (:class:`jwcrypto.jwe.JWE`) for details on the exceptions that may be reaised. :param key: A (:class:`jwcrypto.jwk.JWK`) key. """ t = JWE(self.claims, self.header) t.add_recipient(key) self.token = t def deserialize(self, jwt, key=None): """Deserialize a JWT token. NOTE: Destroys any current status and tries to import the raw token provided. :param jwt: a 'raw' JWT token. :param key: A (:class:`jwcrypto.jwk.JWK`) verification or decryption key. """ c = jwt.count('.') if c == 2: self.token = JWS() elif c == 4: self.token = JWE() else: raise ValueError("Token format unrecognized") # Apply algs restrictions if any, before performing any operation if self._algs: self.token.allowed_algs = self._algs # now deserialize and also decrypt/verify (or raise) if we # have a key self.token.deserialize(jwt, key) if key is not None: self.header = self.token.jose_header self.claims = self.token.payload.decode('utf-8') def serialize(self, compact=True): """Serializes the object into a JWS token. :param compact(boolean): must be True. Note: the compact parameter is provided for general compatibility with the serialize() functions of :class:`jwcrypto.jws.JWS` and :class:`jwcrypto.jwe.JWE` so that these objects can all be used interchangeably. However the only valid JWT representtion is the compact representation. """ return self.token.serialize(compact) jwcrypto-0.2.1/jwcrypto/__init__.py0000664000175000017500000000000012540023424021765 0ustar puiterwijkpuiterwijk00000000000000jwcrypto-0.2.1/jwcrypto/jwk.py0000664000175000017500000004500712575550302021051 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from binascii import hexlify, unhexlify from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.asymmetric import ec from jwcrypto.common import base64url_decode, base64url_encode from jwcrypto.common import json_decode, json_encode import os # RFC 7518 - 7.4 JWKTypesRegistry = {'EC': 'Elliptic Curve', 'RSA': 'RSA', 'oct': 'Octet sequence'} """Registry of valid Key Types""" # RFC 7518 - 7.5 # It is part of the JWK Parameters Registry, but we want a more # specific map for internal usage JWKValuesRegistry = {'EC': {'crv': ('Curve', 'Public'), 'x': ('X Coordinate', 'Public'), 'y': ('Y Coordinate', 'Public'), 'd': ('ECC Private Key', 'Private')}, 'RSA': {'n': ('Modulus', 'Public'), 'e': ('Exponent', 'Public'), 'd': ('Private Exponent', 'Private'), 'p': ('First Prime Factor', 'Private'), 'q': ('Second Prime Factor', 'Private'), 'dp': ('First Factor CRT Exponent', 'Private'), 'dq': ('Second Factor CRT Exponent', 'Private'), 'qi': ('First CRT Coefficient', 'Private')}, 'oct': {'k': ('Key Value', 'Private')}} """Registry of valid key values""" JWKParamsRegistry = {'kty': ('Key Type', 'Public', ), 'use': ('Public Key Use', 'Public'), 'key_ops': ('Key Operations', 'Public'), 'alg': ('Algorithm', 'Public'), 'kid': ('Key ID', 'Public'), 'x5u': ('X.509 URL', 'Public'), 'x5c': ('X.509 Certificate Chain', 'Public'), 'x5t': ('X.509 Certificate SHA-1 Thumbprint', 'Public'), 'x5t#S256': ('X.509 Certificate SHA-256 Thumbprint', 'Public')} """Regstry of valid key parameters""" # RFC 7518 - 7.6 JWKEllipticCurveRegistry = {'P-256': 'P-256 curve', 'P-384': 'P-384 curve', 'P-521': 'P-521 curve'} """Registry of allowed Elliptic Curves""" # RFC 7517 - 8.2 JWKUseRegistry = {'sig': 'Digital Signature or MAC', 'enc': 'Encryption'} """Registry of allowed uses""" # RFC 7517 - 8.3 JWKOperationsRegistry = {'sign': 'Compute digital Signature or MAC', 'verify': 'Verify digital signature or MAC', 'encrypt': 'Encrypt content', 'decrypt': 'Decrypt content and validate' ' decryption, if applicable', 'wrapKey': 'Encrypt key', 'unwrapKey': 'Decrypt key and validate' ' decryption, if applicable', 'deriveKey': 'Derive key', 'deriveBits': 'Derive bits not to be used as a key'} """Registry of allowed operations""" class InvalidJWKType(Exception): """Invalid JWK Type Exception. This exception is raised when an invalid parameter type is used. """ def __init__(self, value=None): super(InvalidJWKType, self).__init__() self.value = value def __str__(self): return 'Unknown type "%s", valid types are: %s' % ( self.value, list(JWKTypesRegistry.keys())) class InvalidJWKUsage(Exception): """Invalid JWK usage Exception. This exception is raised when an invalid key usage is requested, based on the key type and declared usage constraints. """ def __init__(self, use, value): super(InvalidJWKUsage, self).__init__() self.value = value self.use = use def __str__(self): if self.use in list(JWKUseRegistry.keys()): usage = JWKUseRegistry[self.use] else: usage = 'Unknown(%s)' % self.use if self.value in list(JWKUseRegistry.keys()): valid = JWKUseRegistry[self.value] else: valid = 'Unknown(%s)' % self.value return 'Invalid usage requested: "%s". Valid for: "%s"' % (usage, valid) class InvalidJWKOperation(Exception): """Invalid JWK Operation Exception. This exception is raised when an invalid key operation is requested, based on the key type and declared usage constraints. """ def __init__(self, operation, values): super(InvalidJWKOperation, self).__init__() self.op = operation self.values = values def __str__(self): if self.op in list(JWKOperationsRegistry.keys()): op = JWKOperationsRegistry[self.op] else: op = 'Unknown(%s)' % self.op valid = list() for v in self.values: if v in list(JWKOperationsRegistry.keys()): valid.append(JWKOperationsRegistry[v]) else: valid.append('Unknown(%s)' % v) return 'Invalid operation requested: "%s". Valid for: "%s"' % (op, valid) class InvalidJWKValue(Exception): """Invalid JWK Value Exception. This exception is raised when an invalid/unknown value is used in the context of an operation that requires specific values to be used based on the key type or other constraints. """ pass class JWK(object): """JSON Web Key object This object represent a Key. It must be instantiated by using the standard defined key/value pairs as arguents of the initialization function. """ def __init__(self, **kwargs): """Creates a new JWK object. The function arguments must be valid parameters as defined in the 'IANA JSON Web Key Set Parameters registry' and specified in the :data:`JWKParamsRegistry` variable. The 'kty' parameter must always be provided and its value must be a valid one as defined by the 'IANA JSON Web Key Types registry' and specified in the :data:`JWKTypesRegistry` variable. The valid key parameters per key type are defined in the :data:`JWKValuesregistry` variable. Alternatively if the 'generate' parameter is provided, with a valid key type as value then a new key will be generated according to the defaults or provided key strenght options (type specific). Valid options per type, when generating new keys: * oct: size(int) * RSA: public_exponent(int), size(int) * EC: curve(str) (one of P-256, P-384, P-521) :raises InvalidJWKType: if the key type is invalid :raises InvalidJWKValue: if incorrect or inconsistent parameters are provided. """ self._params = dict() self._key = dict() self._unknown = dict() if 'generate' in kwargs: self.generate_key(**kwargs) else: self.import_key(**kwargs) def generate_key(self, **kwargs): params = kwargs.copy() try: kty = params['generate'] del params['generate'] gen = getattr(self, '_generate_%s' % kty) except (KeyError, AttributeError): raise InvalidJWKType(kty) gen(params) def _generate_oct(self, params): size = 128 if 'size' in params: size = params['size'] del params['size'] key = os.urandom(size // 8) params['kty'] = 'oct' params['k'] = base64url_encode(key) self.import_key(**params) def _encode_int(self, i): I = hex(i).rstrip("L").lstrip("0x") return base64url_encode(unhexlify((len(I) % 2) * '0' + I)) def _generate_RSA(self, params): pubexp = 65537 size = 2048 if 'public_exponent' in params: pubexp = params['public_exponent'] del params['public_exponent'] if 'size' in params: size = params['size'] del params['size'] key = rsa.generate_private_key(pubexp, size, default_backend()) pn = key.private_numbers() params['kty'] = 'RSA' params['n'] = self._encode_int(pn.public_numbers.n) params['e'] = self._encode_int(pn.public_numbers.e) params['d'] = self._encode_int(pn.d) params['p'] = self._encode_int(pn.p) params['q'] = self._encode_int(pn.q) params['dp'] = self._encode_int(pn.dmp1) params['dq'] = self._encode_int(pn.dmq1) params['qi'] = self._encode_int(pn.iqmp) self.import_key(**params) def _get_curve_by_name(self, name): if name == 'P-256': return ec.SECP256R1() elif name == 'P-384': return ec.SECP384R1() elif name == 'P-521': return ec.SECP521R1() else: raise InvalidJWKValue('Unknown Elliptic Curve Type') def _generate_EC(self, params): curve = 'P-256' if 'curve' in params: curve = params['curve'] del params['curve'] # 'curve' is for backwards compat, if 'crv' is defined it takes # precedence if 'crv' in params: curve = params['crv'] del params['crv'] curve_name = self._get_curve_by_name(curve) key = ec.generate_private_key(curve_name, default_backend()) pn = key.private_numbers() params['kty'] = 'EC' params['crv'] = curve params['x'] = self._encode_int(pn.public_numbers.x) params['y'] = self._encode_int(pn.public_numbers.y) params['d'] = self._encode_int(pn.private_value) self.import_key(**params) def import_key(self, **kwargs): names = list(kwargs.keys()) for name in list(JWKParamsRegistry.keys()): if name in kwargs: self._params[name] = kwargs[name] while name in names: names.remove(name) kty = self._params.get('kty', None) if kty not in JWKTypesRegistry: raise InvalidJWKType(kty) for name in list(JWKValuesRegistry[kty].keys()): if name in kwargs: self._key[name] = kwargs[name] while name in names: names.remove(name) # Unknown key parameters are allowed # Let's just store them out of the way for name in names: self._unknown[name] = kwargs[name] while name in names: names.remove(name) if len(names) != 0: raise InvalidJWKValue('Unknown key parameters: %s' % names) if len(self._key) == 0: raise InvalidJWKValue('No Key Values found') # check key_ops if 'key_ops' in self._params: for ko in self._params['key_ops']: c = 0 for cko in self._params['key_ops']: if ko == cko: c += 1 if c != 1: raise InvalidJWKValue('Duplicate values in "key_ops"') # check use/key_ops consistency if 'use' in self._params and 'key_ops' in self._params: sigl = ['sign', 'verify'] encl = ['encrypt', 'decrypt', 'wrapKey', 'unwrapKey', 'deriveKey', 'deriveBits'] if self._params['use'] == 'sig': for op in encl: if op in self._params['key_ops']: raise InvalidJWKValue('Incompatible "use" and' ' "key_ops" values specified at' ' the same time') elif self._params['use'] == 'enc': for op in sigl: if op in self._params['key_ops']: raise InvalidJWKValue('Incompatible "use" and' ' "key_ops" values specified at' ' the same time') def export(self): """Exports the key in the standard JSON format""" d = dict() d.update(self._params) d.update(self._key) d.update(self._unknown) return json_encode(d) def export_public(self): """Exports the public key in the standard JSON format""" pub = {} preg = JWKParamsRegistry for name in preg: if preg[name][1] == 'Public': if name in self._params: pub[name] = self._params[name] reg = JWKValuesRegistry[self._params['kty']] for param in reg: if reg[param][1] == 'Public': pub[param] = self._key[param] return json_encode(pub) @property def key_type(self): """The Key type""" return self._params.get('kty', None) @property def key_id(self): """The Key ID. Provided by the kid parameter if present, otherwise returns None. """ return self._params.get('kid', None) def get_curve(self, arg): """Gets the Elliptic Curve associated with the key. :param arg: an optional curve name :raises InvalidJWKType: the key is not an EC key. :raises InvalidJWKValue: if the curve names is invalid. """ k = self._key if self._params['kty'] != 'EC': raise InvalidJWKType('Not an EC key') if arg and k['crv'] != arg: raise InvalidJWKValue('Curve requested is "%s", but ' 'key curve is "%s"' % (arg, k['crv'])) return self._get_curve_by_name(k['crv']) def _check_constraints(self, usage, operation): use = self._params.get('use', None) if use and use != usage: raise InvalidJWKUsage(usage, use) ops = self._params.get('key_ops', None) if ops: if not isinstance(ops, list): ops = [ops] if operation not in ops: raise InvalidJWKOperation(operation, ops) # TODO: check alg ? def _decode_int(self, n): return int(hexlify(base64url_decode(n)), 16) def _rsa_pub(self, k): return rsa.RSAPublicNumbers(self._decode_int(k['e']), self._decode_int(k['n'])) def _rsa_pri(self, k): return rsa.RSAPrivateNumbers(self._decode_int(k['p']), self._decode_int(k['q']), self._decode_int(k['d']), self._decode_int(k['dp']), self._decode_int(k['dq']), self._decode_int(k['qi']), self._rsa_pub(k)) def _ec_pub(self, k, curve): return ec.EllipticCurvePublicNumbers(self._decode_int(k['x']), self._decode_int(k['y']), self.get_curve(curve)) def _ec_pri(self, k, curve): return ec.EllipticCurvePrivateNumbers(self._decode_int(k['d']), self._ec_pub(k, curve)) def _get_public_key(self, arg=None): if self._params['kty'] == 'oct': return self._key['k'] elif self._params['kty'] == 'RSA': return self._rsa_pub(self._key).public_key(default_backend()) elif self._params['kty'] == 'EC': return self._ec_pub(self._key, arg).public_key(default_backend()) else: raise NotImplementedError def _get_private_key(self, arg=None): if self._params['kty'] == 'oct': return self._key['k'] elif self._params['kty'] == 'RSA': return self._rsa_pri(self._key).private_key(default_backend()) elif self._params['kty'] == 'EC': return self._ec_pri(self._key, arg).private_key(default_backend()) else: raise NotImplementedError def get_op_key(self, operation=None, arg=None): """Get the key object associated to the requested opration. For example the public RSA key for the 'verify' operation or the private EC key for the 'decrypt' operation. :param operation: The requested operation. The valid set of operations is availble in the :data:`JWKOperationsRegistry` registry. :param arg: an optional, context specific, argument For example a curve name. :raises InvalidJWKOperation: if the operation is unknown or not permitted with this key. :raises InvalidJWKUsage: if the use constraints do not permit the operation. """ validops = self._params.get('key_ops', list(JWKOperationsRegistry.keys())) if validops is not list: validops = [validops] if operation is None: if self._params['kty'] == 'oct': return self._key['k'] raise InvalidJWKOperation(operation, validops) elif operation == 'sign': self._check_constraints('sig', operation) return self._get_private_key(arg) elif operation == 'verify': self._check_constraints('sig', operation) return self._get_public_key(arg) elif operation == 'encrypt' or operation == 'wrapKey': self._check_constraints('enc', operation) return self._get_public_key(arg) elif operation == 'decrypt' or operation == 'unwrapKey': self._check_constraints('enc', operation) return self._get_private_key(arg) else: raise NotImplementedError class JWKSet(set): """A set of JWK objects. Inherits for the standard 'set' bultin type. """ def add(self, elem): """Adds a JWK object to the set :param elem: the JWK object to add. :raises TypeError: if the object is not a JWK. """ if not isinstance(elem, JWK): raise TypeError('Only JWK objects are valid elements') set.add(self, elem) def export(self): """Exports the set using the standard JSON format""" keys = list() for jwk in self: keys.append(json_decode(jwk.export())) return json_encode({'keys': keys}) def get_key(self, kid): """Gets a key from the set. :param kid: the 'kid' key identifier. """ for jwk in self: if jwk.key_id == kid: return jwk return None jwcrypto-0.2.1/jwcrypto/tests.py0000664000175000017500000011231612575550302021416 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from __future__ import unicode_literals from jwcrypto.common import base64url_decode, base64url_encode from jwcrypto.common import json_decode, json_encode from jwcrypto import jwk from jwcrypto import jws from jwcrypto import jwe from jwcrypto import jwt import unittest # RFC 7517 - A.1 PublicKeys = {"keys": [ {"kty": "EC", "crv": "P-256", "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", "use": "enc", "kid": "1"}, {"kty": "RSA", "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbf" "AAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknj" "hMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65" "YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQ" "vRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lF" "d2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzK" "nqDKgw", "e": "AQAB", "alg": "RS256", "kid": "2011-04-29"}]} # RFC 7517 - A.2 PrivateKeys = {"keys": [ {"kty": "EC", "crv": "P-256", "x": "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4", "y": "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM", "d": "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE", "use": "enc", "kid": "1"}, {"kty": "RSA", "n": "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbb" "fAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3ok" "njhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v" "-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu" "6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0" "fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8a" "wapJzKnqDKgw", "e": "AQAB", "d": "X4cTteJY_gn4FYPsXB8rdXix5vwsg1FLN5E3EaG6RJoVH-HLLKD9M7d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zgU" "IZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_" "mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia" "6zTKhAVRU", "alg": "RS256", "kid": "2011-04-29"}]} # RFC 7517 - A.3 SymmetricKeys = {"keys": [ {"kty": "oct", "alg": "A128KW", "k": "GawgguFyGrWKav7AX4VKUg"}, {"kty": "oct", "k": "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH7" "5aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow", "kid": "HMAC key used in JWS A.1 example"}]} # RFC 7517 - B Useofx5c = {"kty": "RSA", "use": "sig", "kid": "1b94c", "n": "vrjOfz9Ccdgx5nQudyhdoR17V-IubWMeOZCwX_jj0hgAsz2J_pqYW08PLbK" "_PdiVGKPrqzmDIsLI7sA25VEnHU1uCLNwBuUiCO11_-7dYbsr4iJmG0Qu2j" "8DsVyT1azpJC_NG84Ty5KKthuCaPod7iI7w0LK9orSMhBEwwZDCxTWq4aYW" "Achc8t-emd9qOvWtVMDC2BXksRngh6X5bUYLy6AyHKvj-nUy1wgzjYQDwHM" "TplCoLtU-o-8SNnZ1tmRoGE9uJkBLdh5gFENabWnU5m1ZqZPdwS-qo-meMv" "VfJb6jJVWRpl2SUtCnYG2C32qvbWbjZ_jBPD5eunqsIo1vQ", "e": "AQAB", "x5c": ["MIIDQjCCAiqgAwIBAgIGATz/FuLiMA0GCSqGSIb3DQEBBQUAMGIxCzAJ" "BgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVudmVyMRww" "GgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQDEw5Ccmlh" "biBDYW1wYmVsbDAeFw0xMzAyMjEyMzI5MTVaFw0xODA4MTQyMjI5MTVa" "MGIxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDTzEPMA0GA1UEBxMGRGVu" "dmVyMRwwGgYDVQQKExNQaW5nIElkZW50aXR5IENvcnAuMRcwFQYDVQQD" "Ew5CcmlhbiBDYW1wYmVsbDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC" "AQoCggEBAL64zn8/QnHYMeZ0LncoXaEde1fiLm1jHjmQsF/449IYALM9" "if6amFtPDy2yvz3YlRij66s5gyLCyO7ANuVRJx1NbgizcAblIgjtdf/u" "3WG7K+IiZhtELto/A7Fck9Ws6SQvzRvOE8uSirYbgmj6He4iO8NCyvaK" "0jIQRMMGQwsU1quGmFgHIXPLfnpnfajr1rVTAwtgV5LEZ4Iel+W1GC8u" "gMhyr4/p1MtcIM42EA8BzE6ZQqC7VPqPvEjZ2dbZkaBhPbiZAS3YeYBR" "DWm1p1OZtWamT3cEvqqPpnjL1XyW+oyVVkaZdklLQp2Btgt9qr21m42f" "4wTw+Xrp6rCKNb0CAwEAATANBgkqhkiG9w0BAQUFAAOCAQEAh8zGlfSl" "cI0o3rYDPBB07aXNswb4ECNIKG0CETTUxmXl9KUL+9gGlqCz5iWLOgWs" "nrcKcY0vXPG9J1r9AqBNTqNgHq2G03X09266X5CpOe1zFo+Owb1zxtp3" "PehFdfQJ610CDLEaS9V9Rqp17hCyybEpOGVwe8fnk+fbEL2Bo3UPGrps" "HzUoaGpDftmWssZkhpBJKVMJyf/RuP2SmmaIzmnw9JiSlYhzo4tpzd5r" "FXhjRbg4zW9C+2qok+2+qDM1iJ684gPHMIY8aLWrdgQTxkumGmTqgawR" "+N5MDtdPTEQ0XfIBc2cJEUyMTY5MPvACWpkA6SdS4xSvdXK3IVfOWA==" ]} # RFC 7517 - C.1 RSAPrivateKey = {"kty": "RSA", "kid": "juliet@capulet.lit", "use": "enc", "n": "t6Q8PWSi1dkJj9hTP8hNYFlvadM7DflW9mWepOJhJ66w7nyoK1gPNq" "FMSQRyO125Gp-TEkodhWr0iujjHVx7BcV0llS4w5ACGgPrcAd6ZcSR" "0-Iqom-QFcNP8Sjg086MwoqQU_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" "hqigI4y_kqS1wY52IwjUn5rgRrJ-yYo1h41KR-vz2pYhEAeYrhttW" "txVqLCRViD6c", "dq": "AvfS0-gRxvn0bwJoMSnFxYcK1WnuEjQFluMGfwGitQBWtfZ1Er7t1" "xDkbN9GQTB9yqpDoYaN06H7CFtrkxhJIBQaj6nkF5KKS3TQtQ5qCz" "kOkmxIe3KRbBymXxkb5qwUpX5ELD5xFc6FeiafWYY63TmmEAu_lRF" "COJ3xDea-ots", "qi": "lSQi-w9CpyUReMErP1RsBLk7wNtOvs5EQpPqmuMvqW57NBUczScEo" "PwmUqqabu9V0-Py4dQ57_bapoKRu1R90bvuFnU63SHWEFglZQvJDM" "eAvmj4sm-Fp0oYu_neotgQ0hzbI5gry7ajdYy9-2lNx_76aBZoOUu" "9HCJ-UsfSOI8"} class TestJWK(unittest.TestCase): def test_create_pubKeys(self): keylist = PublicKeys['keys'] for key in keylist: _ = jwk.JWK(**key) def test_create_priKeys(self): keylist = PrivateKeys['keys'] for key in keylist: _ = jwk.JWK(**key) def test_create_symKeys(self): keylist = SymmetricKeys['keys'] for key in keylist: jwkey = jwk.JWK(**key) _ = jwkey.get_op_key('sign') _ = jwkey.get_op_key('verify') e = jwkey.export() self.assertEqual(json_decode(e), key) _ = jwk.JWK(**Useofx5c) _ = jwk.JWK(**RSAPrivateKey) def test_generate_keys(self): jwk.JWK(generate='oct', size=256) jwk.JWK(generate='RSA', size=4096) jwk.JWK(generate='EC', curve='P-521') def test_export_public_keys(self): k = jwk.JWK(**RSAPrivateKey) jk = k.export_public() self.assertFalse('d' in json_decode(jk)) k2 = jwk.JWK(**json_decode(jk)) self.assertEqual(k.key_id, k2.key_id) def test_generate_oct_key(self): key = jwk.JWK(generate='oct', size=128) E = jwe.JWE('test', '{"alg":"A128KW","enc":"A128GCM"}') E.add_recipient(key) e = E.serialize() E.deserialize(e, key) self.assertEqual(E.payload.decode('utf-8'), 'test') def test_generate_EC_key(self): # Backwards compat curve key = jwk.JWK(generate='EC', curve='P-256') key.get_curve('P-256') # New param key = jwk.JWK(generate='EC', crv='P-521') key.get_curve('P-521') # New param prevails key = jwk.JWK(generate='EC', curve='P-256', crv='P-521') key.get_curve('P-521') # RFC 7515 - A.1 A1_protected = \ [123, 34, 116, 121, 112, 34, 58, 34, 74, 87, 84, 34, 44, 13, 10, 32, 34, 97, 108, 103, 34, 58, 34, 72, 83, 50, 53, 54, 34, 125] A1_payload = \ [123, 34, 105, 115, 115, 34, 58, 34, 106, 111, 101, 34, 44, 13, 10, 32, 34, 101, 120, 112, 34, 58, 49, 51, 48, 48, 56, 49, 57, 51, 56, 48, 44, 13, 10, 32, 34, 104, 116, 116, 112, 58, 47, 47, 101, 120, 97, 109, 112, 108, 101, 46, 99, 111, 109, 47, 105, 115, 95, 114, 111, 111, 116, 34, 58, 116, 114, 117, 101, 125] A1_signature = \ [116, 24, 223, 180, 151, 153, 224, 37, 79, 250, 96, 125, 216, 173, 187, 186, 22, 212, 37, 77, 105, 214, 191, 240, 91, 88, 5, 88, 83, 132, 141, 121] A1_example = {'key': SymmetricKeys['keys'][1], 'alg': 'HS256', 'protected': bytes(bytearray(A1_protected)).decode('utf-8'), 'payload': bytes(bytearray(A1_payload)), 'signature': bytes(bytearray(A1_signature))} # RFC 7515 - A.2 A2_protected = \ [123, 34, 97, 108, 103, 34, 58, 34, 82, 83, 50, 53, 54, 34, 125] A2_payload = A1_payload A2_key = \ {"kty": "RSA", "n": "ofgWCuLjybRlzo0tZWJjNiuSfb4p4fAkd_wWJcyQoTbji9k0l8W26mPddx" "HmfHQp-Vaw-4qPCJrcS2mJPMEzP1Pt0Bm4d4QlL-yRT-SFd2lZS-pCgNMs" "D1W_YpRPEwOWvG6b32690r2jZ47soMZo9wGzjb_7OMg0LOL-bSf63kpaSH" "SXndS5z5rexMdbBYUsLA9e-KXBdQOS-UTo7WTBEMa2R2CapHg665xsmtdV" "MTBQY4uDZlxvb3qCo5ZwKh9kG4LT6_I5IhlJH7aGhyxXFvUK-DWNmoudF8" "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Md2w9cjz3_-ky" "NlxAr2v4IKhGNpmM5iIgOS1VZnOZ68m6_pbLBSp3nssTdlqvd0tIiTHU", "qi": "IYd7DHOhrWvxkwPQsRM2tOgrjbcrfvtQJipd-DlcxyVuuM9sQLdgjVk2o" "y26F0EmpScGLq2MowX7fhd_QJQ3ydy5cY7YIBi87w93IKLEdfnbJtoOPLU" "W0ITrJReOgo1cq9SbsxYawBgfp_gh6A5603k2-ZQwVK0JKSHuLFkuQ3U"} A2_signature = \ [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] A2_example = {'key': A2_key, 'alg': 'RS256', 'protected': bytes(bytearray(A2_protected)).decode('utf-8'), 'payload': bytes(bytearray(A2_payload)), 'signature': bytes(bytearray(A2_signature))} # RFC 7515 - A.3 A3_protected = \ [123, 34, 97, 108, 103, 34, 58, 34, 69, 83, 50, 53, 54, 34, 125] A3_payload = A2_payload A3_key = \ {"kty": "EC", "crv": "P-256", "x": "f83OJ3D2xF1Bg8vub9tLe1gHMzV76e8Tus9uPHvRVEU", "y": "x_FEzRu9m36HLN_tue659LNpXW6pCyStikYjKIWI5a0", "d": "jpsQnnGQmL-YBIffH1136cspYG6-0iY7X1fCE9-E9LI"} A3_signature = \ [14, 209, 33, 83, 121, 99, 108, 72, 60, 47, 127, 21, 88, 7, 212, 2, 163, 178, 40, 3, 58, 249, 124, 126, 23, 129, 154, 195, 22, 158, 166, 101] + \ [197, 10, 7, 211, 140, 60, 112, 229, 216, 241, 45, 175, 8, 74, 84, 128, 166, 101, 144, 197, 242, 147, 80, 154, 143, 63, 127, 138, 131, 163, 84, 213] A3_example = {'key': A3_key, 'alg': 'ES256', 'protected': bytes(bytearray(A3_protected)).decode('utf-8'), 'payload': bytes(bytearray(A3_payload)), 'signature': bytes(bytearray(A3_signature))} # RFC 7515 - A.4 A4_protected = \ [123, 34, 97, 108, 103, 34, 58, 34, 69, 83, 53, 49, 50, 34, 125] A4_payload = [80, 97, 121, 108, 111, 97, 100] A4_key = \ {"kty": "EC", "crv": "P-521", "x": "AekpBQ8ST8a8VcfVOTNl353vSrDCLLJXmPk06wTjxrrjcBpXp5EOnYG_" "NjFZ6OvLFV1jSfS9tsz4qUxcWceqwQGk", "y": "ADSmRA43Z1DSNx_RvcLI87cdL07l6jQyyBXMoxVg_l2Th-x3S1WDhjDl" "y79ajL4Kkd0AZMaZmh9ubmf63e3kyMj2", "d": "AY5pb7A0UFiB3RELSD64fTLOSV_jazdF7fLYyuTw8lOfRhWg6Y6rUrPA" "xerEzgdRhajnu0ferB0d53vM9mE15j2C"} A4_signature = \ [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] A4_example = {'key': A4_key, 'alg': 'ES512', 'protected': bytes(bytearray(A4_protected)).decode('utf-8'), 'payload': bytes(bytearray(A4_payload)), 'signature': bytes(bytearray(A4_signature))} # RFC 7515 - A.4 A5_protected = 'eyJhbGciOiJub25lIn0' A5_payload = A2_payload A5_key = \ {"kty": "oct", "k": ""} A5_signature = b'' A5_example = {'key': A5_key, 'alg': 'none', 'protected': base64url_decode(A5_protected).decode('utf-8'), 'payload': bytes(bytearray(A5_payload)), 'signature': A5_signature} A6_serialized = \ '{' + \ '"payload":' + \ '"eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF' + \ 'tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ",' + \ '"signatures":[' + \ '{"protected":"eyJhbGciOiJSUzI1NiJ9",' + \ '"header":' + \ '{"kid":"2010-12-29"},' + \ '"signature":' + \ '"cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZ' + \ 'mh7AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjb' + \ 'KBYNX4BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHl' + \ 'b1L07Qe7K0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZES' + \ 'c6BfI7noOPqvhJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AX' + \ 'LIhWkWywlVmtVrBp0igcN_IoypGlUPQGe77Rw"},' + \ '{"protected":"eyJhbGciOiJFUzI1NiJ9",' + \ '"header":' + \ '{"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"},' + \ '"signature":' + \ '"DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8IS' + \ 'lSApmWQxfKTUJqPP3-Kg6NU1Q"}]' + \ '}' A6_example = { 'payload': bytes(bytearray(A2_payload)), 'key1': jwk.JWK(**A2_key), 'protected1': bytes(bytearray(A2_protected)).decode('utf-8'), 'header1': json_encode({"kid": "2010-12-29"}), 'key2': jwk.JWK(**A3_key), 'protected2': bytes(bytearray(A3_protected)).decode('utf-8'), 'header2': json_encode({"kid": "e9bc097a-ce51-4036-9562-d2ade882db0d"}), 'serialized': A6_serialized} A7_example = \ '{' + \ '"payload":' + \ '"eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMDA4MTkzODAsDQogImh0dHA6Ly9leGF' + \ 'tcGxlLmNvbS9pc19yb290Ijp0cnVlfQ",' + \ '"protected":"eyJhbGciOiJFUzI1NiJ9",' + \ '"header":' + \ '{"kid":"e9bc097a-ce51-4036-9562-d2ade882db0d"},' + \ '"signature":' + \ '"DtEhU3ljbEg8L38VWAfUAqOyKAM6-Xx-F4GawxaepmXFCgfTjDxw5djxLa8IS' + \ 'lSApmWQxfKTUJqPP3-Kg6NU1Q"' + \ '}' E_negative = \ 'eyJhbGciOiJub25lIiwNCiAiY3JpdCI6WyJodHRwOi8vZXhhbXBsZS5jb20vVU5ERU' + \ 'ZJTkVEIl0sDQogImh0dHA6Ly9leGFtcGxlLmNvbS9VTkRFRklORUQiOnRydWUNCn0.' + \ 'RkFJTA.' class TestJWS(unittest.TestCase): def check_sign(self, test): S = jws.JWSCore(test['alg'], jwk.JWK(**test['key']), test['protected'], test['payload'], test.get('allowed_algs', None)) sig = S.sign() decsig = base64url_decode(sig['signature']) S.verify(decsig) # ECDSA signatures are always different every time # they are generated unlike RSA or symmetric ones if test['key']['kty'] != 'EC': self.assertEqual(decsig, test['signature']) else: # Check we can verify the test signature independently # this is so taht we can test the ECDSA agaist a known # good signature S.verify(test['signature']) def test_A1(self): self.check_sign(A1_example) def test_A2(self): self.check_sign(A2_example) def test_A3(self): self.check_sign(A3_example) def test_A4(self): self.check_sign(A4_example) def test_A5(self): self.assertRaises(jws.InvalidJWSOperation, self.check_sign, A5_example) A5_bis = {'allowed_algs': ['none']} A5_bis.update(A5_example) self.check_sign(A5_bis) def test_A6(self): S = jws.JWS(A6_example['payload']) S.add_signature(A6_example['key1'], None, A6_example['protected1'], A6_example['header1']) S.add_signature(A6_example['key2'], None, A6_example['protected2'], A6_example['header2']) sig = S.serialize() S.deserialize(sig, A6_example['key1']) S.deserialize(A6_serialized, A6_example['key2']) def test_A7(self): S = jws.JWS(A6_example['payload']) S.deserialize(A7_example, A6_example['key2']) def test_E(self): S = jws.JWS(A6_example['payload']) with self.assertRaises(jws.InvalidJWSSignature): jws.InvalidJWSSignature(S.deserialize, E_negative) S.verify(None) E_A1_plaintext = \ [84, 104, 101, 32, 116, 114, 117, 101, 32, 115, 105, 103, 110, 32, 111, 102, 32, 105, 110, 116, 101, 108, 108, 105, 103, 101, 110, 99, 101, 32, 105, 115, 32, 110, 111, 116, 32, 107, 110, 111, 119, 108, 101, 100, 103, 101, 32, 98, 117, 116, 32, 105, 109, 97, 103, 105, 110, 97, 116, 105, 111, 110, 46] E_A1_protected = "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZHQ00ifQ" E_A1_key = \ {"kty": "RSA", "n": "oahUIoWw0K0usKNuOR6H4wkf4oBUX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'key': jwk.JWK(**E_A1_key), 'protected': base64url_decode(E_A1_protected), 'plaintext': bytes(bytearray(E_A1_plaintext)), 'vector': E_A1_vector} E_A2_plaintext = "Live long and prosper." E_A2_protected = "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0" E_A2_key = \ {"kty": "RSA", "n": "sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1Wl" "UzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDpre" "cbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_" "7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBI" "Y2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU" "7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw", "e": "AQAB", "d": "VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq" "1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-ry" "nq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_" "0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj" "-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-Kyvj" "T1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ", "p": "9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68" "ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEP" "krdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_bi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8" \ "rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPgwCp6X-nZZd9OHBv" \ "-B3oWh2TbqmScqXMR4gp_A." \ "AxY8DCtDaGlsbGljb3RoZQ." \ "KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY." \ "9hH0vgRfYgPnAHOd8stkvw" E_A2_ex = {'key': jwk.JWK(**E_A2_key), 'protected': base64url_decode(E_A2_protected), 'plaintext': E_A2_plaintext, 'vector': E_A2_vector} E_A3_plaintext = "Live long and prosper." E_A3_protected = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0" E_A3_key = {"kty": "oct", "k": "GawgguFyGrWKav7AX4VKUg"} E_A3_vector = \ "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." \ "6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ." \ "AxY8DCtDaGlsbGljb3RoZQ." \ "KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY." \ "U0m_YmjN04DJvceFICbCVQ" E_A3_ex = {'key': jwk.JWK(**E_A3_key), 'protected': base64url_decode(E_A3_protected).decode('utf-8'), 'plaintext': E_A3_plaintext, 'vector': E_A3_vector} E_A4_protected = "eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0" E_A4_unprotected = {"jku": "https://server.example.com/keys.jwks"} E_A4_vector = \ '{"protected":"eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",' \ '"unprotected":{"jku":"https://server.example.com/keys.jwks"},' \ '"recipients":[' \ '{"header":{"alg":"RSA1_5","kid":"2011-04-29"},' \ '"encrypted_key":'\ '"UGhIOguC7IuEvf_NPVaXsGMoLOmwvc1GyqlIKOK1nN94nHPoltGRhWhw7Zx0-' \ 'kFm1NJn8LE9XShH59_i8J0PH5ZZyNfGy2xGdULU7sHNF6Gp2vPLgNZ__deLKx' \ 'GHZ7PcHALUzoOegEI-8E66jX2E4zyJKx-YxzZIItRzC5hlRirb6Y5Cl_p-ko3' \ 'YvkkysZIFNPccxRU7qve1WYPxqbb2Yw8kZqa2rMWI5ng8OtvzlV7elprCbuPh' \ 'cCdZ6XDP0_F8rkXds2vE4X-ncOIM8hAYHHi29NX0mcKiRaD0-D-ljQTP-cFPg' \ 'wCp6X-nZZd9OHBv-B3oWh2TbqmScqXMR4gp_A"},' \ '{"header":{"alg":"A128KW","kid":"7"},' \ '"encrypted_key":' \ '"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ"}],' \ '"iv":"AxY8DCtDaGlsbGljb3RoZQ",' \ '"ciphertext":"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY",' \ '"tag":"Mz-VPPyU4RlcuYv1IwIvzw"}' E_A4_ex = {'key1': jwk.JWK(**E_A2_key), 'header1': '{"alg":"RSA1_5","kid":"2011-04-29"}', 'key2': jwk.JWK(**E_A3_key), 'header2': '{"alg":"A128KW","kid":"7"}', 'protected': base64url_decode(E_A4_protected), 'unprotected': json_encode(E_A4_unprotected), 'plaintext': E_A3_plaintext, 'vector': E_A4_vector} E_A5_ex = \ '{"protected":"eyJlbmMiOiJBMTI4Q0JDLUhTMjU2In0",' \ '"unprotected":{"jku":"https://server.example.com/keys.jwks"},' \ '"header":{"alg":"A128KW","kid":"7"},' \ '"encrypted_key":' \ '"6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ",' \ '"iv":"AxY8DCtDaGlsbGljb3RoZQ",' \ '"ciphertext":"KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY",' \ '"tag":"Mz-VPPyU4RlcuYv1IwIvzw"}' class TestJWE(unittest.TestCase): def check_enc(self, plaintext, protected, key, vector): E = jwe.JWE(plaintext, protected) E.add_recipient(key) # Encrypt and serialize using compact e = E.serialize() # And test that we can decrypt our own E.deserialize(e, key) # Now test the Spec Test Vector E.deserialize(vector, key) def test_A1(self): self.check_enc(E_A1_ex['plaintext'], E_A1_ex['protected'], E_A1_ex['key'], E_A1_ex['vector']) def test_A2(self): self.check_enc(E_A2_ex['plaintext'], E_A2_ex['protected'], E_A2_ex['key'], E_A2_ex['vector']) def test_A3(self): self.check_enc(E_A3_ex['plaintext'], E_A3_ex['protected'], E_A3_ex['key'], E_A3_ex['vector']) def test_A4(self): E = jwe.JWE(E_A4_ex['plaintext'], E_A4_ex['protected']) E.add_recipient(E_A4_ex['key1'], E_A4_ex['header1']) E.add_recipient(E_A4_ex['key2'], E_A4_ex['header2']) e = E.serialize() E.deserialize(e, E_A4_ex['key1']) E.deserialize(e, E_A4_ex['key2']) # Now test the Spec Test Vector E.deserialize(E_A4_ex['vector'], E_A4_ex['key1']) E.deserialize(E_A4_ex['vector'], E_A4_ex['key2']) def test_A5(self): E = jwe.JWE() E.deserialize(E_A5_ex, E_A4_ex['key2']) with self.assertRaises(jwe.InvalidJWEData): E = jwe.JWE(algs=['A256KW']) E.deserialize(E_A5_ex, E_A4_ex['key2']) # RFC 7519 A1_header = { "alg": "RSA1_5", "enc": "A128CBC-HS256"} A1_claims = { "iss": "joe", "exp": 1300819380, "http://example.com/is_root": True} A1_token = \ "eyJhbGciOiJSU0ExXzUiLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0." + \ "QR1Owv2ug2WyPBnbQrRARTeEk9kDO2w8qDcjiHnSJflSdv1iNqhWXaKH4MqAkQtM" + \ "oNfABIPJaZm0HaA415sv3aeuBWnD8J-Ui7Ah6cWafs3ZwwFKDFUUsWHSK-IPKxLG" + \ "TkND09XyjORj_CHAgOPJ-Sd8ONQRnJvWn_hXV1BNMHzUjPyYwEsRhDhzjAD26ima" + \ "sOTsgruobpYGoQcXUwFDn7moXPRfDE8-NoQX7N7ZYMmpUDkR-Cx9obNGwJQ3nM52" + \ "YCitxoQVPzjbl7WBuB7AohdBoZOdZ24WlN1lVIeh8v1K4krB8xg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WxSNsS-r1TJ1I-FMJ4XyAiGrfmo9hQPcNBYxPz3GQb2" + \ "8Y5CLSQfNgKSGt0A4isp1hBUXBHAndgtcslt7ZoQJaKe_nNJgNliWtWpJ_ebuOpE" + \ "l8jdhehdccnRMIwAmU1n7SPkmhIl1HlSOpvcvDfhUN5wuqU955vOBvfkBOh5A11U" + \ "zBuo2WlgZ6hYi9-e3w29bR0C2-pp3jbqxEDw3iWaf2dc5b-LnR0FEYXvI_tYk5rd" + \ "_J9N0mg0tQ6RbpxNEMNoA9QWk5lgdPvbh9BaO195abQ." + \ "AVO9iT5AV4CzvDJCdhSFlQ" class TestJWT(unittest.TestCase): def test_A1(self): key = jwk.JWK(**E_A2_key) # first encode/decode ourselves T = jwt.JWT(A1_header, A1_claims) T.make_encrypted_token(key) token = T.serialize() T.deserialize(token) # then try the test vector T = jwt.JWT(jwt=A1_token, key=key) def test_A2(self): sigkey = jwk.JWK(**A2_example['key']) Touter = jwt.JWT(jwt=A2_token, key=E_A2_ex['key']) Tinner = jwt.JWT(jwt=Touter.claims, key=sigkey) self.assertEqual(A1_claims, json_decode(Tinner.claims)) with self.assertRaises(jwe.InvalidJWEData): jwt.JWT(jwt=A2_token, key=E_A2_ex['key'], algs=['RSA_1_5', 'AES256GCM']) class ConformanceTests(unittest.TestCase): def test_unknown_key_params(self): key = jwk.JWK(kty='oct', k='secret', unknown='mystery') # pylint: disable=protected-access self.assertEqual('mystery', key._unknown['unknown']) def test_key_ops_values(self): self.assertRaises(jwk.InvalidJWKValue, jwk.JWK, kty='RSA', n=1, key_ops=['sign'], use='enc') self.assertRaises(jwk.InvalidJWKValue, jwk.JWK, kty='RSA', n=1, key_ops=['sign', 'sign']) def test_jwe_no_protected_header(self): enc = jwe.JWE(plaintext='plain') enc.add_recipient(jwk.JWK(kty='oct', k=base64url_encode(b'A'*16)), '{"alg":"A128KW","enc":"A128GCM"}') def test_jwe_no_alg_in_jose_headers(self): enc = jwe.JWE(plaintext='plain') self.assertRaises(jwe.InvalidJWEData, enc.add_recipient, jwk.JWK(kty='oct', k=base64url_encode(b'A'*16)), '{"enc":"A128GCM"}') def test_jwe_no_enc_in_jose_headers(self): enc = jwe.JWE(plaintext='plain') self.assertRaises(jwe.InvalidJWEData, enc.add_recipient, jwk.JWK(kty='oct', k=base64url_encode(b'A'*16)), '{"alg":"A128KW"}') def test_aes_128(self): enc = jwe.JWE(plaintext='plain') key128 = jwk.JWK(kty='oct', k=base64url_encode(b'A' * (128 // 8))) enc.add_recipient(key128, '{"alg":"A128KW","enc":"A128CBC-HS256"}') enc.add_recipient(key128, '{"alg":"A128KW","enc":"A128GCM"}') def test_aes_192(self): enc = jwe.JWE(plaintext='plain') key192 = jwk.JWK(kty='oct', k=base64url_encode(b'B' * (192 // 8))) enc.add_recipient(key192, '{"alg":"A192KW","enc":"A192CBC-HS384"}') enc.add_recipient(key192, '{"alg":"A192KW","enc":"A192GCM"}') def test_aes_256(self): enc = jwe.JWE(plaintext='plain') key256 = jwk.JWK(kty='oct', k=base64url_encode(b'C' * (256 // 8))) enc.add_recipient(key256, '{"alg":"A256KW","enc":"A256CBC-HS512"}') enc.add_recipient(key256, '{"alg":"A256KW","enc":"A256GCM"}') def test_jws_loopback(self): sign = jws.JWS(payload='message') sign.add_signature(jwk.JWK(kty='oct', k=base64url_encode(b'A'*16)), alg="HS512") o = sign.serialize() check = jws.JWS() check.deserialize(o, jwk.JWK(kty='oct', k=base64url_encode(b'A'*16)), alg="HS512") self.assertTrue(check.objects['valid']) jwcrypto-0.2.1/jwcrypto/jwe.py0000664000175000017500000006640512540045220021036 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from binascii import hexlify, unhexlify from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import constant_time, hashes, hmac from cryptography.hazmat.primitives.padding import PKCS7 from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from jwcrypto.common import base64url_encode, base64url_decode from jwcrypto.common import InvalidJWAAlgorithm from jwcrypto.common import json_decode, json_encode from jwcrypto.jwk import JWK import os import zlib # RFC 7516 - 4.1 # name: (description, supported?) JWEHeaderRegistry = {'alg': ('Algorithm', True), 'enc': ('Encryption Algorithm', True), 'zip': ('Compression Algorithm', True), 'jku': ('JWK Set URL', False), 'jwk': ('JSON Web Key', False), 'kid': ('Key ID', True), 'x5u': ('X.509 URL', False), 'x5c': ('X.509 Certificate Chain', False), 'x5t': ('X.509 Certificate SHA-1 Thumbprint', False), 'x5t#S256': ('X.509 Certificate SHA-256 Thumbprint', False), 'typ': ('Type', True), 'cty': ('Content Type', True), 'crit': ('Critical', True)} """Registry of valid header parameters""" default_allowed_algs = [ # Key Management Algorithms 'RSA1_5', 'RSA-OAEP', 'RSA-OAEP-256', 'A128KW', 'A192KW', 'A256KW', 'dir', 'ECDH-ES', 'ECDH-ES+A128KW', 'ECDH-ES+A192KW', 'ECDH-ES+A256KW', 'A128GCMKW', 'A192GCMKW', 'A256GCMKW', 'PBES2-HS256+A128KW', 'PBES2-HS384+A192KW', 'PBES2-HS512+A256KW', # Content Encryption Algoritms 'A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512', 'A128GCM', 'A192GCM', 'A256GCM'] """Default allowed algorithms""" # Note: l is the number of bits, which should be a multiple of 16 def _encode_int(n, l): e = hex(n).rstrip("L").lstrip("0x") el = len(e) L = ((l + 7) // 8) * 2 # number of bytes rounded up times 2 chars/bytes if el > L: e = e[:L] else: e = '0' * (L - el) + e # pad as necessary return unhexlify(e) def _decode_int(n): return int(hexlify(n), 16) class InvalidJWEData(Exception): """Invalid JWE Object. This exception is raised when the JWE Object is invalid and/or improperly formatted. """ def __init__(self, message=None, exception=None): msg = None if message: msg = message else: msg = 'Unknown Data Verification Failure' if exception: msg += ' {%s}' % str(exception) super(InvalidJWEData, self).__init__(msg) class InvalidCEKeyLength(Exception): """Invalid CEK Key Length. This exception is raised when a Content Encryption Key does not match the required lenght. """ def __init__(self, expected, obtained): msg = 'Expected key of length %d, got %d' % (expected, obtained) super(InvalidCEKeyLength, self).__init__(msg) class InvalidJWEOperation(Exception): """Invalid JWS Object. This exception is raised when a requested operation cannot be execute due to unsatisfied conditions. """ def __init__(self, message=None, exception=None): msg = None if message: msg = message else: msg = 'Unknown Operation Failure' if exception: msg += ' {%s}' % repr(exception) super(InvalidJWEOperation, self).__init__(msg) class InvalidJWEKeyType(Exception): """Invalid JWE Key Type. This exception is raised when the provided JWK Key does not match the type required by the sepcified algorithm. """ def __init__(self, expected, obtained): msg = 'Expected key type %s, got %s' % (expected, obtained) super(InvalidJWEKeyType, self).__init__(msg) class InvalidJWEKeyLength(Exception): """Invalid JWE Key Length. This exception is raised when the provided JWK Key does not match the lenght required by the sepcified algorithm. """ def __init__(self, expected, obtained): msg = 'Expected key of lenght %d, got %d' % (expected, obtained) super(InvalidJWEKeyLength, self).__init__(msg) class _raw_key_mgmt(object): def wrap(self, key, keylen, cek): raise NotImplementedError def unwrap(self, key, ek): raise NotImplementedError class _rsa(_raw_key_mgmt): def __init__(self, padfn): self.padfn = padfn def check_key(self, key): if key.key_type != 'RSA': raise InvalidJWEKeyType('RSA', key.key_type) # FIXME: get key size and insure > 2048 bits def wrap(self, key, keylen, cek): self.check_key(key) if not cek: cek = os.urandom(keylen) rk = key.get_op_key('encrypt') ek = rk.encrypt(cek, self.padfn) return (cek, ek) def unwrap(self, key, ek): self.check_key(key) rk = key.get_op_key('decrypt') cek = rk.decrypt(ek, self.padfn) return cek class _aes_kw(_raw_key_mgmt): def __init__(self, keysize): self.backend = default_backend() self.keysize = keysize // 8 def get_key(self, key, op): if key.key_type != 'oct': raise InvalidJWEKeyType('oct', key.key_type) rk = base64url_decode(key.get_op_key(op)) if len(rk) != self.keysize: raise InvalidJWEKeyLength(self.keysize * 8, len(rk) * 8) return rk def wrap(self, key, keylen, cek): rk = self.get_key(key, 'encrypt') if not cek: cek = os.urandom(keylen) # Implement RFC 3394 Key Unwrap - 2.2.2 # TODO: Use cryptography once issue #1733 is resolved iv = 'a6a6a6a6a6a6a6a6' A = unhexlify(iv) R = [cek[i:i+8] for i in range(0, len(cek), 8)] n = len(R) for j in range(0, 6): for i in range(0, n): e = Cipher(algorithms.AES(rk), modes.ECB(), backend=self.backend).encryptor() B = e.update(A + R[i]) + e.finalize() A = _encode_int(_decode_int(B[:8]) ^ ((n*j)+i+1), 64) R[i] = B[-8:] ek = A for i in range(0, n): ek += R[i] return (cek, ek) def unwrap(self, key, ek): rk = self.get_key(key, 'decrypt') # Implement RFC 3394 Key Unwrap - 2.2.3 # TODO: Use cryptography once issue #1733 is resolved iv = 'a6a6a6a6a6a6a6a6' Aiv = unhexlify(iv) R = [ek[i:i+8] for i in range(0, len(ek), 8)] A = R.pop(0) n = len(R) for j in range(5, -1, -1): for i in range(n - 1, -1, -1): AtR = _encode_int((_decode_int(A) ^ ((n*j)+i+1)), 64) + R[i] d = Cipher(algorithms.AES(rk), modes.ECB(), backend=self.backend).decryptor() B = d.update(AtR) + d.finalize() A = B[:8] R[i] = B[-8:] if A != Aiv: raise InvalidJWEData('Decryption Failed') cek = b''.join(R) return cek class _direct(_raw_key_mgmt): def check_key(self, key): if key.key_type != 'oct': raise InvalidJWEKeyType('oct', key.key_type) def wrap(self, key, keylen, cek): self.check_key(key) if cek: return (cek, None) k = base64url_decode(key.get_op_key('encrypt')) if len(k) != keylen: raise InvalidCEKeyLength(keylen, len(k)) return (k, '') def unwrap(self, key, ek): self.check_key(key) if ek != b'': raise InvalidJWEData('Invalid Encryption Key.') return base64url_decode(key.get_op_key('decrypt')) class _raw_jwe(object): def encrypt(self, k, a, m): raise NotImplementedError def decrypt(self, k, a, iv, e, t): raise NotImplementedError class _aes_cbc_hmac_sha2(_raw_jwe): def __init__(self, hashfn, keybits): self.backend = default_backend() self.hashfn = hashfn self.keysize = keybits // 8 self.blocksize = algorithms.AES.block_size @property def key_size(self): return self.keysize * 2 def _mac(self, k, a, iv, e): al = _encode_int(len(a * 8), 64) h = hmac.HMAC(k, self.hashfn, backend=self.backend) h.update(a) h.update(iv) h.update(e) h.update(al) m = h.finalize() return m[:self.keysize] # RFC 7518 - 5.2.2 def encrypt(self, k, a, m): """ Encrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authentication Data :param m: Plaintext Returns a dictionary with the computed data. """ hkey = k[:self.keysize] ekey = k[self.keysize:] # encrypt iv = os.urandom(self.blocksize // 8) cipher = Cipher(algorithms.AES(ekey), modes.CBC(iv), backend=self.backend) encryptor = cipher.encryptor() padder = PKCS7(self.blocksize).padder() padded_data = padder.update(m) + padder.finalize() e = encryptor.update(padded_data) + encryptor.finalize() # mac t = self._mac(hkey, a, iv, e) return (iv, e, t) def decrypt(self, k, a, iv, e, t): """ Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication Tag Returns plaintext or raises an error """ hkey = k[:self.keysize] dkey = k[self.keysize:] # verify mac if not constant_time.bytes_eq(t, self._mac(hkey, a, iv, e)): raise InvalidJWEData('Failed to verify MAC') # decrypt cipher = Cipher(algorithms.AES(dkey), modes.CBC(iv), backend=self.backend) decryptor = cipher.decryptor() d = decryptor.update(e) + decryptor.finalize() unpadder = PKCS7(self.blocksize).unpadder() return unpadder.update(d) + unpadder.finalize() class _aes_gcm(_raw_jwe): def __init__(self, keybits): self.backend = default_backend() self.keysize = keybits // 8 @property def key_size(self): return self.keysize # RFC 7518 - 5.3 def encrypt(self, k, a, m): """ Encrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authentication Data :param m: Plaintext Returns a dictionary with the computed data. """ iv = os.urandom(96 // 8) cipher = Cipher(algorithms.AES(k), modes.GCM(iv), backend=self.backend) encryptor = cipher.encryptor() encryptor.authenticate_additional_data(a) e = encryptor.update(m) + encryptor.finalize() return (iv, e, encryptor.tag) def decrypt(self, k, a, iv, e, t): """ Decrypt accoriding to the selected encryption and hashing functions. :param k: Encryption key (optional) :param a: Additional Authenticated Data :param iv: Initialization Vector :param e: Ciphertext :param t: Authentication Tag Returns plaintext or raises an error """ cipher = Cipher(algorithms.AES(k), modes.GCM(iv, t), backend=self.backend) decryptor = cipher.decryptor() decryptor.authenticate_additional_data(a) return decryptor.update(e) + decryptor.finalize() class JWE(object): """JSON Web Encryption object This object represent a JWE token. """ def __init__(self, plaintext=None, protected=None, unprotected=None, aad=None, algs=None): """Creates a JWE token. :param plaintext(bytes): An arbitrary plaintext to be encrypted. :param protected: A JSON string with the protected header. :param unprotected: A JSON string with the shared unprotected header. :param aad(bytes): Arbitrary additional authenticated data :param algs: An optional list of allowed algorithms """ self._allowed_algs = None self.objects = dict() self.plaintext = None if plaintext is not None: if isinstance(plaintext, bytes): self.plaintext = plaintext else: self.plaintext = plaintext.encode('utf-8') self.cek = None self.decryptlog = None if aad: self.objects['aad'] = aad if protected: _ = json_decode(protected) # check header encoding self.objects['protected'] = protected if unprotected: _ = json_decode(unprotected) # check header encoding self.objects['unprotected'] = unprotected if algs: self.allowed_algs = algs # key wrapping mechanisms def _jwa_RSA1_5(self): return _rsa(padding.PKCS1v15()) def _jwa_RSA_OAEP(self): return _rsa(padding.OAEP(padding.MGF1(hashes.SHA1()), hashes.SHA1(), None)) def _jwa_RSA_OAEP_256(self): return _rsa(padding.OAEP(padding.MGF1(hashes.SHA256()), hashes.SHA256(), None)) def _jwa_A128KW(self): return _aes_kw(128) def _jwa_A192KW(self): return _aes_kw(192) def _jwa_A256KW(self): return _aes_kw(256) def _jwa_dir(self): return _direct() # content encryption mechanisms def _jwa_A128CBC_HS256(self): return _aes_cbc_hmac_sha2(hashes.SHA256(), 128) def _jwa_A192CBC_HS384(self): return _aes_cbc_hmac_sha2(hashes.SHA384(), 192) def _jwa_A256CBC_HS512(self): return _aes_cbc_hmac_sha2(hashes.SHA512(), 256) def _jwa_A128GCM(self): return _aes_gcm(128) def _jwa_A192GCM(self): return _aes_gcm(192) def _jwa_A256GCM(self): return _aes_gcm(256) def _jwa(self, name): try: attr = '_jwa_%s' % name.replace('-', '_').replace('+', '_') fn = getattr(self, attr) except (KeyError, AttributeError): raise InvalidJWAAlgorithm() allowed = self._allowed_algs or default_allowed_algs if name not in allowed: raise InvalidJWEOperation('Algorithm not allowed') return fn() @property def allowed_algs(self): """Allowed algorithms. The list of allowed algorithms. Can be changed by setting a list of algorithm names. """ if self._allowed_algs: return self._allowed_algs else: return default_allowed_algs @allowed_algs.setter def allowed_algs(self, algs): if not isinstance(algs, list): raise TypeError('Allowed Algs must be a list') self._allowed_algs = algs def _merge_headers(self, h1, h2): for k in list(h1.keys()): if k in h2: raise InvalidJWEData('Duplicate header: "%s"' % k) h1.update(h2) return h1 def _get_jose_header(self, header=None): jh = dict() if 'protected' in self.objects: ph = json_decode(self.objects['protected']) jh = self._merge_headers(jh, ph) if 'unprotected' in self.objects: uh = json_decode(self.objects['unprotected']) jh = self._merge_headers(jh, uh) if header: rh = json_decode(header) jh = self._merge_headers(jh, rh) return jh def _get_alg_enc_from_headers(self, jh): algname = jh.get('alg', None) if algname is None: raise InvalidJWEData('Missing "alg" from headers') alg = self._jwa(algname) encname = jh.get('enc', None) if encname is None: raise InvalidJWEData('Missing "enc" from headers') enc = self._jwa(encname) return alg, enc def add_recipient(self, key, header=None): """Encrypt the plaintext with the given key. :param key: A JWK key of appropriate type for the 'alg' provided in the JOSE Headers. :param header: A JSON string representing the per-recipient header. :raises ValueError: if the plaintext is missing or not of type bytes. :raises ValueError: if the key is not a JWK object. :raises ValueError: if the compression type is unknown. :raises InvalidJWAAlgorithm: if the 'alg' provided in the JOSE headers is missing or unknown, or otherwise not implemented. """ if self.plaintext is None: raise ValueError('Missing plaintext') if not isinstance(self.plaintext, bytes): raise ValueError("Plaintext must be 'bytes'") if not isinstance(key, JWK): raise ValueError('key is not a JWK object') jh = self._get_jose_header(header) alg, enc = self._get_alg_enc_from_headers(jh) rec = dict() if header: rec['header'] = header self.cek, ek = alg.wrap(key, enc.key_size, self.cek) if ek: rec['encrypted_key'] = ek if 'ciphertext' not in self.objects: aad = base64url_encode(self.objects.get('protected', '')) if 'aad' in self.objects: aad += '.' + base64url_encode(self.objects['aad']) aad = aad.encode('utf-8') compress = jh.get('zip', None) if compress == 'DEF': data = zlib.compress(self.plaintext)[2:-4] elif compress is None: data = self.plaintext else: raise ValueError('Unknown compression') iv, ciphertext, tag = enc.encrypt(self.cek, aad, data) self.objects['iv'] = iv self.objects['ciphertext'] = ciphertext self.objects['tag'] = tag if 'recipients' in self.objects: self.objects['recipients'].append(rec) elif 'encrypted_key' in self.objects or 'header' in self.objects: self.objects['recipients'] = list() n = dict() if 'encrypted_key' in self.objects: n['encrypted_key'] = self.objects['encrypted_key'] del self.objects['encrypted_key'] if 'header' in self.objects: n['header'] = self.objects['header'] del self.objects['header'] self.objects['recipients'].append(n) self.objects['recipients'].append(rec) else: self.objects.update(rec) def serialize(self, compact=False): """Serializes the object into a JWE token. :param compact(boolean): if True generates the compact representation, otherwise generates a standard JSON format. :raises InvalidJWEOperation: if the object cannot serialized with the compact representation and `compat` is True. :raises InvalidJWEOperation: if no recipients have been added to the object. """ if 'ciphertext' not in self.objects: raise InvalidJWEOperation("No available ciphertext") if compact: for invalid in 'aad', 'unprotected': if invalid in self.objects: raise InvalidJWEOperation("Can't use compact encoding") if 'recipiens' in self.objects: if len(self.objects['recipients']) != 1: raise InvalidJWEOperation("Invalid number of recipients") rec = self.objects['recipients'][0] else: rec = self.objects return '.'.join([base64url_encode(self.objects['protected']), base64url_encode(rec.get('encrypted_key', '')), base64url_encode(self.objects['iv']), base64url_encode(self.objects['ciphertext']), base64url_encode(self.objects['tag'])]) else: obj = self.objects enc = {'ciphertext': base64url_encode(obj['ciphertext']), 'iv': base64url_encode(obj['iv']), 'tag': base64url_encode(self.objects['tag'])} if 'protected' in obj: enc['protected'] = base64url_encode(obj['protected']) if 'unprotected' in obj: enc['unprotected'] = json_decode(obj['unprotected']) if 'aad' in obj: enc['aad'] = base64url_encode(obj['aad']) if 'recipients' in obj: enc['recipients'] = list() for rec in obj['recipients']: e = dict() if 'encrypted_key' in rec: e['encrypted_key'] = \ base64url_encode(rec['encrypted_key']) if 'header' in rec: e['header'] = json_decode(rec['header']) enc['recipients'].append(e) else: if 'encrypted_key' in obj: enc['encrypted_key'] = \ base64url_encode(obj['encrypted_key']) if 'header' in obj: enc['header'] = json_decode(obj['header']) return json_encode(enc) def _check_crit(self, crit): for k in crit: if k not in JWEHeaderRegistry: raise InvalidJWEData('Unknown critical header: "%s"' % k) else: if not JWEHeaderRegistry[k][1]: raise InvalidJWEData('Unsupported critical header: ' '"%s"' % k) # FIXME: allow to specify which algorithms to accept as valid def _decrypt(self, key, ppe): jh = self._get_jose_header(ppe.get('header', None)) # TODO: allow caller to specify list of headers it understands self._check_crit(jh.get('crit', dict())) alg = self._jwa(jh.get('alg', None)) enc = self._jwa(jh.get('enc', None)) aad = base64url_encode(self.objects.get('protected', '')) if 'aad' in self.objects: aad += '.' + base64url_encode(self.objects['aad']) cek = alg.unwrap(key, ppe.get('encrypted_key', b'')) data = enc.decrypt(cek, aad.encode('utf-8'), self.objects['iv'], self.objects['ciphertext'], self.objects['tag']) self.decryptlog.append('Success') self.cek = cek compress = jh.get('zip', None) if compress == 'DEF': self.plaintext = zlib.decompress(data, -zlib.MAX_WBITS) elif compress is None: self.plaintext = data else: raise ValueError('Unknown compression') def decrypt(self, key): """Decrypt a JWE token. :param key: The (:class:`jwcrypto.jwk.JWK`) decryption key. :raises InvalidJWEOperation: if the key is not a JWK object. :raises InvalidJWEData: if the ciphertext can't be decrypted or the object is otherwise malformed. """ if not isinstance(key, JWK): raise ValueError('key is not a JWK object') if 'ciphertext' not in self.objects: raise InvalidJWEOperation("No available ciphertext") self.decryptlog = list() if 'recipients' in self.objects: for rec in self.objects['recipients']: try: self._decrypt(key, rec) except Exception as e: # pylint: disable=broad-except self.decryptlog.append('Failed: [%s]' % repr(e)) else: try: self._decrypt(key, self.objects) except Exception as e: # pylint: disable=broad-except self.decryptlog.append('Failed: [%s]' % repr(e)) if not self.plaintext: raise InvalidJWEData('No recipient matched the provided ' 'key' + repr(self.decryptlog)) def deserialize(self, raw_jwe, key=None): """Deserialize a JWE token. NOTE: Destroys any current status and tries to import the raw JWE provided. :param raw_jwe: a 'raw' JWE token (JSON Encoded or Compact notation) string. :param key: A (:class:`jwcrypto.jwk.JWK`) decryption key (optional). If a key is provided a idecryption step will be attempted after the object is successfully deserialized. :raises InvalidJWEData: if the raw object is an invaid JWE token. :raises InvalidJWEOperation: if the decryption fails. """ self.objects = dict() self.plaintext = None self.cek = None o = dict() try: try: djwe = json_decode(raw_jwe) o['iv'] = base64url_decode(str(djwe['iv'])) o['ciphertext'] = base64url_decode(str(djwe['ciphertext'])) o['tag'] = base64url_decode(str(djwe['tag'])) if 'protected' in djwe: p = base64url_decode(str(djwe['protected'])) o['protected'] = p.decode('utf-8') if 'unprotected' in djwe: o['unprotected'] = json_encode(djwe['unprotected']) if 'aad' in djwe: o['aad'] = base64url_decode(str(djwe['aad'])) if 'recipients' in djwe: o['recipients'] = list() for rec in djwe['recipients']: e = dict() if 'encrypted_key' in rec: e['encrypted_key'] = \ base64url_decode(str(rec['encrypted_key'])) if 'header' in rec: e['header'] = json_encode(rec['header']) o['recipients'].append(e) else: if 'encrypted_key' in djwe: o['encrypted_key'] = \ base64url_decode(str(djwe['encrypted_key'])) if 'header' in djwe: o['header'] = json_encode(djwe['header']) except ValueError: c = raw_jwe.split('.') if len(c) != 5: raise InvalidJWEData() p = base64url_decode(str(c[0])) o['protected'] = p.decode('utf-8') ekey = base64url_decode(str(c[1])) if ekey != '': o['encrypted_key'] = base64url_decode(str(c[1])) o['iv'] = base64url_decode(str(c[2])) o['ciphertext'] = base64url_decode(str(c[3])) o['tag'] = base64url_decode(str(c[4])) self.objects = o except Exception as e: # pylint: disable=broad-except raise InvalidJWEData('Invalid format', repr(e)) if key: self.decrypt(key) @property def payload(self): if not self.plaintext: raise InvalidJWEOperation("Plaintext not available") return self.plaintext @property def jose_header(self): jh = self._get_jose_header() if len(jh) == 0: raise InvalidJWEOperation("JOSE Header not available") return jh jwcrypto-0.2.1/jwcrypto/jws.py0000664000175000017500000005641312575550302021064 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from binascii import hexlify, unhexlify from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, hmac from cryptography.hazmat.primitives.asymmetric import padding from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.asymmetric import utils as ec_utils from cryptography.exceptions import InvalidSignature from jwcrypto.common import base64url_encode, base64url_decode from jwcrypto.common import InvalidJWAAlgorithm from jwcrypto.common import json_decode, json_encode from jwcrypto.jwk import JWK # RFC 7515 - 9.1 # name: (description, supported?) JWSHeaderRegistry = {'alg': ('Algorithm', True), 'jku': ('JWK Set URL', False), 'jwk': ('JSON Web Key', False), 'kid': ('Key ID', True), 'x5u': ('X.509 URL', False), 'x5c': ('X.509 Certificate Chain', False), 'x5t': ('X.509 Certificate SHA-1 Thumbprint', False), 'x5t#S256': ('X.509 Certificate SHA-256 Thumbprint', False), 'typ': ('Type', True), 'cty': ('Content Type', True), 'crit': ('Critical', True)} """Registry of valid header parameters""" default_allowed_algs = [ 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'PS256', 'PS384', 'PS512'] """Default allowed algorithms""" class InvalidJWSSignature(Exception): """Invalid JWS Signature. This exception is raised when a signature cannot be validated. """ def __init__(self, message=None, exception=None): msg = None if message: msg = str(message) else: msg = 'Unknown Signature Verification Failure' if exception: msg += ' {%s}' % str(exception) super(InvalidJWSSignature, self).__init__(msg) class InvalidJWSObject(Exception): """Invalid JWS Object. This exception is raised when the JWS Object is invalid and/or improperly formatted. """ def __init__(self, message=None, exception=None): msg = 'Invalid JWS Object' if message: msg += ' [%s]' % message if exception: msg += ' {%s}' % str(exception) super(InvalidJWSObject, self).__init__(msg) class InvalidJWSOperation(Exception): """Invalid JWS Object. This exception is raised when a requested operation cannot be execute due to unsatisfied conditions. """ def __init__(self, message=None, exception=None): msg = None if message: msg = message else: msg = 'Unknown Operation Failure' if exception: msg += ' {%s}' % str(exception) super(InvalidJWSOperation, self).__init__(msg) class _raw_jws(object): def sign(self, key, payload): raise NotImplementedError def verify(self, key, payload, signature): raise NotImplementedError class _raw_hmac(_raw_jws): def __init__(self, hashfn): self.backend = default_backend() self.hashfn = hashfn def _hmac_setup(self, key, payload): h = hmac.HMAC(key, self.hashfn, backend=self.backend) h.update(payload) return h def sign(self, key, payload): skey = base64url_decode(key.get_op_key('sign')) h = self._hmac_setup(skey, payload) return h.finalize() def verify(self, key, payload, signature): vkey = base64url_decode(key.get_op_key('verify')) h = self._hmac_setup(vkey, payload) try: h.verify(signature) except InvalidSignature as e: raise InvalidJWSSignature(exception=e) class _raw_rsa(_raw_jws): def __init__(self, padfn, hashfn): self.padfn = padfn self.hashfn = hashfn def sign(self, key, payload): skey = key.get_op_key('sign') signer = skey.signer(self.padfn, self.hashfn) signer.update(payload) return signer.finalize() def verify(self, key, payload, signature): pkey = key.get_op_key('verify') verifier = pkey.verifier(signature, self.padfn, self.hashfn) verifier.update(payload) verifier.verify() class _raw_ec(_raw_jws): def __init__(self, curve, hashfn): self.curve = curve self.hashfn = hashfn def encode_int(self, n, l): e = hex(n).rstrip("L").lstrip("0x") L = (l + 7) // 8 # number of bytes rounded up e = '0' * (L * 2 - len(e)) + e # pad as necessary return unhexlify(e) def sign(self, key, payload): skey = key.get_op_key('sign', self.curve) signer = skey.signer(ec.ECDSA(self.hashfn)) signer.update(payload) signature = signer.finalize() r, s = ec_utils.decode_rfc6979_signature(signature) l = key.get_curve(self.curve).key_size return self.encode_int(r, l) + self.encode_int(s, l) def verify(self, key, payload, signature): pkey = key.get_op_key('verify', self.curve) r = signature[:len(signature)//2] s = signature[len(signature)//2:] enc_signature = ec_utils.encode_rfc6979_signature( int(hexlify(r), 16), int(hexlify(s), 16)) verifier = pkey.verifier(enc_signature, ec.ECDSA(self.hashfn)) verifier.update(payload) verifier.verify() class _raw_none(_raw_jws): def sign(self, key, payload): return '' def verify(self, key, payload, signature): if signature != b'': raise InvalidJWSSignature('The "none" signature must be the ' 'empty string') class JWSCore(object): """The inner JWS Core object. This object SHOULD NOT be used directly, the JWS object should be used instead as JWS perform necessary checks on the validity of the object and requested operations. """ def __init__(self, alg, key, header, payload, algs=None): """Core JWS token handling. :param alg: The algorithm used to produce the signature. See RFC 7518 :param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate type for the "alg" provided in the 'protected' json string. :param header: A JSON string representing the protected header. :param payload(bytes): An arbitrary value :param algs: An optional list of allowed algorithms :raises ValueError: if the key is not a :class:`JWK` object :raises InvalidJWAAlgorithm: if the algorithm is not valid, is unknown or otherwise not yet implemented. """ self.alg = alg self.engine = self._jwa(alg, algs) if not isinstance(key, JWK): raise ValueError('key is not a JWK object') self.key = key if header is not None: self.protected = base64url_encode(header.encode('utf-8')) else: self.protected = '' self.payload = base64url_encode(payload) def _jwa_HS256(self): return _raw_hmac(hashes.SHA256()) def _jwa_HS384(self): return _raw_hmac(hashes.SHA384()) def _jwa_HS512(self): return _raw_hmac(hashes.SHA512()) def _jwa_RS256(self): return _raw_rsa(padding.PKCS1v15(), hashes.SHA256()) def _jwa_RS384(self): return _raw_rsa(padding.PKCS1v15(), hashes.SHA384()) def _jwa_RS512(self): return _raw_rsa(padding.PKCS1v15(), hashes.SHA512()) def _jwa_ES256(self): return _raw_ec('P-256', hashes.SHA256()) def _jwa_ES384(self): return _raw_ec('P-384', hashes.SHA384()) def _jwa_ES512(self): return _raw_ec('P-521', hashes.SHA512()) def _jwa_PS256(self): return _raw_rsa(padding.PSS(padding.MGF1(hashes.SHA256()), hashes.SHA256.digest_size), hashes.SHA256()) def _jwa_PS384(self): return _raw_rsa(padding.PSS(padding.MGF1(hashes.SHA384()), hashes.SHA384.digest_size), hashes.SHA384()) def _jwa_PS512(self): return _raw_rsa(padding.PSS(padding.MGF1(hashes.SHA512()), hashes.SHA512.digest_size), hashes.SHA512()) def _jwa_none(self): return _raw_none() def _jwa(self, name, allowed): if allowed is None: allowed = default_allowed_algs attr = '_jwa_%s' % name try: fn = getattr(self, attr) except (KeyError, AttributeError): raise InvalidJWAAlgorithm() if name not in allowed: raise InvalidJWSOperation('Algorithm not allowed') return fn() def sign(self): """Generates a signature""" sigin = ('.'.join([self.protected, self.payload])).encode('utf-8') signature = self.engine.sign(self.key, sigin) return {'protected': self.protected, 'payload': self.payload, 'signature': base64url_encode(signature)} def verify(self, signature): """Verifies a signature :raises InvalidJWSSignature: if the verification fails. """ try: sigin = ('.'.join([self.protected, self.payload])).encode('utf-8') self.engine.verify(self.key, sigin, signature) except Exception as e: # pylint: disable=broad-except raise InvalidJWSSignature('Verification failed', repr(e)) return True class JWS(object): """JSON Web Signature object This object represent a JWS token. """ def __init__(self, payload=None): """Creates a JWS object. :param payload(bytes): An arbitrary value (optional). """ self.objects = dict() if payload: self.objects['payload'] = payload self.verifylog = None self._allowed_algs = None def _check_crit(self, crit): for k in crit: if k not in JWSHeaderRegistry: raise InvalidJWSSignature('Unknown critical header: ' '"%s"' % k) else: if not JWSHeaderRegistry[k][1]: raise InvalidJWSSignature('Unsupported critical ' 'header: "%s"' % k) @property def allowed_algs(self): """Allowed algorithms. The list of allowed algorithms. Can be changed by setting a list of algorithm names. """ if self._allowed_algs: return self._allowed_algs else: return default_allowed_algs @allowed_algs.setter def allowed_algs(self, algs): if not isinstance(algs, list): raise TypeError('Allowed Algs must be a list') self._allowed_algs = algs @property def is_valid(self): return self.objects.get('valid', False) def _merge_headers(self, h1, h2): for k in list(h1.keys()): if k in h2: raise InvalidJWSObject('Duplicate header: "%s"' % k) h1.update(h2) return h1 # TODO: support selecting key with 'kid' and passing in multiple keys def _verify(self, alg, key, payload, signature, protected, header=None): # verify it is a valid JSON object and keep a decode copy if protected is not None: p = json_decode(protected) else: p = dict() if not isinstance(p, dict): raise InvalidJWSSignature('Invalid Protected header') # merge heders, and verify there are no duplicates if header: h = json_decode(header) if not isinstance(h, dict): raise InvalidJWSSignature('Invalid Unprotected header') p = self._merge_headers(p, h) # verify critical headers # TODO: allow caller to specify list of headers it understands if 'crit' in p: self._check_crit(p['crit']) # check 'alg' is present if alg is None and 'alg' not in p: raise InvalidJWSSignature('No "alg" in headers') if alg: if 'alg' in p and alg != p['alg']: raise InvalidJWSSignature('"alg" mismatch, requested ' '"%s", found "%s"' % (alg, p['alg'])) a = alg else: a = p['alg'] # the following will verify the "alg" is supported and the signature # verifies S = JWSCore(a, key, protected, payload, self._allowed_algs) S.verify(signature) def verify(self, key, alg=None): """Verifies a JWS token. :param key: The (:class:`jwcrypto.jwk.JWK`) verification key. :param alg: The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token. :raises InvalidJWSSignature: if the verification fails. """ self.verifylog = list() self.objects['valid'] = False obj = self.objects if 'signature' in obj: try: self._verify(alg, key, obj['payload'], obj['signature'], obj.get('protected', None), obj.get('header', None)) obj['valid'] = True except Exception as e: # pylint: disable=broad-except self.verifylog.append('Failed: [%s]' % repr(e)) elif 'signatures' in obj: for o in obj['signatures']: try: self._verify(alg, key, obj['payload'], o['signature'], o.get('protected', None), o.get('header', None)) # Ok if at least one verifies obj['valid'] = True except Exception as e: # pylint: disable=broad-except self.verifylog.append('Failed: [%s]' % repr(e)) else: raise InvalidJWSSignature('No signatures availble') if not self.is_valid: raise InvalidJWSSignature('Verification failed for all ' 'signatures' + repr(self.verifylog)) def deserialize(self, raw_jws, key=None, alg=None): """Deserialize a JWS token. NOTE: Destroys any current status and tries to import the raw JWS provided. :param raw_jws: a 'raw' JWS token (JSON Encoded or Compact notation) string. :param key: A (:class:`jwcrypto.jwk.JWK`) verification key (optional). If a key is provided a verification step will be attempted after the object is successfully deserialized. :param alg: The signing algorithm (optional). usually the algorithm is known as it is provided with the JOSE Headers of the token. :raises InvalidJWSObject: if the raw object is an invaid JWS token. :raises InvalidJWSSignature: if the verification fails. """ self.objects = dict() o = dict() try: try: djws = json_decode(raw_jws) o['payload'] = base64url_decode(str(djws['payload'])) if 'signatures' in djws: o['signatures'] = list() for s in djws['signatures']: os = dict() os['signature'] = base64url_decode(str(s['signature'])) if 'protected' in s: p = base64url_decode(str(s['protected'])) os['protected'] = p.decode('utf-8') if 'header' in s: os['header'] = json_encode(s['header']) o['signatures'].append(os) else: o['signature'] = base64url_decode(str(djws['signature'])) if 'protected' in djws: p = base64url_decode(str(djws['protected'])) o['protected'] = p.decode('utf-8') if 'header' in djws: o['header'] = json_encode(djws['header']) except ValueError: c = raw_jws.split('.') if len(c) != 3: raise InvalidJWSObject('Unrecognized representation') p = base64url_decode(str(c[0])) if len(p) > 0: o['protected'] = p.decode('utf-8') o['payload'] = base64url_decode(str(c[1])) o['signature'] = base64url_decode(str(c[2])) self.objects = o except Exception as e: # pylint: disable=broad-except raise InvalidJWSObject('Invalid format', repr(e)) if key: self.verify(key, alg) def add_signature(self, key, alg=None, protected=None, header=None): """Adds a new signature to the object. :param key: A (:class:`jwcrypto.jwk.JWK`) key of appropriate for the "alg" provided. :param alg: An optional algorithm name. If already provided as an element of the protected or unprotected header it can be safely omitted. :param potected: The Protected Header (optional) :param header: The Unprotected Header (optional) :raises InvalidJWSObject: if no payload has been set on the object. :raises ValueError: if the key is not a :class:`JWK` object. :raises ValueError: if the algorithm is missing or is not provided by one of the headers. :raises InvalidJWAAlgorithm: if the algorithm is not valid, is unknown or otherwise not yet implemented. """ if not self.objects.get('payload', None): raise InvalidJWSObject('Missing Payload') p = dict() if protected: p = json_decode(protected) # TODO: allow caller to specify list of headers it understands if 'crit' in p: self._check_crit(p['crit']) if header: h = json_decode(header) p = self._merge_headers(p, h) if 'alg' in p: if alg is None: alg = p['alg'] elif alg != p['alg']: raise ValueError('"alg" value mismatch, specified "alg" ' 'does not match JOSE header value') if alg is None: raise ValueError('"alg" not specified') S = JWSCore(alg, key, protected, self.objects['payload']) sig = S.sign() o = dict() o['signature'] = base64url_decode(sig['signature']) if protected: o['protected'] = protected if header: o['header'] = h o['valid'] = True if 'signatures' in self.objects: self.objects['signatures'].append(o) elif 'signature' in self.objects: self.objects['signatures'] = list() n = dict() n['signature'] = self.objects['signature'] del self.objects['signature'] if 'protected' in self.objects: n['protected'] = self.objects['protected'] del self.objects['protected'] if 'header' in self.objects: n['header'] = self.objects['header'] del self.objects['header'] if 'valid' in self.objects: n['valid'] = self.objects['valid'] del self.objects['valid'] self.objects['signatures'].append(n) self.objects['signatures'].append(o) else: self.objects.update(o) def serialize(self, compact=False): """Serializes the object into a JWS token. :param compact(boolean): if True generates the compact representation, otherwise generates a standard JSON format. :raises InvalidJWSOperation: if the object cannot serialized with the compact representation and `compat` is True. :raises InvalidJWSSignature: if no signature has been added to the object, or no valid signature can be found. """ if compact: if 'signatures' in self.objects: raise InvalidJWSOperation("Can't use compact encoding with " "multiple signatures") if 'signature' not in self.objects: raise InvalidJWSSignature("No available signature") if not self.objects.get('valid', False): raise InvalidJWSSignature("No valid signature found") if 'protected' in self.objects: protected = base64url_encode(self.objects['protected']) else: protected = '' return '.'.join([protected, base64url_encode(self.objects['payload']), base64url_encode(self.objects['signature'])]) else: obj = self.objects if 'signature' in obj: if not obj.get('valid', False): raise InvalidJWSSignature("No valid signature found") sig = {'payload': base64url_encode(obj['payload']), 'signature': base64url_encode(obj['signature'])} if 'protected' in obj: sig['protected'] = base64url_encode(obj['protected']) if 'header' in obj: sig['header'] = obj['header'] elif 'signatures' in obj: sig = {'payload': base64url_encode(obj['payload']), 'signatures': list()} for o in obj['signatures']: if not o.get('valid', False): continue s = {'signature': base64url_encode(o['signature'])} if 'protected' in o: s['protected'] = base64url_encode(o['protected']) if 'header' in o: s['header'] = o['header'] sig['signatures'].append(s) if len(sig['signatures']) == 0: raise InvalidJWSSignature("No valid signature found") else: raise InvalidJWSSignature("No available signature") return json_encode(sig) @property def payload(self): if 'payload' not in self.objects: raise InvalidJWSOperation("Payload not available") if not self.is_valid: raise InvalidJWSOperation("Payload not verified") return self.objects['payload'] @property def jose_header(self): obj = self.objects if 'signature' in obj: jh = dict() if 'protected' in obj: p = json_decode(obj['protected']) jh = self._merge_headers(jh, p) jh = self._merge_headers(jh, obj.get('header', dict())) return jh elif 'signatures' in self.objects: jhl = list() for o in obj['signatures']: jh = dict() if 'protected' in obj: p = json_decode(o['protected']) jh = self._merge_headers(jh, p) jh = self._merge_headers(jh, o.get('header', dict())) jhl.append(jh) return jhl else: raise InvalidJWSOperation("JOSE Header(s) not available") jwcrypto-0.2.1/jwcrypto/common.py0000664000175000017500000000232512540045220021530 0ustar puiterwijkpuiterwijk00000000000000# Copyright (C) 2015 JWCrypto Project Contributors - see LICENSE file from base64 import urlsafe_b64encode, urlsafe_b64decode import json # Padding stripping versions as described in # RFC 7515 Appendix C def base64url_encode(payload): if not isinstance(payload, bytes): payload = payload.encode('utf-8') encode = urlsafe_b64encode(payload) return encode.decode('utf-8').rstrip('=') def base64url_decode(payload): l = len(payload) % 4 if l == 2: payload += '==' elif l == 3: payload += '=' elif l != 0: raise ValueError('Invalid base64 string') return urlsafe_b64decode(payload.encode('utf-8')) # JSON encoding/decoding helpers with good defaults def json_encode(string): if isinstance(string, bytes): string = string.decode('utf-8') return json.dumps(string, separators=(',', ':')) def json_decode(string): if isinstance(string, bytes): string = string.decode('utf-8') return json.loads(string) class InvalidJWAAlgorithm(Exception): def __init__(self, message=None): msg = 'Invalid JWS Algorithm name' if message: msg += ' (%s)' % message super(InvalidJWAAlgorithm, self).__init__(msg) jwcrypto-0.2.1/LICENSE0000664000175000017500000001674312540023424017025 0ustar puiterwijkpuiterwijk00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. jwcrypto-0.2.1/MANIFEST.in0000664000175000017500000000003212540045220017534 0ustar puiterwijkpuiterwijk00000000000000include LICENSE README.md jwcrypto-0.2.1/setup.py0000775000175000017500000000137412575550302017537 0ustar puiterwijkpuiterwijk00000000000000#!/usr/bin/python # # Copyright (C) 2015 JWCrypto Project Contributors, see LICENSE file from setuptools import setup setup( name = 'jwcrypto', version = '0.2.1', license = 'LGPLv3+', maintainer = 'JWCrypto Project Contributors', maintainer_email = 'simo@redhat.com', url='https://github.com/simo5/jwcrypto', packages = ['jwcrypto'], description = 'Implementation of JOSE Web standards', classifiers = [ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Intended Audience :: Developers', 'Topic :: Security', 'Topic :: Software Development :: Libraries :: Python Modules' ], data_files = [('share/doc/jwcrypto', ['LICENSE', 'README.md'])], ) jwcrypto-0.2.1/PKG-INFO0000664000175000017500000000100212575550334017110 0ustar puiterwijkpuiterwijk00000000000000Metadata-Version: 1.1 Name: jwcrypto Version: 0.2.1 Summary: Implementation of JOSE Web standards Home-page: https://github.com/simo5/jwcrypto Author: JWCrypto Project Contributors Author-email: simo@redhat.com License: LGPLv3+ Description: UNKNOWN Platform: UNKNOWN Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3.3 Classifier: Intended Audience :: Developers Classifier: Topic :: Security Classifier: Topic :: Software Development :: Libraries :: Python Modules