Debian Codegraph @

awscrt/crypto.py

raw symbols SCIP
1 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 # SPDX-License-Identifier: Apache-2.0.
3
4 import _awscrt
5 from awscrt import NativeResource
6 from typing import Union, NamedTuple
7 from enum import IntEnum
8
9
10 class Hash:
11
12 def __init__(self, native_handle):
13 """
14 don't call me, I'm private
15 """
16 self._hash = native_handle
17
18 @staticmethod
19 def sha1_new():
20 """
21 Creates a new instance of Hash, using the sha1 algorithm
22 """
23 return Hash(native_handle=_awscrt.sha1_new())
24
25 @staticmethod
26 def sha256_new():
27 """
28 Creates a new instance of Hash, using the sha256 algorithm
29 """
30 return Hash(native_handle=_awscrt.sha256_new())
31
32 @staticmethod
33 def md5_new():
34 """
35 Creates a new instance of Hash, using the md5 algorithm.
36 """
37 return Hash(native_handle=_awscrt.md5_new())
38
39 def update(self, to_hash):
40 _awscrt.hash_update(self._hash, to_hash)
41
42 def digest(self, truncate_to=0):
43 return _awscrt.hash_digest(self._hash, truncate_to)
44
45
46 class HMAC:
47 def __init__(self, native_handle):
48 """
49 don't call me, I'm private
50 """
51 self._hmac = native_handle
52
53 @staticmethod
54 def sha256_hmac_new(secret_key):
55 """
56 Creates a new instance of HMAC, using SHA256 HMAC as the algorithm and secret_key as the secret
57 """
58 return HMAC(native_handle=_awscrt.sha256_hmac_new(secret_key))
59
60 def update(self, to_hmac):
61 _awscrt.hmac_update(self._hmac, to_hmac)
62
63 def digest(self, truncate_to=0):
64 return _awscrt.hmac_digest(self._hmac, truncate_to)
65
66
67 class RSAEncryptionAlgorithm(IntEnum):
68 """RSA Encryption Algorithm"""
69
70 PKCS1_5 = 0
71 """
72 PKCSv1.5 padding
73 """
74
75 OAEP_SHA256 = 1
76 """
77 OAEP padding with sha256 hash function
78 """
79
80 OAEP_SHA512 = 2
81 """
82 OAEP padding with sha512 hash function
83 """
84
85
86 class RSASignatureAlgorithm(IntEnum):
87 """RSA Encryption Algorithm"""
88
89 PKCS1_5_SHA256 = 0
90 """
91 PKCSv1.5 padding with sha256 hash function
92 """
93
94 PKCS1_5_SHA1 = 1
95 """
96 PKCSv1.5 padding with sha1 hash function
97 """
98
99 PSS_SHA256 = 2
100 """
101 PSS padding with sha256 hash function
102 """
103
104
105 class RSA(NativeResource):
106 def __init__(self, binding):
107 super().__init__()
108 self._binding = binding
109
110 @staticmethod
111 def new_private_key_from_pem_data(pem_data: Union[str, bytes, bytearray, memoryview]) -> 'RSA':
112 """
113 Creates a new instance of private RSA key pair from pem data.
114 Raises ValueError if pem does not have private key object.
115 """
116 return RSA(binding=_awscrt.rsa_private_key_from_pem_data(pem_data))
117
118 @staticmethod
119 def new_public_key_from_pem_data(pem_data: Union[str, bytes, bytearray, memoryview]) -> 'RSA':
120 """
121 Creates a new instance of public RSA key pair from pem data.
122 Raises ValueError if pem does not have public key object.
123 """
124 return RSA(binding=_awscrt.rsa_public_key_from_pem_data(pem_data))
125
126 @staticmethod
127 def new_private_key_from_der_data(der_data: Union[bytes, bytearray, memoryview]) -> 'RSA':
128 """
129 Creates a new instance of private RSA key pair from der data.
130 Expects key in PKCS1 format.
131 Raises ValueError if pem does not have private key object.
132 """
133 return RSA(binding=_awscrt.rsa_private_key_from_der_data(der_data))
134
135 @staticmethod
136 def new_public_key_from_der_data(der_data: Union[bytes, bytearray, memoryview]) -> 'RSA':
137 """
138 Creates a new instance of public RSA key pair from der data.
139 Expects key in PKCS1 format.
140 Raises ValueError if pem does not have public key object.
141 """
142 return RSA(binding=_awscrt.rsa_public_key_from_der_data(der_data))
143
144 def encrypt(self, encryption_algorithm: RSAEncryptionAlgorithm,
145 plaintext: Union[bytes, bytearray, memoryview]) -> bytes:
146 """
147 Encrypts data using a given algorithm.
148 """
149 return _awscrt.rsa_encrypt(self._binding, encryption_algorithm, plaintext)
150
151 def decrypt(self, encryption_algorithm: RSAEncryptionAlgorithm,
152 ciphertext: Union[bytes, bytearray, memoryview]) -> bytes:
153 """
154 Decrypts data using a given algorithm.
155 """
156 return _awscrt.rsa_decrypt(self._binding, encryption_algorithm, ciphertext)
157
158 def sign(self, signature_algorithm: RSASignatureAlgorithm,
159 digest: Union[bytes, bytearray, memoryview]) -> bytes:
160 """
161 Signs data using a given algorithm.
162 Note: function expects digest of the message, ex sha256
163 """
164 return _awscrt.rsa_sign(self._binding, signature_algorithm, digest)
165
166 def verify(self, signature_algorithm: RSASignatureAlgorithm,
167 digest: Union[bytes, bytearray, memoryview],
168 signature: Union[bytes, bytearray, memoryview]) -> bool:
169 """
170 Verifies signature against digest.
171 Returns True if signature matches and False if not.
172 """
173 return _awscrt.rsa_verify(self._binding, signature_algorithm, digest, signature)
174
175
176 class ED25519ExportFormat(IntEnum):
177 """ED25519 Export format"""
178
179 RAW = 0
180 """
181 Raw bytes.
182 """
183
184 OPENSSH_B64 = 1
185 """
186 Base64 encoded OpenSSH format as defined in RFC 8709.
187 """
188
189
190 class ED25519(NativeResource):
191 def __init__(self, binding):
192 super().__init__()
193 self._binding = binding
194
195 @staticmethod
196 def new_generate() -> 'ED25519':
197 """
198 Generates a new instance of ED25159 key pair.
199 """
200 return ED25519(binding=_awscrt.ed25519_new_generate())
201
202 def export_public_key(self, export_format: ED25519ExportFormat) -> bytes:
203 """
204 Exports public part of the key in specified format.
205 """
206 return _awscrt.ed25519_export_public_key(self._binding, export_format)
207
208 def export_private_key(self, export_format: ED25519ExportFormat) -> bytes:
209 """
210 Exports public part of the key in specified format.
211 """
212 return _awscrt.ed25519_export_private_key(self._binding, export_format)
213
214
215 class ECType(IntEnum):
216 """Elliptic Curve Type"""
217
218 P_256 = 0
219 """
220 P-256 curve aka secp256r1
221 """
222
223 P_384 = 1
224 """
225 P-384 curve aka secp384r1
226 """
227
228
229 class ECExportFormat(IntEnum):
230 """EC Export format"""
231
232 SEC1 = 0
233 """
234 Raw bytes for the private key as defined in Sec1 ("EC Private Key" in pem)
235 """
236
237 PKCS8 = 1
238 """
239 Raw bytes for the private key as defined in PKCS8 ("Private Key" in pem)
240 """
241
242 SPKI = 2
243 """
244 Raw bytes for the public key as defined in x509/SPKI ("EC Public Key" or "Public Key" in pem)
245 """
246
247
248 class ECRawSignature(NamedTuple):
249 r: bytes
250 s: bytes
251
252
253 class ECPublicCoords(NamedTuple):
254 x: bytes
255 y: bytes
256
257
258 class EC(NativeResource):
259 def __init__(self, binding):
260 super().__init__()
261 self._binding = binding
262
263 @staticmethod
264 def new_generate(type: ECType) -> 'EC':
265 """
266 Generates a new instance of EC key pair.
267 """
268 return EC(binding=_awscrt.ec_new_generate(type))
269
270 @staticmethod
271 def new_key_from_der_data(der_data: Union[bytes, bytearray, memoryview]) -> 'EC':
272 """
273 Creates a new instance of EC key pair from der data.
274 Will figure out what type of key it is without hint (i.e. pem header).
275 Supports all formats specified in ECExportFormat.
276 Expects raw bytes (i.e. strip b64 you get when reading pem).
277 Raises ValueError if pem does not have private key object.
278 """
279 return EC(binding=_awscrt.ec_key_from_der_data(der_data))
280
281 @staticmethod
282 def decode_der_signature(signature: bytes) -> ECRawSignature:
283 """
284 Decodes ec signature into raw r and s.
285 """
286 (r, s) = _awscrt.ec_decode_signature(signature)
287 return ECRawSignature(r=r, s=s)
288
289 @staticmethod
290 def decode_der_signature_to_padded_pair(signature: bytes, pad_to: int) -> bytes:
291 """
292 Decodes ec signature into padded r || s.
293 Both r and s are padded to the specified value and then concatenated.
294 Typical format for jwt use case.
295 Note: pad_to typically should equal to coord size. e.g 32 for P256 or 48 for P384
296 """
297 return _awscrt.ec_decode_signature_to_padded_pair(signature, pad_to)
298
299 @staticmethod
300 def encode_raw_signature(signature: ECRawSignature) -> bytes:
301 """
302 Encodes raw signature into der.
303 """
304 return _awscrt.ec_encode_signature(signature)
305
306 def export_key(self, export_format: ECExportFormat) -> bytes:
307 """
308 Exports the key in specified format.
309 """
310 return _awscrt.ec_export_key(self._binding, export_format)
311
312 def get_public_coords(self) -> ECPublicCoords:
313 """
314 Get public coords of the key
315 """
316 (x, y) = _awscrt.ec_get_public_coords(self._binding)
317 return ECPublicCoords(x=x, y=y)
318
319 def sign(self, digest: Union[bytes, bytearray, memoryview]) -> bytes:
320 """
321 Signs data using a given algorithm.
322 Returns DER encoded signature.
323 Note: function expects digest of the message, ex sha256
324 """
325 return _awscrt.ec_sign(self._binding, digest)
326
327 def verify(self, digest: Union[bytes, bytearray, memoryview],
328 signature: Union[bytes, bytearray, memoryview]) -> bool:
329 """
330 Verifies signature against digest.
331 Returns True if signature matches and False if not.
332 """
333 return _awscrt.ec_verify(self._binding, digest, signature)