5
5
import io
6
6
import uuid
7
7
8
- from Crypto .Cipher import PKCS1_OAEP , AES
9
- from Crypto .PublicKey import RSA
10
- from Crypto .Signature import PKCS1_v1_5
11
- from Crypto .Hash import SHA1
8
+ try :
9
+ from Cryptodome .Cipher import PKCS1_OAEP , AES
10
+ from Cryptodome .Hash import SHA1
11
+ from Cryptodome .PublicKey import RSA
12
+ from Cryptodome .Signature import pkcs1_15 as PKCS1_v1_5
13
+ usingCryptodome = True
14
+ except ImportError :
15
+ from Crypto .Cipher import PKCS1_OAEP , AES
16
+ from Crypto .Hash import SHA1
17
+ from Crypto .PublicKey import RSA
18
+ from Crypto .Signature import PKCS1_v1_5
19
+ usingCryptodome = False
12
20
13
21
14
22
def encrypt (recipient_key_txt : str , data : str ):
@@ -24,20 +32,25 @@ def encrypt(recipient_key_txt: str, data: str):
24
32
25
33
# Encrypt the data with the AES session keynonce: str, nonce: str,
26
34
cipher_aes = AES .new (session_key , AES .MODE_EAX , uuid .uuid4 ().bytes )
27
- ciphertext , tag = cipher_aes .encrypt_and_digest (data )
35
+ if usingCryptodome :
36
+ ciphertext , tag = cipher_aes .encrypt_and_digest (bytes (data , 'utf-8' ))
37
+ else :
38
+ ciphertext , tag = cipher_aes .encrypt_and_digest (data )
28
39
[out .write (x ) for x in (cipher_aes .nonce , tag , ciphertext )]
29
40
out .seek (0 )
30
41
return out .getvalue ()
31
42
32
43
33
44
def decrypt (private_key_txt : str , encrypted : bytes ):
34
-
35
45
private_key = RSA .importKey (private_key_txt )
36
- private_key_size = int ((private_key .size () + 1 )/ 8 )
46
+ if usingCryptodome :
47
+ private_key_size = int ((private_key .size_in_bits () + 1 )/ 8 )
48
+ else :
49
+ private_key_size = int ((private_key .size () + 1 )/ 8 )
37
50
38
51
buffer = io .BytesIO (encrypted )
39
52
session_key , nonce , tag , ciphertext = \
40
- [buffer .read (x ) for x in (private_key_size , 16 , 16 , - 1 )]
53
+ [buffer .read (x ) for x in (private_key_size , 16 , 16 , - 1 )]
41
54
42
55
# Decrypt the session key with the public RSA key
43
56
cipher_rsa = PKCS1_OAEP .new (private_key )
@@ -56,8 +69,15 @@ def sign_message_sha1(key_txt: str, message: str):
56
69
return PKCS1_v1_5 .new (key ).sign (sha1 )
57
70
58
71
59
- def verify_signature (sender_key_txt : str , contents : str , signature : str ):
72
+ def verify_signature (sender_key_txt : str , contents : str , signature : bytes ):
60
73
sender_key = RSA .importKey (sender_key_txt )
61
74
sha1 = SHA1 .new ()
62
75
sha1 .update (contents .encode ())
63
- return PKCS1_v1_5 .new (sender_key ).verify (sha1 , signature )
76
+ if usingCryptodome :
77
+ try :
78
+ PKCS1_v1_5 .new (sender_key ).verify (sha1 , signature )
79
+ return True
80
+ except ValueError :
81
+ return False
82
+ else :
83
+ return PKCS1_v1_5 .new (sender_key ).verify (sha1 , signature )
0 commit comments