This repository was archived by the owner on Dec 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_rsa.py
More file actions
65 lines (51 loc) · 1.77 KB
/
_rsa.py
File metadata and controls
65 lines (51 loc) · 1.77 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
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
class RSACipher():
def __init__(self) -> None:
self.publicKey = None
self.privateKey = None
pass
def GenerateKey(self):
rsa = RSA.generate(1024, Crypto.Random.new().read)
# master的祕鑰對的生成
private_pem = rsa.exportKey()
public_pem = rsa.publickey().exportKey()
self.publicKey = public_pem.decode()
self.privateKey = private_pem.decode()
return {
"public_key": self.publicKey,
"private_key": self.privateKey
}
def PublicKeyImport(self, PublicKey):
self.publicKey = PublicKey;
pass
# 公鑰加密
def rsa_encode(self, message):
rsakey = RSA.importKey(self.publicKey)
cipher = PKCS1_v1_5.new(rsakey)
cipher_text = base64.b64encode(
cipher.encrypt(message.encode(encoding="utf-8")))
return cipher_text.decode()
# 公鑰解密
def rsa_decode(self, cipher_text):
rsakey = RSA.importKey(self.privateKey)
cipher = PKCS1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
return text.decode()
if __name__ == '__main__':
print("Case 1:")
a = RSACipher()
a.GenerateKey()
encrypt = a.rsa_encode("This is the testing message form case 1")
decrypt = a.rsa_decode(encrypt)
print("[ENCRYPTED]{}".format(encrypt))
print("[DECRYPTED]{}".format(decrypt))
print("\nCase 2:")
b = RSACipher()
b.PublicKeyImport(a.publicKey)
encrypt = b.rsa_encode("This is the testing message form case 2")
decrypt = a.rsa_decode(encrypt)
print("[ENCRYPTED]{}".format(encrypt))
print("[DECRYPTED]{}".format(decrypt))