File: crypto.py

package info (click to toggle)
aws-crt-python 0.28.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 78,428 kB
  • sloc: ansic: 437,955; python: 27,657; makefile: 5,855; sh: 4,289; ruby: 208; java: 82; perl: 73; cpp: 25; xml: 11
file content (323 lines) | stat: -rw-r--r-- 9,312 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.

import _awscrt
from awscrt import NativeResource
from typing import Union, NamedTuple
from enum import IntEnum


class Hash:

    def __init__(self, native_handle):
        """
        don't call me, I'm private
        """
        self._hash = native_handle

    @staticmethod
    def sha1_new():
        """
        Creates a new instance of Hash, using the sha1 algorithm
        """
        return Hash(native_handle=_awscrt.sha1_new())

    @staticmethod
    def sha256_new():
        """
        Creates a new instance of Hash, using the sha256 algorithm
        """
        return Hash(native_handle=_awscrt.sha256_new())

    @staticmethod
    def md5_new():
        """
        Creates a new instance of Hash, using the md5 algorithm.
        """
        return Hash(native_handle=_awscrt.md5_new())

    def update(self, to_hash):
        _awscrt.hash_update(self._hash, to_hash)

    def digest(self, truncate_to=0):
        return _awscrt.hash_digest(self._hash, truncate_to)


class HMAC:
    def __init__(self, native_handle):
        """
        don't call me, I'm private
        """
        self._hmac = native_handle

    @staticmethod
    def sha256_hmac_new(secret_key):
        """
        Creates a new instance of HMAC, using SHA256 HMAC as the algorithm and secret_key as the secret
        """
        return HMAC(native_handle=_awscrt.sha256_hmac_new(secret_key))

    def update(self, to_hmac):
        _awscrt.hmac_update(self._hmac, to_hmac)

    def digest(self, truncate_to=0):
        return _awscrt.hmac_digest(self._hmac, truncate_to)


class RSAEncryptionAlgorithm(IntEnum):
    """RSA Encryption Algorithm"""

    PKCS1_5 = 0
    """
    PKCSv1.5 padding
    """

    OAEP_SHA256 = 1
    """
    OAEP padding with sha256 hash function
    """

    OAEP_SHA512 = 2
    """
    OAEP padding with sha512 hash function
    """


class RSASignatureAlgorithm(IntEnum):
    """RSA Encryption Algorithm"""

    PKCS1_5_SHA256 = 0
    """
    PKCSv1.5 padding with sha256 hash function
    """

    PKCS1_5_SHA1 = 1
    """
    PKCSv1.5 padding with sha1 hash function
    """

    PSS_SHA256 = 2
    """
    PSS padding with sha256 hash function
    """


class RSA(NativeResource):
    def __init__(self, binding):
        super().__init__()
        self._binding = binding

    @staticmethod
    def new_private_key_from_pem_data(pem_data: Union[str, bytes, bytearray, memoryview]) -> 'RSA':
        """
        Creates a new instance of private RSA key pair from pem data.
        Raises ValueError if pem does not have private key object.
        """
        return RSA(binding=_awscrt.rsa_private_key_from_pem_data(pem_data))

    @staticmethod
    def new_public_key_from_pem_data(pem_data: Union[str, bytes, bytearray, memoryview]) -> 'RSA':
        """
        Creates a new instance of public RSA key pair from pem data.
        Raises ValueError if pem does not have public key object.
        """
        return RSA(binding=_awscrt.rsa_public_key_from_pem_data(pem_data))

    @staticmethod
    def new_private_key_from_der_data(der_data: Union[bytes, bytearray, memoryview]) -> 'RSA':
        """
        Creates a new instance of private RSA key pair from der data.
        Expects key in PKCS1 format.
        Raises ValueError if pem does not have private key object.
        """
        return RSA(binding=_awscrt.rsa_private_key_from_der_data(der_data))

    @staticmethod
    def new_public_key_from_der_data(der_data: Union[bytes, bytearray, memoryview]) -> 'RSA':
        """
        Creates a new instance of public RSA key pair from der data.
        Expects key in PKCS1 format.
        Raises ValueError if pem does not have public key object.
        """
        return RSA(binding=_awscrt.rsa_public_key_from_der_data(der_data))

    def encrypt(self, encryption_algorithm: RSAEncryptionAlgorithm,
                plaintext: Union[bytes, bytearray, memoryview]) -> bytes:
        """
        Encrypts data using a given algorithm.
        """
        return _awscrt.rsa_encrypt(self._binding, encryption_algorithm, plaintext)

    def decrypt(self, encryption_algorithm: RSAEncryptionAlgorithm,
                ciphertext: Union[bytes, bytearray, memoryview]) -> bytes:
        """
        Decrypts data using a given algorithm.
        """
        return _awscrt.rsa_decrypt(self._binding, encryption_algorithm, ciphertext)

    def sign(self, signature_algorithm: RSASignatureAlgorithm,
             digest: Union[bytes, bytearray, memoryview]) -> bytes:
        """
        Signs data using a given algorithm.
        Note: function expects digest of the message, ex sha256
        """
        return _awscrt.rsa_sign(self._binding, signature_algorithm, digest)

    def verify(self, signature_algorithm: RSASignatureAlgorithm,
               digest: Union[bytes, bytearray, memoryview],
               signature: Union[bytes, bytearray, memoryview]) -> bool:
        """
        Verifies signature against digest.
        Returns True if signature matches and False if not.
        """
        return _awscrt.rsa_verify(self._binding, signature_algorithm, digest, signature)


class ED25519ExportFormat(IntEnum):
    """ED25519 Export format"""

    RAW = 0
    """
    Raw bytes.
    """

    OPENSSH_B64 = 1
    """
    Base64 encoded OpenSSH format as defined in RFC 8709.
    """


class ED25519(NativeResource):
    def __init__(self, binding):
        super().__init__()
        self._binding = binding

    @staticmethod
    def new_generate() -> 'ED25519':
        """
        Generates a new instance of ED25159 key pair.
        """
        return ED25519(binding=_awscrt.ed25519_new_generate())

    def export_public_key(self, export_format: ED25519ExportFormat) -> bytes:
        """
        Exports public part of the key in specified format.
        """
        return _awscrt.ed25519_export_public_key(self._binding, export_format)

    def export_private_key(self, export_format: ED25519ExportFormat) -> bytes:
        """
        Exports public part of the key in specified format.
        """
        return _awscrt.ed25519_export_private_key(self._binding, export_format)


class ECType(IntEnum):
    """Elliptic Curve Type"""

    P_256 = 0
    """
    P-256 curve aka secp256r1
    """

    P_384 = 1
    """
    P-384 curve aka secp384r1
    """


class ECExportFormat(IntEnum):
    """EC Export format"""

    SEC1 = 0
    """
    Raw bytes for the private key as defined in Sec1 ("EC Private Key" in pem)
    """

    PKCS8 = 1
    """
    Raw bytes for the private key as defined in PKCS8 ("Private Key" in pem)
    """

    SPKI = 2
    """
    Raw bytes for the public key as defined in x509/SPKI ("EC Public Key" or "Public Key" in pem)
    """


class ECRawSignature(NamedTuple):
    r: bytes
    s: bytes


class ECPublicCoords(NamedTuple):
    x: bytes
    y: bytes


class EC(NativeResource):
    def __init__(self, binding):
        super().__init__()
        self._binding = binding

    @staticmethod
    def new_generate(type: ECType) -> 'EC':
        """
        Generates a new instance of EC key pair.
        """
        return EC(binding=_awscrt.ec_new_generate(type))

    @staticmethod
    def new_key_from_der_data(der_data: Union[bytes, bytearray, memoryview]) -> 'EC':
        """
        Creates a new instance of EC key pair from der data.
        Will figure out what type of key it is without hint (i.e. pem header).
        Supports all formats specified in ECExportFormat.
        Expects raw bytes (i.e. strip b64 you get when reading pem).
        Raises ValueError if pem does not have private key object.
        """
        return EC(binding=_awscrt.ec_key_from_der_data(der_data))

    @staticmethod
    def decode_der_signature(signature: bytes) -> ECRawSignature:
        """
        Decodes ec signature into raw r and s.
        """
        (r, s) = _awscrt.ec_decode_signature(signature)
        return ECRawSignature(r=r, s=s)

    @staticmethod
    def encode_raw_signature(signature: ECRawSignature) -> bytes:
        """
        Encodes raw signature into der.
        """
        return _awscrt.ec_encode_signature(signature)

    def export_key(self, export_format: ECExportFormat) -> bytes:
        """
        Exports the key in specified format.
        """
        return _awscrt.ec_export_key(self._binding, export_format)

    def get_public_coords(self) -> ECPublicCoords:
        """
        Get public coords of the key
        """
        (x, y) = _awscrt.ec_get_public_coords(self._binding)
        return ECPublicCoords(x=x, y=y)

    def sign(self, digest: Union[bytes, bytearray, memoryview]) -> bytes:
        """
        Signs data using a given algorithm.
        Returns DER encoded signature.
        Note: function expects digest of the message, ex sha256
        """
        return _awscrt.ec_sign(self._binding, digest)

    def verify(self, digest: Union[bytes, bytearray, memoryview],
               signature: Union[bytes, bytearray, memoryview]) -> bool:
        """
        Verifies signature against digest.
        Returns True if signature matches and False if not.
        """
        return _awscrt.ec_verify(self._binding, digest, signature)