-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSAcipher.py
More file actions
55 lines (40 loc) · 1.48 KB
/
Copy pathRSAcipher.py
File metadata and controls
55 lines (40 loc) · 1.48 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
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from base64 import b64encode, b64decode
import os
class RSAcipher:
def __init__(self, certfile=None, key=None):
try:
if key is not None:
self.key = RSA.importKey(key)
elif certfile is not None:
self.key = RSA.importKey(open(certfile).read())
else:
self.key = RSA.generate(2048)
_pubkey = self.key.publickey()
self.pubkey = _pubkey.exportKey()
self.privkey = self.key.exportKey('PEM')
self.rsa = PKCS1_OAEP.new(self.key)
except Exception as e:
print('Error initializing RSAcipher : ' + e.message)
self.key = None
def create_keyset(self, name='key'):
self.key = RSA.generate(2048)
with open(name + '.key', 'wb') as f:
f.write(self.key.exportKey('PEM'))
self.pubkey = self.key.publickey()
with open(name + '.pub', 'wb') as f:
f.write(self.pubkey.exportKey())
return self.key
def encrypt(self, text):
return b64encode(self.rsa.encrypt(text.encode())).decode()
def decrypt(self, msg):
try:
return self.rsa.decrypt(b64decode(msg)).decode()
except Exception as e:
return None
def main():
rsa = RSAcipher()
rsa.create_keyset(os.getenv('USERPROFILE') + r'\\.ssh\\' + os.getenv('USERNAME'))
if __name__ == "__main__":
main()