コード例 #1
0
    def test_cose_usage_examples_cose_encrypt_ecdh_ss_a128kw(self):

        # The sender side:
        enc_key = COSEKey.from_symmetric_key(alg="A128GCM")
        nonce = enc_key.generate_nonce()
        r = Recipient.from_jwk({
            "kty":
            "EC",
            "crv":
            "P-256",
            "alg":
            "ECDH-SS+A128KW",
            "x":
            "7cvYCcdU22WCwW1tZXR8iuzJLWGcd46xfxO1XJs-SPU",
            "y":
            "DzhJXgz9RI6TseNmwEfLoNVns8UmvONsPzQDop2dKoo",
            "d":
            "Uqr4fay_qYQykwcNCB2efj_NFaQRRQ-6fHZm763jt5w",
        })
        pub_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "crv":
            "P-256",
            "kid":
            "*****@*****.**",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
        })
        r.apply(enc_key, recipient_key=pub_key, context={"alg": "A128GCM"})
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_encrypt(
            b"Hello world!",
            key=enc_key,
            nonce=nonce,
            recipients=[r],
        )

        # The recipient side:
        priv_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "crv":
            "P-256",
            "alg":
            "ECDH-SS+A128KW",
            "kid":
            "*****@*****.**",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
            "d":
            "r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8",
        })
        assert b"Hello world!" == ctx.decode(encoded,
                                             priv_key,
                                             context={"alg": "A128GCM"})
コード例 #2
0
    def test_cose_decode_mac_with_multiple_keys_without_kid(self, ctx):
        key = COSEKey.from_symmetric_key(alg="HS256")

        material1 = base64.urlsafe_b64encode(token_bytes(16)).decode()
        material2 = base64.urlsafe_b64encode(token_bytes(16)).decode()
        material3 = base64.urlsafe_b64encode(token_bytes(16)).decode()

        r1 = Recipient.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material1
        })
        r2 = Recipient.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material2
        })
        r1.apply(key)
        r2.apply(key)

        encoded = ctx.encode_and_mac(b"Hello world!", key, recipients=[r2, r1])

        shared_key1 = COSEKey.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material1
        })
        shared_key3 = COSEKey.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material3
        })
        assert b"Hello world!" == ctx.decode(encoded,
                                             keys=[shared_key3, shared_key1])
コード例 #3
0
    def test_cose_decode_mac_with_different_multiple_keys_2(self):
        ctx = COSE.new(alg_auto_inclusion=True, verify_kid=True)
        key = COSEKey.from_symmetric_key(alg="HS256")

        material1 = base64.urlsafe_b64encode(token_bytes(16)).decode()
        material2 = base64.urlsafe_b64encode(token_bytes(16)).decode()
        material3 = base64.urlsafe_b64encode(token_bytes(16)).decode()

        r2 = Recipient.from_jwk({
            "kid": "03",
            "kty": "oct",
            "alg": "A128KW",
            "k": material2
        })
        r2.apply(key)

        encoded = ctx.encode_and_mac(b"Hello world!", key, recipients=[r2])

        shared_key1 = COSEKey.from_jwk({
            "kid": "01",
            "kty": "oct",
            "alg": "A128KW",
            "k": material1
        })
        shared_key3 = COSEKey.from_jwk({
            "kid": "02",
            "kty": "oct",
            "alg": "A128KW",
            "k": material3
        })

        with pytest.raises(ValueError) as err:
            ctx.decode(encoded, keys=[shared_key1, shared_key3])
            pytest.fail("decode() should fail.")
        assert "key is not found." in str(err.value)
コード例 #4
0
ファイル: test_cwt_sample.py プロジェクト: dajiaji/python-cwt
    def test_sample_readme_signed_cwt_ed25519_with_jwk(self):

        # The sender side:
        private_key = COSEKey.from_jwk(
            {
                "kid": "01",
                "kty": "OKP",
                "key_ops": ["sign"],
                "alg": "EdDSA",
                "crv": "Ed25519",
                "x": "2E6dX83gqD_D0eAmqnaHe1TC1xuld6iAKXfw2OVATr0",
                "d": "L8JS08VsFZoZxGa9JvzYmCWOwg7zaKcei3KZmYsj7dc",
            }
        )
        token = cwt.encode({"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"}, private_key)

        # The recipient side:
        public_key = COSEKey.from_jwk(
            {
                "kid": "01",
                "kty": "OKP",
                "key_ops": ["verify"],
                "crv": "Ed25519",
                "x": "2E6dX83gqD_D0eAmqnaHe1TC1xuld6iAKXfw2OVATr0",
            }
        )
        decoded = cwt.decode(token, public_key)
        assert 1 in decoded and decoded[1] == "coaps://as.example"
コード例 #5
0
    def test_cose_wg_examples_ecdh_wrap_p256_ss_wrap_128_01(self):
        # The sender side:
        enc_key = COSEKey.from_symmetric_key(
            # bytes.fromhex("B2353161740AACF1F7163647984B522A"),
            alg="A128GCM", )
        rec = Recipient.from_jwk({
            "kty":
            "EC",
            "crv":
            "P-256",
            "alg":
            "ECDH-SS+A128KW",
            "x":
            "7cvYCcdU22WCwW1tZXR8iuzJLWGcd46xfxO1XJs-SPU",
            "y":
            "DzhJXgz9RI6TseNmwEfLoNVns8UmvONsPzQDop2dKoo",
            "d":
            "Uqr4fay_qYQykwcNCB2efj_NFaQRRQ-6fHZm763jt5w",
        })
        pub_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "crv":
            "P-256",
            "kid":
            "*****@*****.**",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
            # "d":"r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8"
        })
        rec.apply(enc_key, recipient_key=pub_key, context={"alg": "A128GCM"})
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_encrypt(
            b"This is the content.",
            key=enc_key,
            nonce=b"\x02\xd1\xf7\xe6\xf2lC\xd4\x86\x8d\x87\xce",
            recipients=[rec],
        )

        # The recipient side:
        priv_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "crv":
            "P-256",
            "alg":
            "ECDH-SS+A128KW",
            "kid":
            "*****@*****.**",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
            "d":
            "r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8",
        })
        assert b"This is the content." == ctx.decode(
            encoded, priv_key, context={"alg": "A128GCM"})
コード例 #6
0
 def test_key_builder_from_jwk_with_byte_formatted_kid(self):
     try:
         with open(key_path("public_key_ed25519.json")) as key_file:
             obj = json.loads(key_file.read())
             obj["kid"] = b"01"
             COSEKey.from_jwk(obj)
     except Exception:
         pytest.fail("from_jwk should not fail.")
コード例 #7
0
 def test_key_builder_from_jwk_without_use(self):
     try:
         with open(key_path("public_key_ed25519.json")) as key_file:
             obj = json.loads(key_file.read())
             del obj["use"]
             COSEKey.from_jwk(obj)
     except Exception:
         pytest.fail("from_jwk should not fail.")
コード例 #8
0
    def test_cose_usage_examples_cose_encrypt_ecdh_aes_key_wrap(self):

        enc_key = COSEKey.from_symmetric_key(alg="A128GCM")
        r = Recipient.from_jwk(
            {
                "kty": "EC",
                "alg": "ECDH-ES+A128KW",
                "crv": "P-256",
            }, )
        pub_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "alg":
            "ECDH-ES+A128KW",
            "kid":
            "01",
            "crv":
            "P-256",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
        })
        r.apply(enc_key, recipient_key=pub_key, context={"alg": "A128GCM"})
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_encrypt(
            b"Hello world!",
            key=enc_key,
            recipients=[r],
        )
        priv_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "alg":
            "ECDH-ES+A128KW",
            "kid":
            "01",
            "crv":
            "P-256",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
            "d":
            "r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8",
        })
        assert b"Hello world!" == ctx.decode(encoded,
                                             priv_key,
                                             context={"alg": "A128GCM"})
コード例 #9
0
    def test_cose_usage_examples_cose_signature1(self):

        priv_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "kid":
            "01",
            "crv":
            "P-256",
            "x":
            "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8",
            "y":
            "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4",
            "d":
            "V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM",
        })
        ctx = COSE.new(alg_auto_inclusion=True, kid_auto_inclusion=True)
        encoded = ctx.encode_and_sign(b"Hello world!", priv_key)

        pub_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "kid":
            "01",
            "crv":
            "P-256",
            "x":
            "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8",
            "y":
            "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4",
        })
        assert b"Hello world!" == ctx.decode(encoded, pub_key)

        ctx = COSE.new()
        encoded2 = ctx.encode_and_sign(
            b"Hello world!",
            priv_key,
            protected={"alg": "ES256"},
            unprotected={"kid": "01"},
        )
        assert b"Hello world!" == ctx.decode(encoded2, pub_key)

        encoded3 = ctx.encode_and_sign(
            b"Hello world!",
            priv_key,
            protected={1: -7},
            unprotected={4: b"01"},
        )
        assert b"Hello world!" == ctx.decode(encoded3, pub_key)
コード例 #10
0
 def test_key_builder_from_jwk_with_encode(self, private_key_path,
                                           public_key_path):
     with open(key_path(private_key_path)) as key_file:
         private_key = COSEKey.from_jwk(key_file.read())
     with open(key_path(public_key_path)) as key_file:
         public_key = COSEKey.from_jwk(key_file.read())
     token = cwt.encode(
         {
             "iss": "coaps://as.example",
             "sub": "dajiaji",
             "cti": "123"
         },
         private_key,
     )
     decoded = cwt.decode(token, public_key)
     assert 1 in decoded and decoded[1] == "coaps://as.example"
コード例 #11
0
ファイル: test_signer.py プロジェクト: dajiaji/python-cwt
 def test_signer_new(self):
     signer = Signer.new(
         cose_key=COSEKey.from_jwk({
             "kty":
             "EC",
             "kid":
             "01",
             "crv":
             "P-256",
             "x":
             "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8",
             "y":
             "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4",
             "d":
             "V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM",
         }),
         protected={"alg": "ES256"},
         unprotected={"kid": "01"},
     )
     assert signer.unprotected[4] == b"01"
     assert cbor2.loads(signer.protected)[1] == -7
     assert signer.cose_key.alg == -7
     assert signer.cose_key.kid == b"01"
     try:
         signer.sign(b"Hello world!")
         signer.verify(b"Hello world!")
     except Exception:
         pytest.fail("signer.sign and verify should not fail.")
コード例 #12
0
 def test_cose_wg_examples_sign1_pass_02(self):
     cwt_str = "D28443A10126A10442313154546869732069732074686520636F6E74656E742E584010729CD711CB3813D8D8E944A8DA7111E7B258C9BDCA6135F7AE1ADBEE9509891267837E1E33BD36C150326AE62755C6BD8E540C3E8F92D7D225E8DB72B8820B"
     key = COSEKey.from_jwk({
         "kty":
         "EC",
         "kid":
         "11",
         "crv":
         "P-256",
         "x":
         "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8",
         "y":
         "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4",
         "d":
         "V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM",
     })
     ctx = COSE.new()
     encoded = ctx.encode_and_sign(
         b"This is the content.",
         key,
         protected={1: -7},
         unprotected={4: b"11"},
         external_aad=bytes.fromhex("11aa22bb33cc44dd55006699"),
     )
     assert ctx.decode(
         encoded,
         key,
         external_aad=bytes.fromhex(
             "11aa22bb33cc44dd55006699")) == b"This is the content."
     assert (ctx.decode(
         bytes.fromhex(cwt_str),
         key,
         external_aad=bytes.fromhex("11aa22bb33cc44dd55006699"),
     ) == b"This is the content.")
コード例 #13
0
 def test_cose_wg_examples_eddsa_sig_01(self):
     cwt_str = "D28445A201270300A10442313154546869732069732074686520636F6E74656E742E58407142FD2FF96D56DB85BEE905A76BA1D0B7321A95C8C4D3607C5781932B7AFB8711497DFA751BF40B58B3BCC32300B1487F3DB34085EEF013BF08F4A44D6FEF0D"
     key = COSEKey.from_jwk({
         "kty":
         "OKP",
         "kid":
         "11",
         "crv":
         "Ed25519",
         "x":
         base64.urlsafe_b64encode(
             bytes.fromhex(
                 "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a"
             )).replace(b"=", b"").decode("ascii"),
         "d":
         base64.urlsafe_b64encode(
             bytes.fromhex(
                 "9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
             )).replace(b"=", b"").decode("ascii"),
     })
     ctx = COSE.new(kid_auto_inclusion=True)
     encoded = ctx.encode_and_sign(
         b"This is the content.",
         key,
         protected={
             1: -8,
             3: 0
         },
     )
     assert encoded == bytes.fromhex(cwt_str)
     assert ctx.decode(encoded, key) == b"This is the content."
コード例 #14
0
    def test_cose_usage_examples_cose_mac_aes_key_wrap(self):

        # The sender side:
        mac_key = COSEKey.from_symmetric_key(alg="HS512")
        r = Recipient.from_jwk(
            {
                "kty": "oct",
                "alg": "A128KW",
                "kid": "01",
                "k": "hJtXIZ2uSN5kbQfbtTNWbg",  # A shared wrapping key
            }, )
        r.apply(mac_key)
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_mac(b"Hello world!",
                                     key=mac_key,
                                     recipients=[r])

        # The recipient side:
        shared_key = COSEKey.from_jwk(
            {
                "kty": "oct",
                "alg": "A128KW",
                "kid": "01",
                "k": "hJtXIZ2uSN5kbQfbtTNWbg",
            }, )
        assert b"Hello world!" == ctx.decode(encoded, shared_key)
コード例 #15
0
 def test_cose_wg_examples_eddsa_sig_02(self):
     cwt_str = "D28443A10127A10445656434343854546869732069732074686520636F6E74656E742E5872988240A3A2F189BD486DE14AA77F54686C576A09F2E7ED9BAE910DF9139C2AC3BE7C27B7E10A20FA17C9D57D3510A2CF1F634BC0345AB9BE00849842171D1E9E98B2674C0E38BFCF6C557A1692B01B71015A47AC9F7748840CAD1DA80CBB5B349309FEBB912672B377C8B2072AF1598B3700"
     key = COSEKey.from_jwk({
         "kty":
         "OKP",
         "kid":
         "ed448",
         "crv":
         "Ed448",
         "x":
         base64.urlsafe_b64encode(
             bytes.fromhex(
                 "5fd7449b59b461fd2ce787ec616ad46a1da1342485a70e1f8a0ea75d80e96778edf124769b46c7061bd6783df1e50f6cd1fa1abeafe8256180"
             )).replace(b"=", b"").decode("ascii"),
         "d":
         base64.urlsafe_b64encode(
             bytes.fromhex(
                 "6c82a562cb808d10d632be89c8513ebf6c929f34ddfa8c9f63c9960ef6e348a3528c8a3fcc2f044e39a3fc5b94492f8f032e7549a20098f95b"
             )).replace(b"=", b"").decode("ascii"),
     })
     ctx = COSE.new(alg_auto_inclusion=True, kid_auto_inclusion=True)
     encoded = ctx.encode_and_sign(
         b"This is the content.",
         key,
     )
     assert encoded == bytes.fromhex(cwt_str)
     assert ctx.decode(encoded, key) == b"This is the content."
コード例 #16
0
 def test_cose_wg_examples_chacha_poly_01(self, ctx):
     # cwt_str = "D8608444A1011818A1054C26682306D4FB28CA01B43B8058245F2BD5381BBB04921A8477E55C0D850069674A05E683D416583AA0CEE0E2929CDF648094818340A2012504477365632D32353640"
     cwt_str = "D8608444A1011818A1054C26682306D4FB28CA01B43B8058241CD5D49DAA014CCAFFB30E765DC5CD410689AAE1C60B45648853298FF6808DB3FA8235DB818340A2012504477365632D32353640"
     key = COSEKey.from_jwk({
         "kty":
         "oct",
         "alg":
         "ChaCha20/Poly1305",
         "kid":
         "sec-256",
         "use":
         "enc",
         "k":
         "Dx4tPEtaaXiHlqW0w9Lh8B8uPUxbanmIl6a1xNPi8QA",
     })
     encoded = ctx.encode_and_encrypt(
         b"This is the content.",
         key,
         nonce=bytes.fromhex("26682306D4FB28CA01B43B80"),
         recipients=[
             RecipientInterface(unprotected={
                 1: -6,
                 4: b"sec-256"
             })
         ],
     )
     assert encoded == bytes.fromhex(cwt_str)
     assert ctx.decode(encoded, key) == b"This is the content."
コード例 #17
0
 def test_cose_wg_examples_aes_wrap_128_03(self):
     cwt_str = "D8618543A10107A054546869732069732074686520636F6E74656E742E58400021C21B2A7FADB677DAB64389B3FDA4AAC892D5C81B786A459E4182104A1501462FFD471422AF4D48BEEB864951D5947A55E3155E670DFC4A96017B0FD0E725818340A20122044A6F75722D7365637265745848792C46CE0BC689747133FA0DB1F5E2BC4DAAE22F906E93DFCA2DF44F0DF6C2CEF16EA8FC91D52AD662C4B49DD0D689E1086EC754347957F80F95C92C887521641B8F637D91C6E258"
     mac_key = COSEKey.from_symmetric_key(
         bytes.fromhex(
             "DDDC08972DF9BE62855291A17A1B4CF767C2DC762CB551911893BF7754988B0A286127BFF5D60C4CBC877CAC4BF3BA02C07AD544C951C3CA2FC46B70219BC3DC"
         ),
         alg="HS512",
     )
     recipient = Recipient.from_jwk(
         {
             "kty": "oct",
             "alg": "A128KW",
             "kid": "our-secret",
             "k": "hJtXIZ2uSN5kbQfbtTNWbg",
         }, )
     recipient.apply(mac_key)
     ctx = COSE.new()
     encoded = ctx.encode_and_mac(
         b"This is the content.",
         key=mac_key,
         protected={1: 7},
         recipients=[recipient],
     )
     assert encoded == bytes.fromhex(cwt_str)
     key = COSEKey.from_jwk(
         {
             "kty": "oct",
             "alg": "A128KW",
             "kid": "our-secret",
             "k": "hJtXIZ2uSN5kbQfbtTNWbg",
         }, )
     res = ctx.decode(encoded, keys=[key])
     assert res == b"This is the content."
コード例 #18
0
 def test_cose_wg_examples_hmac_01(self, ctx):
     cwt_str = "D8618543A10105A054546869732069732074686520636F6E74656E742E58202BDCC89F058216B8A208DDC6D8B54AA91F48BD63484986565105C9AD5A6682F6818340A20125044A6F75722D73656372657440"
     key = COSEKey.from_jwk({
         "kty":
         "oct",
         "alg":
         "HS256",
         "kid":
         "our-secret",
         "use":
         "sig",
         "k":
         "hJtXIZ2uSN5kbQfbtTNWbpdmhkV8FJG-Onbc6mxCcYg",
     })
     encoded = ctx.encode_and_mac(
         b"This is the content.",
         key=key,
         recipients=[
             RecipientInterface(unprotected={
                 1: -6,
                 4: b"our-secret"
             })
         ],
     )
     assert encoded == bytes.fromhex(cwt_str)
     assert ctx.decode(encoded, key) == b"This is the content."
コード例 #19
0
 def test_cose_wg_examples_sign1_pass_01(self):
     # cwt_str = "D28441A0A201260442313154546869732069732074686520636F6E74656E742E584087DB0D2E5571843B78AC33ECB2830DF7B6E0A4D5B7376DE336B23C591C90C425317E56127FBE04370097CE347087B233BF722B64072BEB4486BDA4031D27244F"
     key = COSEKey.from_jwk({
         "kty":
         "EC",
         "kid":
         "11",
         "crv":
         "P-256",
         "x":
         "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8",
         "y":
         "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4",
         "d":
         "V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM",
     })
     ctx = COSE.new()
     encoded = ctx.encode_and_sign(
         b"This is the content.",
         key,
         protected=bytes.fromhex("a0"),
         unprotected={
             1: -7,
             4: b"11"
         },
     )
     assert ctx.decode(encoded, key) == b"This is the content."
コード例 #20
0
    def refresh_trustlist(self):
        self._dscs = []
        self._trustlist = []

        # Get a trust-list signer certificate.
        r = requests.get(self._base_url + "/cert")
        if r.status_code != 200:
            raise Exception(f"Received {r.status_code} from /cert")
        key = r.text
        cose_key = COSEKey.from_pem(key)

        # Get DSCs
        r = requests.get(self._base_url + "/trust-list")
        if r.status_code != 200:
            raise Exception(f"Received {r.status_code} from /trust-list")
        decoded = jwt.decode(
            r.text,
            cose_key.key,
            algorithms=["ES256"],
            options={"verify_aud": False},
        )
        for v in decoded["dsc_trust_list"].values():
            for k in v["keys"]:
                if "use" in k and k["use"] == "enc":
                    # Workaround for Swedish DSC.
                    del k["use"]
                if k["kty"] == "RSA":
                    k["alg"] = "PS256"
                self._dscs.append(COSEKey.from_jwk(k))
            self._trustlist.append(k)

        # Update trustlist store.
        with open(self._trustlist_store_path, "w") as f:
            json.dump(self._trustlist, f, indent=4)
        return
コード例 #21
0
    def test_cose_decode_mac_with_multiple_keys_with_verify_kid_and_protected_kid(
            self):
        ctx = COSE.new(alg_auto_inclusion=True, verify_kid=True)
        key = COSEKey.from_symmetric_key(alg="HS256")

        material1 = base64.urlsafe_b64encode(token_bytes(16)).decode()
        material2 = base64.urlsafe_b64encode(token_bytes(16)).decode()
        material3 = base64.urlsafe_b64encode(token_bytes(16)).decode()

        shared_key1 = COSEKey.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material1
        })
        shared_key2 = COSEKey.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material2
        })
        shared_key3 = COSEKey.from_jwk({
            "kty": "oct",
            "alg": "A128KW",
            "k": material3
        })

        r1 = Recipient.new(protected={1: -3, 4: b"01"}, sender_key=shared_key1)
        r2 = Recipient.new(protected={1: -3, 4: b"02"}, sender_key=shared_key2)
        r1.apply(key)
        r2.apply(key)

        encoded = ctx.encode_and_mac(b"Hello world!", key, recipients=[r2, r1])

        shared_key1 = COSEKey.from_jwk({
            "kid": "01",
            "kty": "oct",
            "alg": "A128KW",
            "k": material1
        })
        shared_key3 = COSEKey.from_jwk({
            "kid": "03",
            "kty": "oct",
            "alg": "A128KW",
            "k": material3
        })

        assert b"Hello world!" == ctx.decode(encoded,
                                             keys=[shared_key3, shared_key1])
コード例 #22
0
    def test_cose_usage_examples_cose_mac_ecdh_direct_hkdf_p256(self):

        r = Recipient.from_jwk(
            {
                "kty": "EC",
                "alg": "ECDH-ES+HKDF-256",
                "crv": "P-256",
            }, )
        pub_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "kid":
            "01",
            "crv":
            "P-256",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
        })
        mac_key = r.apply(recipient_key=pub_key, context={"alg": "HS256"})
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_mac(
            b"Hello world!",
            key=mac_key,
            recipients=[r],
        )
        priv_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "alg":
            "ECDH-ES+HKDF-256",
            "kid":
            "01",
            "crv":
            "P-256",
            "x":
            "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
            "y":
            "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
            "d":
            "r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8",
        })
        assert b"Hello world!" == ctx.decode(encoded,
                                             priv_key,
                                             context={"alg": "HS256"})
コード例 #23
0
    def test_cose_usage_examples_cose_encrypt_ecdh_direct_hkdf_x25519(self):

        r = Recipient.from_jwk(
            {
                "kty": "OKP",
                "alg": "ECDH-ES+HKDF-256",
                "crv": "X25519",
            }, )
        pub_key = COSEKey.from_jwk({
            "kty":
            "OKP",
            "alg":
            "ECDH-ES+HKDF-256",
            "kid":
            "01",
            "crv":
            "X25519",
            "x":
            "y3wJq3uXPHeoCO4FubvTc7VcBuqpvUrSvU6ZMbHDTCI",
        })
        enc_key = r.apply(recipient_key=pub_key, context={"alg": "A128GCM"})
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_encrypt(
            b"Hello world!",
            key=enc_key,
            recipients=[r],
        )
        priv_key = COSEKey.from_jwk({
            "kty":
            "OKP",
            "alg":
            "ECDH-ES+HKDF-256",
            "kid":
            "01",
            "crv":
            "X25519",
            "x":
            "y3wJq3uXPHeoCO4FubvTc7VcBuqpvUrSvU6ZMbHDTCI",
            "d":
            "vsJ1oX5NNi0IGdwGldiac75r-Utmq3Jq4LGv48Q_Qc4",
        })
        assert b"Hello world!" == ctx.decode(encoded,
                                             priv_key,
                                             context={"alg": "A128GCM"})
コード例 #24
0
    def test_cose_usage_examples_cose_encrypt_ecdh_direct_hkdf_x448(self):

        r = Recipient.from_jwk(
            {
                "kty": "OKP",
                "alg": "ECDH-ES+HKDF-256",
                "crv": "X448",
            }, )
        pub_key = COSEKey.from_jwk({
            "kty":
            "OKP",
            "alg":
            "ECDH-ES+HKDF-256",
            "kid":
            "01",
            "crv":
            "X448",
            "x":
            "IkLmc0klvEMXYneHMKAB6ePohryAwAPVe2pRSffIDY6NrjeYNWVX5J-fG4NV2OoU77C88A0mvxI",
        })
        enc_key = r.apply(recipient_key=pub_key, context={"alg": "A128GCM"})
        ctx = COSE.new(alg_auto_inclusion=True)
        encoded = ctx.encode_and_encrypt(
            b"Hello world!",
            key=enc_key,
            recipients=[r],
        )
        priv_key = COSEKey.from_jwk({
            "kty":
            "OKP",
            "alg":
            "ECDH-ES+HKDF-256",
            "kid":
            "01",
            "crv":
            "X448",
            "x":
            "IkLmc0klvEMXYneHMKAB6ePohryAwAPVe2pRSffIDY6NrjeYNWVX5J-fG4NV2OoU77C88A0mvxI",
            "d":
            "rJJRG3nshyCtd9CgXld8aNaB9YXKR0UOi7zj7hApg9YH4XdBO0G8NcAFNz_uPH2GnCZVcSDgV5c",
        })
        assert b"Hello world!" == ctx.decode(encoded,
                                             priv_key,
                                             context={"alg": "A128GCM"})
コード例 #25
0
 def test_cose_wg_examples_ecdh_direct_p256_hkdf_256_01(self):
     rec = Recipient.from_jwk({
         "kty": "EC",
         "crv": "P-256",
         "alg": "ECDH-ES+HKDF-256",
     })
     pub_key = COSEKey.from_jwk({
         "kty":
         "EC",
         "kid":
         "*****@*****.**",
         "crv":
         "P-256",
         "x":
         "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
         "y":
         "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
     })
     enc_key = rec.apply(recipient_key=pub_key, context={"alg": "A128GCM"})
     ctx = COSE.new(alg_auto_inclusion=True)
     encoded = ctx.encode_and_encrypt(
         b"This is the content.",
         key=enc_key,
         recipients=[rec],
     )
     priv_key = COSEKey.from_jwk({
         "kty":
         "EC",
         "kid":
         "*****@*****.**",
         "crv":
         "P-256",
         "alg":
         "ECDH-ES+HKDF-256",
         "x":
         "Ze2loSV3wrroKUN_4zhwGhCqo3Xhu1td4QjeQ5wIVR0",
         "y":
         "HlLtdXARY_f55A3fnzQbPcm6hgr34Mp8p-nuzQCE0Zw",
         "d":
         "r_kHyZ-a06rmxM3yESK84r1otSg-aQcVStkRhA-iCM8",
     })
     assert b"This is the content." == ctx.decode(
         encoded, priv_key, context={"alg": "A128GCM"})
コード例 #26
0
 def _load_trustlist(self):
     try:
         with open(self._trustlist_store_path) as f:
             self._trustlist = json.load(f)
         self._dscs = [COSEKey.from_jwk(k) for k in self._trustlist]
     except Exception as err:
         if type(err) != FileNotFoundError:
             raise err
         self._trustlist = []
     return
コード例 #27
0
ファイル: test_cwt_sample.py プロジェクト: dajiaji/python-cwt
    def test_sample_readme_signed_cwt_es256_with_cert_without_intermediates(self):
        with open(key_path("private_key_cert_es256.pem")) as f:
            private_key = COSEKey.from_pem(f.read(), kid="P-256-01")

        with open(key_path("cert_es256_2.json")) as f:
            public_key = COSEKey.from_jwk(f.read())

        token = cwt.encode({"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"}, private_key)

        decoder = CWT.new(ca_certs=key_path("cacert.pem"))
        decoded = decoder.decode(token, public_key)
        assert 1 in decoded and decoded[1] == "coaps://as.example"
コード例 #28
0
ファイル: test_cwt_sample.py プロジェクト: dajiaji/python-cwt
    def test_sample_readme_cwt_with_pop_jwk(self):

        # issuer:
        with open(key_path("private_key_ed25519.pem")) as key_file:
            private_key = COSEKey.from_pem(key_file.read(), kid="issuer-01")
        token = cwt.encode(
            {
                "iss": "coaps://as.example",
                "sub": "dajiaji",
                "cti": "123",
                "cnf": {
                    "jwk": {
                        "kty": "OKP",
                        "use": "sig",
                        "crv": "Ed25519",
                        "kid": "01",
                        "x": "2E6dX83gqD_D0eAmqnaHe1TC1xuld6iAKXfw2OVATr0",
                        "alg": "EdDSA",
                    },
                },
            },
            private_key,
        )

        # presenter:
        msg = b"could-you-sign-this-message?"  # Provided by recipient.
        pop_key_private = COSEKey.from_jwk(
            {
                "kty": "OKP",
                "d": "L8JS08VsFZoZxGa9JvzYmCWOwg7zaKcei3KZmYsj7dc",
                "use": "sig",
                "crv": "Ed25519",
                "kid": "01",
                "x": "2E6dX83gqD_D0eAmqnaHe1TC1xuld6iAKXfw2OVATr0",
                "alg": "EdDSA",
            }
        )
        sig = pop_key_private.sign(msg)

        # recipient:
        with open(key_path("public_key_ed25519.pem")) as key_file:
            public_key = COSEKey.from_pem(key_file.read(), kid="issuer-01")
        decoded = cwt.decode(token, public_key)
        assert 8 in decoded and isinstance(decoded[8], dict)
        assert 1 in decoded[8] and isinstance(decoded[8][1], dict)
        c = Claims.new(decoded)
        extracted = COSEKey.new(c.cnf)
        try:
            extracted.verify(msg, sig)
        except Exception:
            pytest.fail("verify should not fail.")
コード例 #29
0
ファイル: test_cwt_sample.py プロジェクト: dajiaji/python-cwt
    def test_sample_readme_signed_cwt_es256_with_another_ca_cert(self):
        with open(key_path("private_key_cert_es256.pem")) as f:
            private_key = COSEKey.from_pem(f.read(), kid="P-256-01")

        with open(key_path("cert_es256.json")) as f:
            public_key = COSEKey.from_jwk(f.read())

        token = cwt.encode({"iss": "coaps://as.example", "sub": "dajiaji", "cti": "123"}, private_key)

        decoder = CWT.new(ca_certs=key_path("cacert_2.pem"))
        with pytest.raises(VerifyError) as err:
            decoder.decode(token, public_key)
            pytest.fail("decode() should fail.")
        assert "Failed to validate the certificate bound to the key." in str(err.value)
コード例 #30
0
    def test_cose_encode_and_decode_signature1_with_options(self):
        ctx = COSE.new(alg_auto_inclusion=True, kid_auto_inclusion=True)

        # Signature1
        sig_key = COSEKey.from_jwk({
            "kty":
            "EC",
            "kid":
            "03",
            "crv":
            "P-256",
            "x":
            "usWxHK2PmfnHKwXPS54m0kTcGJ90UiglWiGahtagnv8",
            "y":
            "IBOL-C3BttVivg-lSreASjpkttcsz-1rb7btKLv8EX4",
            "d":
            "V8kgd2ZBRuh2dgyVINBUqpPDr7BOMGcF22CQMIUHtNM",
        })
        encoded = ctx.encode_and_sign(b"Hello world!", sig_key)
        assert b"Hello world!" == ctx.decode(encoded, sig_key)