1
1
import random
2
- from sympy import isprime , mod_inverse
3
2
import sys
3
+ from sympy import isprime , mod_inverse
4
4
5
5
def generate_prime_candidate (length ):
6
6
"""
@@ -43,8 +43,14 @@ def generate_keys(keysize):
43
43
d = mod_inverse (e , phi )
44
44
45
45
return ((e , n ), (d , n ))
46
+ except ValueError as ex :
47
+ print (f"Value error generating keys: { ex } " , file = sys .stderr )
48
+ sys .exit (1 )
49
+ except TypeError as ex :
50
+ print (f"Type error generating keys: { ex } " , file = sys .stderr )
51
+ sys .exit (1 )
46
52
except Exception as ex :
47
- print (f"Error generating keys: { ex } " , file = sys .stderr )
53
+ print (f"Unexpected error generating keys: { ex } " , file = sys .stderr )
48
54
sys .exit (1 )
49
55
50
56
def gcd (a , b ):
@@ -71,8 +77,11 @@ def encrypt(pk, plaintext):
71
77
key , n = pk
72
78
cipher = [(ord (char ) ** key ) % n for char in plaintext ]
73
79
return cipher
80
+ except TypeError as ex :
81
+ print (f"Type error during encryption: { ex } " , file = sys .stderr )
82
+ return None
74
83
except Exception as ex :
75
- print (f"Error during encryption: { ex } " , file = sys .stderr )
84
+ print (f"Unexpected error during encryption: { ex } " , file = sys .stderr )
76
85
return None
77
86
78
87
def decrypt (pk , ciphertext ):
@@ -89,8 +98,11 @@ def decrypt(pk, ciphertext):
89
98
key , n = pk
90
99
plain = [chr ((char ** key ) % n ) for char in ciphertext ]
91
100
return '' .join (plain )
101
+ except TypeError as ex :
102
+ print (f"Type error during decryption: { ex } " , file = sys .stderr )
103
+ return None
92
104
except Exception as ex :
93
- print (f"Error during decryption: { ex } " , file = sys .stderr )
105
+ print (f"Unexpected error during decryption: { ex } " , file = sys .stderr )
94
106
return None
95
107
96
108
if __name__ == '__main__' :
@@ -115,6 +127,12 @@ def decrypt(pk, ciphertext):
115
127
print ("Decryption failed." , file = sys .stderr )
116
128
else :
117
129
print ("Encryption failed." , file = sys .stderr )
130
+ except ValueError as ex :
131
+ print (f"Value error: { ex } " , file = sys .stderr )
132
+ sys .exit (1 )
133
+ except TypeError as ex :
134
+ print (f"Type error: { ex } " , file = sys .stderr )
135
+ sys .exit (1 )
118
136
except Exception as ex :
119
- print (f"An error occurred : { ex } " , file = sys .stderr )
137
+ print (f"Unexpected error: { ex } " , file = sys .stderr )
120
138
sys .exit (1 )
0 commit comments