1from ..utils import base64url_encode, ensure_binary
2
3
4class Key:
5 """
6 A simple interface for implementing JWK keys.
7 """
8
9 def __init__(self, key, algorithm):
10 pass
11
12 def sign(self, msg):
13 raise NotImplementedError()
14
15 def verify(self, msg, sig):
16 raise NotImplementedError()
17
18 def public_key(self):
19 raise NotImplementedError()
20
21 def to_pem(self):
22 raise NotImplementedError()
23
24 def to_dict(self):
25 raise NotImplementedError()
26
27 def encrypt(self, plain_text, aad=None):
28 """
29 Encrypt the plain text and generate an auth tag if appropriate
30
31 Args:
32 plain_text (bytes): Data to encrypt
33 aad (bytes, optional): Authenticated Additional Data if key's algorithm supports auth mode
34
35 Returns:
36 (bytes, bytes, bytes): IV, cipher text, and auth tag
37 """
38 raise NotImplementedError()
39
40 def decrypt(self, cipher_text, iv=None, aad=None, tag=None):
41 """
42 Decrypt the cipher text and validate the auth tag if present
43 Args:
44 cipher_text (bytes): Cipher text to decrypt
45 iv (bytes): IV if block mode
46 aad (bytes): Additional Authenticated Data to verify if auth mode
47 tag (bytes): Authentication tag if auth mode
48
49 Returns:
50 bytes: Decrypted value
51 """
52 raise NotImplementedError()
53
54 def wrap_key(self, key_data):
55 """
56 Wrap the the plain text key data
57
58 Args:
59 key_data (bytes): Key data to wrap
60
61 Returns:
62 bytes: Wrapped key
63 """
64 raise NotImplementedError()
65
66 def unwrap_key(self, wrapped_key):
67 """
68 Unwrap the the wrapped key data
69
70 Args:
71 wrapped_key (bytes): Wrapped key data to unwrap
72
73 Returns:
74 bytes: Unwrapped key
75 """
76 raise NotImplementedError()
77
78
79class DIRKey(Key):
80 def __init__(self, key_data, algorithm):
81 self._key = ensure_binary(key_data)
82 self._alg = algorithm
83
84 def to_dict(self):
85 return {
86 "alg": self._alg,
87 "kty": "oct",
88 "k": base64url_encode(self._key),
89 }