-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathciphers.py
More file actions
2334 lines (1899 loc) · 84.2 KB
/
ciphers.py
File metadata and controls
2334 lines (1899 loc) · 84.2 KB
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ciphers.py
#
# Copyright (C) 2006-2025 wolfSSL Inc.
#
# This file is part of wolfSSL. (formerly known as CyaSSL)
#
# wolfSSL is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# wolfSSL is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
# pylint: disable=no-member,no-name-in-module
from enum import IntEnum
from wolfcrypt._ffi import ffi as _ffi
from wolfcrypt._ffi import lib as _lib
from wolfcrypt.utils import t2b
from wolfcrypt.random import Random
from wolfcrypt.asn import pem_to_der
from wolfcrypt.hashes import hash_type_to_cls
from wolfcrypt.exceptions import WolfCryptError
# key direction flags
_ENCRYPTION = 0
_DECRYPTION = 1
# feedback modes
MODE_ECB = 1 # Electronic Code Book
MODE_CBC = 2 # Cipher Block Chaining
MODE_CFB = 3 # Cipher Feedback
MODE_OFB = 5 # Output Feedback
MODE_CTR = 6 # Counter
_FEEDBACK_MODES = [MODE_ECB, MODE_CBC, MODE_CFB, MODE_OFB, MODE_CTR]
# ECC curve id
ECC_CURVE_INVALID = -1
ECC_CURVE_DEF = 0
# NIST Prime Curves
ECC_SECP192R1 = 1
ECC_PRIME192V2 = 2
ECC_PRIME192V3 = 3
ECC_PRIME239V1 = 4
ECC_PRIME239V2 = 5
ECC_PRIME239V3 = 6
ECC_SECP256R1 = 7
# SECP Curves
ECC_SECP112R1 = 8
ECC_SECP112R2 = 9
ECC_SECP128R1 = 10
ECC_SECP128R2 = 11
ECC_SECP160R1 = 12
ECC_SECP160R2 = 13
ECC_SECP224R1 = 14
ECC_SECP384R1 = 15
ECC_SECP521R1 = 16
# Koblitz
ECC_SECP160K1 = 17
ECC_SECP192K1 = 18
ECC_SECP224K1 = 19
ECC_SECP256K1 = 20
# Brainpool Curves
ECC_BRAINPOOLP160R1 = 21
ECC_BRAINPOOLP192R1 = 22
ECC_BRAINPOOLP224R1 = 23
ECC_BRAINPOOLP256R1 = 24
ECC_BRAINPOOLP320R1 = 25
ECC_BRAINPOOLP384R1 = 26
ECC_BRAINPOOLP512R1 = 27
if _lib.RSA_ENABLED:
MGF1NONE = _lib.WC_MGF1NONE
MGF1SHA1 = _lib.WC_MGF1SHA1
MGF1SHA224 = _lib.WC_MGF1SHA224
MGF1SHA256 = _lib.WC_MGF1SHA256
MGF1SHA384 = _lib.WC_MGF1SHA384
MGF1SHA512 = _lib.WC_MGF1SHA512
HASH_TYPE_NONE = _lib.WC_HASH_TYPE_NONE
HASH_TYPE_MD2 = _lib.WC_HASH_TYPE_MD2
HASH_TYPE_MD4 = _lib.WC_HASH_TYPE_MD4
HASH_TYPE_MD5 = _lib.WC_HASH_TYPE_MD5
HASH_TYPE_SHA = _lib.WC_HASH_TYPE_SHA
HASH_TYPE_SHA224 = _lib.WC_HASH_TYPE_SHA224
HASH_TYPE_SHA256 = _lib.WC_HASH_TYPE_SHA256
HASH_TYPE_SHA384 = _lib.WC_HASH_TYPE_SHA384
HASH_TYPE_SHA512 = _lib.WC_HASH_TYPE_SHA512
HASH_TYPE_MD5_SHA = _lib.WC_HASH_TYPE_MD5_SHA
HASH_TYPE_SHA3_224 = _lib.WC_HASH_TYPE_SHA3_224
HASH_TYPE_SHA3_256 = _lib.WC_HASH_TYPE_SHA3_256
HASH_TYPE_SHA3_384 = _lib.WC_HASH_TYPE_SHA3_384
HASH_TYPE_SHA3_512 = _lib.WC_HASH_TYPE_SHA3_512
HASH_TYPE_BLAKE2B = _lib.WC_HASH_TYPE_BLAKE2B
HASH_TYPE_BLAKE2S = _lib.WC_HASH_TYPE_BLAKE2S
class _Cipher(object):
"""
A **PEP 272: Block Encryption Algorithms** compliant
**Symmetric Key Cipher**.
"""
def __init__(self, key, mode, IV=None):
if mode not in _FEEDBACK_MODES:
raise ValueError("this mode is not supported")
if mode == MODE_CBC or mode == MODE_CTR:
if IV is None:
raise ValueError("this mode requires an 'IV' string")
else:
raise ValueError("this mode is not supported by this cipher")
self.mode = mode
if self.key_size:
if self.key_size != len(key):
raise ValueError("key must be %d in length, not %d" %
(self.key_size, len(key)))
elif self._key_sizes:
if len(key) not in self._key_sizes:
raise ValueError("key must be %s in length, not %d" %
(self._key_sizes, len(key)))
elif not key: # pragma: no cover
raise ValueError("key must not be 0 in length")
if IV is not None and len(IV) != self.block_size:
raise ValueError("IV must be %d in length, not %d" %
(self.block_size, len(IV)))
self._native_object = _ffi.new(self._native_type)
self._enc = None
self._dec = None
self._key = t2b(key)
if IV:
self._IV = t2b(IV)
else: # pragma: no cover
self._IV = _ffi.new("byte[%d]" % self.block_size)
@classmethod
def new(cls, key, mode, IV=None, **kwargs): # pylint: disable=W0613
"""
Returns a ciphering object, using the secret key contained in
the string **key**, and using the feedback mode **mode**, which
must be one of MODE_* defined in this module.
If **mode** is MODE_CBC or MODE_CFB, **IV** must be provided and
must be a string of the same length as the block size. Not
providing a value of **IV** will result in a ValueError exception
being raised.
"""
return cls(key, mode, IV)
def encrypt(self, string):
"""
Encrypts a non-empty string, using the key-dependent data in
the object, and with the appropriate feedback mode.
The string's length must be an exact multiple of the algorithm's
block size or, in CFB mode, of the segment size.
Returns a string containing the ciphertext.
"""
string = t2b(string)
if not string:
raise ValueError(
"empty string not allowed")
if len(string) % self.block_size and not self.mode == MODE_CTR and not "ChaCha" in self._native_type:
raise ValueError(
"string must be a multiple of %d in length" % self.block_size)
if self._enc is None:
self._enc = _ffi.new(self._native_type)
ret = self._set_key(_ENCRYPTION)
if ret < 0: # pragma: no cover
raise WolfCryptError("Invalid key error (%d)" % ret)
result = _ffi.new("byte[%d]" % len(string))
ret = self._encrypt(result, string)
if ret < 0: # pragma: no cover
raise WolfCryptError("Encryption error (%d)" % ret)
return _ffi.buffer(result)[:]
def decrypt(self, string):
"""
Decrypts **string**, using the key-dependent data in the
object and with the appropriate feedback mode.
The string's length must be an exact multiple of the algorithm's
block size or, in CFB mode, of the segment size.
Returns a string containing the plaintext.
"""
string = t2b(string)
if not string:
raise ValueError(
"empty string not allowed")
if len(string) % self.block_size and not self.mode == MODE_CTR and not "ChaCha" in self._native_type:
raise ValueError(
"string must be a multiple of %d in length" % self.block_size)
if self._dec is None:
self._dec = _ffi.new(self._native_type)
ret = self._set_key(_DECRYPTION)
if ret < 0: # pragma: no cover
raise WolfCryptError("Invalid key error (%d)" % ret)
result = _ffi.new("byte[%d]" % len(string))
ret = self._decrypt(result, string)
if ret < 0: # pragma: no cover
raise WolfCryptError("Decryption error (%d)" % ret)
return _ffi.buffer(result)[:]
if _lib.AES_ENABLED:
class Aes(_Cipher):
"""
The **Advanced Encryption Standard** (AES), a.k.a. Rijndael, is
a symmetric-key cipher standardized by **NIST**.
"""
block_size = 16
key_size = None # 16, 24, 32
_key_sizes = [16, 24, 32]
_native_type = "Aes *"
def _set_key(self, direction):
if direction == _ENCRYPTION:
return _lib.wc_AesSetKey(
self._enc, self._key, len(self._key), self._IV, _ENCRYPTION)
if self.mode == MODE_CTR:
return _lib.wc_AesSetKey(
self._dec, self._key, len(self._key), self._IV, _ENCRYPTION)
return _lib.wc_AesSetKey(
self._dec, self._key, len(self._key), self._IV, _DECRYPTION)
def _encrypt(self, destination, source):
if self.mode == MODE_CBC:
return _lib.wc_AesCbcEncrypt(self._enc, destination,
source, len(source))
elif self.mode == MODE_CTR:
return _lib.wc_AesCtrEncrypt(self._enc, destination,
source, len(source))
else:
raise ValueError("Invalid mode associated to cipher")
def _decrypt(self, destination, source):
if self.mode == MODE_CBC:
return _lib.wc_AesCbcDecrypt(self._dec, destination,
source, len(source))
elif self.mode == MODE_CTR:
return _lib.wc_AesCtrEncrypt(self._dec, destination,
source, len(source))
else:
raise ValueError("Invalid mode associated to cipher")
if _lib.AES_SIV_ENABLED:
class AesSiv(object):
"""
AES-SIV (Synthetic Initialization Vector) implementation as described in RFC 5297.
"""
# RFC 5297 defines key sizes of 256-, 384-, or 512 bits.
_key_sizes = [32, 48, 64]
block_size = 16
def __init__(self, key):
self._key = t2b(key)
if len(self._key) not in AesSiv._key_sizes:
raise ValueError("key must be %s in length, not %d" %
(AesSiv._key_sizes, len(self._key)))
def encrypt(self, associated_data, nonce, plaintext):
"""
Encrypt plaintext data using the nonce provided. The associated
data is not encrypted but is included in the authentication tag.
Associated data may be provided as single str or bytes, or as a
list of str or bytes in case of multiple blocks.
Returns a tuple of the IV and ciphertext.
"""
# Prepare the associated data blocks. Make sure to hold on to the
# returned references until the C function has been called in order
# to prevent garbage collection of them until the function is done.
associated_data, _refs = (
AesSiv._prepare_associated_data(associated_data))
nonce = t2b(nonce)
plaintext = t2b(plaintext)
siv = _ffi.new("byte[%d]" % AesSiv.block_size)
ciphertext = _ffi.new("byte[%d]" % len(plaintext))
ret = _lib.wc_AesSivEncrypt_ex(self._key, len(self._key),
associated_data, len(associated_data), nonce, len(nonce),
plaintext, len(plaintext), siv, ciphertext)
if ret < 0: # pragma: no cover
raise WolfCryptError("AES-SIV encryption error (%d)" % ret)
return _ffi.buffer(siv)[:], _ffi.buffer(ciphertext)[:]
def decrypt(self, associated_data, nonce, siv, ciphertext):
"""
Decrypt the ciphertext using the nonce and SIV provided.
The integrity of the associated data is checked.
Associated data may be provided as single str or bytes, or as a
list of str or bytes in case of multiple blocks.
Returns the decrypted plaintext.
"""
# Prepare the associated data blocks. Make sure to hold on to the
# returned references until the C function has been called in order
# to prevent garbage collection of them until the function is done.
associated_data, _refs = (
AesSiv._prepare_associated_data(associated_data))
nonce = t2b(nonce)
siv = t2b(siv)
if len(siv) != AesSiv.block_size:
raise ValueError("SIV must be %s in length, not %d" %
(AesSiv.block_size, len(siv)))
ciphertext = t2b(ciphertext)
plaintext = _ffi.new("byte[%d]" % len(ciphertext))
ref = _lib.wc_AesSivDecrypt_ex(self._key, len(self._key),
associated_data, len(associated_data), nonce, len(nonce),
ciphertext, len(ciphertext), siv, plaintext)
if ref < 0:
raise WolfCryptError("AES-SIV decryption error (%d)" % ref)
return _ffi.buffer(plaintext)[:]
@staticmethod
def _prepare_associated_data(associated_data):
"""
Prepare associated data for sending to C library.
Associated data may be provided as single str or bytes, or as a
list of str or bytes in case of multiple blocks.
The result is a tuple of the list of cffi cdata pointers to
AesSivAssoc structures, as well as the converted associated
data blocks. The caller **must** hold on to these until the
C function has been called, in order to make sure that the memory
is not freed by the FFI garbage collector before the data is read.
"""
if (isinstance(associated_data, str) or isinstance(associated_data, bytes)):
# A single block is provided.
# Make sure we have bytes.
associated_data = t2b(associated_data)
result = _ffi.new("AesSivAssoc[1]")
result[0].assoc = _ffi.from_buffer(associated_data)
result[0].assocSz = len(associated_data)
else:
# It is assumed that a list is provided.
num_blocks = len(associated_data)
if (num_blocks > 126):
raise WolfCryptError("AES-SIV does not support more than 126 blocks "
"of associated data, got: %d" % num_blocks)
# Make sure we have bytes.
associated_data = [t2b(block) for block in associated_data]
result = _ffi.new("AesSivAssoc[]", num_blocks)
for index, block in enumerate(associated_data):
result[index].assoc = _ffi.from_buffer(block)
result[index].assocSz = len(block)
# Return the converted associated data blocks so the caller can
# hold on to them until the function has been called.
return result, associated_data
if _lib.AESGCM_STREAM_ENABLED:
class AesGcmStream(object):
"""
AES GCM Stream
"""
block_size = 16
_key_sizes = [16, 24, 32]
_native_type = "Aes *"
_aad = bytes()
_tag_bytes = 16
_mode = None
def __init__(self, key, IV, tag_bytes=16):
"""
tag_bytes is the number of bytes to use for the authentication tag during encryption
"""
key = t2b(key)
IV = t2b(IV)
self._tag_bytes = tag_bytes
if len(key) not in self._key_sizes:
raise ValueError("key must be %s in length, not %d" %
(self._key_sizes, len(key)))
self._native_object = _ffi.new(self._native_type)
_lib.wc_AesInit(self._native_object, _ffi.NULL, -2)
ret = _lib.wc_AesGcmInit(self._native_object, key, len(key), IV, len(IV))
if ret < 0:
raise WolfCryptError("Init error (%d)" % ret)
def set_aad(self, data):
"""
Set the additional authentication data for the stream
"""
if self._mode is not None:
raise WolfCryptError("AAD can only be set before encrypt() or decrypt() is called")
self._aad = t2b(data)
def get_aad(self):
return self._aad
def encrypt(self, data):
"""
Add more data to the encryption stream
"""
data = t2b(data)
aad = bytes()
if self._mode is None:
self._mode = _ENCRYPTION
aad = self._aad
elif self._mode == _DECRYPTION:
raise WolfCryptError("Class instance already in use for decryption")
self._buf = _ffi.new("byte[%d]" % (len(data)))
ret = _lib.wc_AesGcmEncryptUpdate(self._native_object, self._buf, data, len(data), aad, len(aad))
if ret < 0:
raise WolfCryptError("Decryption error (%d)" % ret)
return bytes(self._buf)
def decrypt(self, data):
"""
Add more data to the decryption stream
"""
aad = bytes()
data = t2b(data)
if self._mode is None:
self._mode = _DECRYPTION
aad = self._aad
elif self._mode == _ENCRYPTION:
raise WolfCryptError("Class instance already in use for decryption")
self._buf = _ffi.new("byte[%d]" % (len(data)))
ret = _lib.wc_AesGcmDecryptUpdate(self._native_object, self._buf, data, len(data), aad, len(aad))
if ret < 0:
raise WolfCryptError("Decryption error (%d)" % ret)
return bytes(self._buf)
def final(self, authTag=None):
"""
When encrypting, finalize the stream and return an authentication tag for the stream.
When decrypting, verify the authentication tag for the stream.
The authTag parameter is only used for decrypting.
"""
if self._mode is None:
raise WolfCryptError("Final called with no encryption or decryption")
elif self._mode == _ENCRYPTION:
authTag = _ffi.new("byte[%d]" % self._tag_bytes)
ret = _lib.wc_AesGcmEncryptFinal(self._native_object, authTag, self._tag_bytes)
if ret < 0:
raise WolfCryptError("Encryption error (%d)" % ret)
return _ffi.buffer(authTag)[:]
else:
if authTag is None:
raise WolfCryptError("authTag parameter required")
authTag = t2b(authTag)
ret = _lib.wc_AesGcmDecryptFinal(self._native_object, authTag, len(authTag))
if ret < 0:
raise WolfCryptError("Decryption error (%d)" % ret)
if _lib.CHACHA_ENABLED:
class ChaCha(_Cipher):
"""
ChaCha20
"""
block_size = 16
key_size = None # 16, 24, 32
_key_sizes = [16, 32]
_native_type = "ChaCha *"
_IV_nonce = []
_IV_counter = 0
def __init__(self, key="", size=32):
self._native_object = _ffi.new(self._native_type)
self._enc = None
self._dec = None
self._key = None
if len(key) > 0:
if not size in self._key_sizes:
raise ValueError("Invalid key size %d" % size)
self._key = t2b(key)
self.key_size = size
self._IV_nonce = []
self._IV_counter = 0
def _set_key(self, direction):
if self._key == None:
return -1
if self._enc:
ret = _lib.wc_Chacha_SetKey(self._enc, self._key, len(self._key))
if ret == 0:
_lib.wc_Chacha_SetIV(self._enc, self._IV_nonce, self._IV_counter)
if ret != 0:
return ret
if self._dec:
ret = _lib.wc_Chacha_SetKey(self._dec, self._key, len(self._key))
if ret == 0:
_lib.wc_Chacha_SetIV(self._dec, self._IV_nonce, self._IV_counter)
if ret != 0:
return ret
return 0
def _encrypt(self, destination, source):
return _lib.wc_Chacha_Process(self._enc, destination,
source, len(source))
def _decrypt(self, destination, source):
return _lib.wc_Chacha_Process(self._dec,
destination, source, len(source))
_NONCE_SIZE = 12
def set_iv(self, nonce, counter = 0):
self._IV_nonce = t2b(nonce)
if len(self._IV_nonce) != self._NONCE_SIZE:
raise ValueError("nonce must be %d bytes, got %d" %
(self._NONCE_SIZE, len(self._IV_nonce)))
self._IV_counter = counter
self._set_key(0)
if _lib.CHACHA20_POLY1305_ENABLED:
class ChaCha20Poly1305(object):
"""
ChaCha20-Poly1305 AEAD cipher.
One-shot encrypt/decrypt interface (non-streaming).
"""
_key_sizes = [32]
_tag_bytes = 16
def __init__(self, key):
self._key = t2b(key)
if len(self._key) not in self._key_sizes:
raise ValueError("key must be %s in length, not %d" %
(self._key_sizes, len(self._key)))
def encrypt(self, aad, iv, plaintext):
"""
Encrypt plaintext data using the IV/nonce provided. The
associated data (aad) is not encrypted but is included in the
authentication tag.
Returns a tuple of (ciphertext, authTag).
"""
aad = t2b(aad)
iv = t2b(iv)
if len(iv) != 12:
raise ValueError("iv must be 12 bytes, got %d" % len(iv))
plaintext = t2b(plaintext)
ciphertext = _ffi.new("byte[%d]" % len(plaintext))
authTag = _ffi.new("byte[%d]" % self._tag_bytes)
ret = _lib.wc_ChaCha20Poly1305_Encrypt(
_ffi.from_buffer(self._key),
_ffi.from_buffer(iv),
_ffi.from_buffer(aad),
len(aad),
_ffi.from_buffer(plaintext),
len(plaintext),
ciphertext,
authTag
)
if ret < 0:
raise WolfCryptError("Encryption error (%d)" % ret)
return bytes(ciphertext), bytes(authTag)
def decrypt(self, aad, iv, authTag, ciphertext):
"""
Decrypt the ciphertext using the IV/nonce and authentication tag
provided. The integrity of the associated data (aad) is checked.
Returns the decrypted plaintext.
"""
aad = t2b(aad)
iv = t2b(iv)
if len(iv) != 12:
raise ValueError("iv must be 12 bytes, got %d" % len(iv))
authTag = t2b(authTag)
if len(authTag) != self._tag_bytes:
raise ValueError("authTag must be %d bytes, got %d" %
(self._tag_bytes, len(authTag)))
ciphertext = t2b(ciphertext)
plaintext = _ffi.new("byte[%d]" % len(ciphertext))
ret = _lib.wc_ChaCha20Poly1305_Decrypt(
_ffi.from_buffer(self._key),
_ffi.from_buffer(iv),
_ffi.from_buffer(aad),
len(aad),
_ffi.from_buffer(ciphertext),
len(ciphertext),
_ffi.from_buffer(authTag),
plaintext
)
if ret < 0:
raise WolfCryptError("Decryption error (%d)" % ret)
return bytes(plaintext)
if _lib.DES3_ENABLED:
class Des3(_Cipher):
"""
**Triple DES** (3DES) is the common name for the **Triple Data
Encryption Algorithm** (TDEA or Triple DEA) symmetric-key block
cipher, which applies the **Data Encryption Standard** (DES)
cipher algorithm three times to each data block.
"""
block_size = 8
key_size = 24
_native_type = "Des3 *"
def _set_key(self, direction):
if direction == _ENCRYPTION:
return _lib.wc_Des3_SetKey(self._enc, self._key,
self._IV, _ENCRYPTION)
return _lib.wc_Des3_SetKey(self._dec, self._key,
self._IV, _DECRYPTION)
def _encrypt(self, destination, source):
return _lib.wc_Des3_CbcEncrypt(self._enc, destination,
source, len(source))
def _decrypt(self, destination, source):
return _lib.wc_Des3_CbcDecrypt(self._dec, destination,
source, len(source))
if _lib.RSA_ENABLED:
class _Rsa(object): # pylint: disable=too-few-public-methods
RSA_MIN_PAD_SIZE = 11
_mgf = None
_hash_type = None
def __init__(self):
self.native_object = _ffi.new("RsaKey *")
ret = _lib.wc_InitRsaKey(self.native_object, _ffi.NULL)
if ret < 0: # pragma: no cover
raise WolfCryptError("Invalid key error (%d)" % ret)
self._random = Random()
if _lib.RSA_BLINDING_ENABLED:
ret = _lib.wc_RsaSetRNG(self.native_object,
self._random.native_object)
if ret < 0: # pragma: no cover
raise WolfCryptError("Key initialization error (%d)" % ret)
# making sure _lib.wc_FreeRsaKey outlives RsaKey instances
_delete = _lib.wc_FreeRsaKey
def __del__(self):
if self.native_object:
self._delete(self.native_object)
def set_mgf(self, mgf):
self._mgf = mgf
def _get_mgf(self):
if self._hash_type == _lib.WC_HASH_TYPE_SHA:
self._mgf = _lib.WC_MGF1SHA1
elif self._hash_type == _lib.WC_HASH_TYPE_SHA224:
self._mgf = _lib.WC_MGF1SHA224
elif self._hash_type == _lib.WC_HASH_TYPE_SHA256:
self._mgf = _lib.WC_MGF1SHA256
elif self._hash_type == _lib.WC_HASH_TYPE_SHA384:
self._mgf = _lib.WC_MGF1SHA384
elif self._hash_type == _lib.WC_HASH_TYPE_SHA512:
self._mgf = _lib.WC_MGF1SHA512
else:
self._mgf = _lib.WC_MGF1NONE
class RsaPublic(_Rsa):
def __init__(self, key=None, hash_type=None):
if key != None:
key = t2b(key)
self._hash_type = hash_type
_Rsa.__init__(self)
idx = _ffi.new("word32*")
idx[0] = 0
ret = _lib.wc_RsaPublicKeyDecode(key, idx,
self.native_object, len(key))
if ret < 0:
raise WolfCryptError("Invalid key error (%d)" % ret)
self.output_size = _lib.wc_RsaEncryptSize(self.native_object)
self.size = len(key)
if self.output_size <= 0: # pragma: no cover
raise WolfCryptError("Invalid key error (%d)" %
self.output_size)
if _lib.ASN_ENABLED:
@classmethod
def from_pem(cls, file, hash_type=None):
der = pem_to_der(file, _lib.PUBLICKEY_TYPE)
return cls(key=der, hash_type=hash_type)
def encrypt(self, plaintext):
"""
Encrypts **plaintext**, using the public key data in the
object. The plaintext's length must not be greater than:
**self.output_size - self.RSA_MIN_PAD_SIZE**
Returns a string containing the ciphertext.
"""
plaintext = t2b(plaintext)
ciphertext = _ffi.new("byte[%d]" % self.output_size)
ret = _lib.wc_RsaPublicEncrypt(plaintext, len(plaintext),
ciphertext, self.output_size,
self.native_object,
self._random.native_object)
if ret != self.output_size: # pragma: no cover
raise WolfCryptError("Encryption error (%d)" % ret)
return _ffi.buffer(ciphertext)[:]
def encrypt_oaep(self, plaintext, label=""):
plaintext = t2b(plaintext)
label = t2b(label)
ciphertext = _ffi.new("byte[%d]" % self.output_size)
if self._mgf is None:
self._get_mgf()
ret = _lib.wc_RsaPublicEncrypt_ex(plaintext, len(plaintext),
ciphertext, self.output_size,
self.native_object,
self._random.native_object,
_lib.WC_RSA_OAEP_PAD, self._hash_type,
self._mgf, label, len(label))
if ret != self.output_size: # pragma: no cover
raise WolfCryptError("Encryption error (%d)" % ret)
return _ffi.buffer(ciphertext)[:]
def verify(self, signature):
"""
Verifies **signature**, using the public key data in the
object. The signature's length must be equal to:
**self.output_size**
Returns a string containing the plaintext.
"""
signature = t2b(signature)
plaintext = _ffi.new("byte[%d]" % self.output_size)
ret = _lib.wc_RsaSSL_Verify(signature, len(signature),
plaintext, self.output_size,
self.native_object)
if ret < 0: # pragma: no cover
raise WolfCryptError("Verify error (%d)" % ret)
return _ffi.buffer(plaintext, ret)[:]
if _lib.RSA_PSS_ENABLED:
def verify_pss(self, plaintext, signature):
"""
Verifies **signature**, using the public key data in the
object. The signature's length must be equal to:
**self.output_size**
Returns a string containing the plaintext.
"""
if not self._hash_type:
raise WolfCryptError(("Hash type not set. Cannot verify a "
"PSS signature without a hash type."))
hash_cls = hash_type_to_cls(self._hash_type)
if not hash_cls:
raise WolfCryptError("Unsupported PSS hash type.")
plaintext = t2b(plaintext)
signature = t2b(signature)
if self._mgf is None:
self._get_mgf()
verify = _ffi.new("byte[%d]" % self.output_size)
ret = _lib.wc_RsaPSS_Verify(signature, len(signature),
verify, self.output_size,
self._hash_type, self._mgf,
self.native_object)
if ret < 0: # pragma: no cover
raise WolfCryptError("Verify error (%d)" % ret)
digest = hash_cls.new(plaintext).digest()
ret = _lib.wc_RsaPSS_CheckPadding(digest, len(digest),
verify, ret, self._hash_type)
if ret < 0: # pragma: no cover
raise WolfCryptError("PSS padding check error (%d)" % ret)
return ret == 0
class RsaPrivate(RsaPublic):
if _lib.KEYGEN_ENABLED:
@classmethod
def make_key(cls, size, rng=Random(), hash_type=None):
"""
Generates a new key pair of desired length **size**.
"""
rsa = cls(hash_type=hash_type)
if rsa == None: # pragma: no cover
raise WolfCryptError("Invalid key error (%d)" % ret)
ret = _lib.wc_MakeRsaKey(rsa.native_object, size, 65537,
rng.native_object)
if ret < 0:
raise WolfCryptError("Key generation error (%d)" % ret)
rsa.output_size = _lib.wc_RsaEncryptSize(rsa.native_object)
rsa.size = size
if rsa.output_size <= 0: # pragma: no cover
raise WolfCryptError("Invalid key size error (%d)" % ret)
return rsa
def __init__(self, key=None, hash_type=None): # pylint: disable=super-init-not-called
_Rsa.__init__(self) # pylint: disable=non-parent-init-called
self._hash_type = hash_type
idx = _ffi.new("word32*")
idx[0] = 0
if key != None:
key = t2b(key)
ret = _lib.wc_RsaPrivateKeyDecode(key, idx,
self.native_object, len(key))
if ret < 0:
idx[0] = 0
ret = _lib.wc_GetPkcs8TraditionalOffset(key, idx, len(key))
if ret < 0:
raise WolfCryptError("Invalid key error (%d)" % ret)
ret = _lib.wc_RsaPrivateKeyDecode(key, idx,
self.native_object, len(key))
if ret < 0:
raise WolfCryptError("Invalid key error (%d)" % ret)
self.size = len(key)
self.output_size = _lib.wc_RsaEncryptSize(self.native_object)
if self.output_size <= 0: # pragma: no cover
raise WolfCryptError("Invalid key size error (%d)" %
self.output_size)
if _lib.ASN_ENABLED:
@classmethod
def from_pem(cls, file, hash_type=None):
der = pem_to_der(file, _lib.PRIVATEKEY_TYPE)
return cls(key=der, hash_type=hash_type)
if _lib.KEYGEN_ENABLED:
def encode_key(self):
"""
Encodes the RSA private and public keys in an ASN sequence.
Returns the encoded key.
"""
priv = _ffi.new("byte[%d]" % (self.size * 4))
pub = _ffi.new("byte[%d]" % (self.size * 4))
ret = _lib.wc_RsaKeyToDer(self.native_object, priv, self.size)
if ret <= 0: # pragma: no cover
raise WolfCryptError("Private RSA key error (%d)" % ret)
privlen = ret
ret = _lib.wc_RsaKeyToPublicDer(self.native_object, pub,
self.size)
if ret <= 0: # pragma: no cover
raise WolfCryptError("Public RSA key encode error (%d)" %
ret)
publen = ret
return _ffi.buffer(priv, privlen)[:], _ffi.buffer(pub,
publen)[:]
def decrypt(self, ciphertext):
"""
Decrypts **ciphertext**, using the private key data in the
object. The ciphertext's length must be equal to:
**self.output_size**
Returns a string containing the plaintext.
"""
ciphertext = t2b(ciphertext)
plaintext = _ffi.new("byte[%d]" % self.output_size)
ret = _lib.wc_RsaPrivateDecrypt(ciphertext, len(ciphertext),
plaintext, self.output_size,
self.native_object)
if ret < 0: # pragma: no cover
raise WolfCryptError("Decryption error (%d)" % ret)
return _ffi.buffer(plaintext, ret)[:]
def decrypt_oaep(self, ciphertext, label=""):
"""
Decrypts **ciphertext**, using the private key data in the
object. The ciphertext's length must be equal to:
**self.output_size**
Returns a string containing the plaintext.
"""
ciphertext = t2b(ciphertext)
label = t2b(label)
plaintext = _ffi.new("byte[%d]" % self.output_size)
if self._mgf is None:
self._get_mgf()
ret = _lib.wc_RsaPrivateDecrypt_ex(ciphertext, len(ciphertext),
plaintext, self.output_size,
self.native_object,
_lib.WC_RSA_OAEP_PAD, self._hash_type,
self._mgf, label, len(label))
if ret < 0: # pragma: no cover
raise WolfCryptError("Decryption error (%d)" % ret)
return _ffi.buffer(plaintext, ret)[:]
def sign(self, plaintext):
"""
Signs **plaintext**, using the private key data in the object.
The plaintext's length must not be greater than:
**self.output_size - self.RSA_MIN_PAD_SIZE**
Returns a string containing the signature.
"""
plaintext = t2b(plaintext)
signature = _ffi.new("byte[%d]" % self.output_size)
ret = _lib.wc_RsaSSL_Sign(plaintext, len(plaintext),
signature, self.output_size,
self.native_object,
self._random.native_object)
if ret != self.output_size: # pragma: no cover
raise WolfCryptError("Signature error (%d)" % ret)
return _ffi.buffer(signature, self.output_size)[:]
if _lib.RSA_PSS_ENABLED:
def sign_pss(self, plaintext):
"""
Signs **plaintext**, using the private key data in the object.
The plaintext's length must not be greater than:
**self.output_size - self.RSA_MIN_PAD_SIZE**
Returns a string containing the signature.
"""
if not self._hash_type:
raise WolfCryptError(("Hash type not set. Cannot verify a "
"PSS signature without a hash type."))
hash_cls = hash_type_to_cls(self._hash_type)
if not hash_cls:
raise WolfCryptError("Unsupported PSS hash type.")
plaintext = t2b(plaintext)
digest = hash_cls.new(plaintext).digest()
signature = _ffi.new("byte[%d]" % self.output_size)
if self._mgf is None:
self._get_mgf()
ret = _lib.wc_RsaPSS_Sign(digest, len(digest),
signature, self.output_size,