-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathKriptaRSA.py
66 lines (51 loc) · 2.03 KB
/
KriptaRSA.py
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
from Crypto.Protocol.KDF import PBKDF2
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Cipher import AES
import base64
class KriptaRSA:
def __init__(self, keysize = 1024):
self.keysize = keysize
self.public_key = b""
self.private_key = b""
def toBytes(self, m):
return m.encode() if type(m) == str else m
# Setters and getters
def getKeySize(self):
return self.keysize
def setKeySize(self, m):
self.keysize = m
# Setters and getters
def getPublicKey(self):
return self.public_key
def setPublicKey(self, m):
self.public_key = self.toBytes(m)
# Setters and getters
def getPrivateKey(self):
return self.private_key
def setPrivateKey(self, m):
self.private_key = self.toBytes(m)
def generate_RSA(self):
new_key = RSA.generate(self.keysize, e=65537)
self.setPublicKey(new_key.publickey().exportKey("PEM"))
self.setPrivateKey(new_key.exportKey("PEM"))
return self.getPrivateKey(), self.getPublicKey()
def encrypt(self, key, plaintext):
# Assuming that the public key is coming from java or javascript,
# strip off the headers.
# if it's bytes, then convert to string
if type(key) == bytes:
key = key.decode('utf-8')
key = key.replace('-----BEGIN PUBLIC KEY-----', '').replace('-----END PUBLIC KEY-----', '')
# Since it's coming from java/javascript, it's base 64 encoded.
# Decode before importing.
pubkey = RSA.importKey(base64.b64decode(key))
cipher = PKCS1_OAEP.new(pubkey, hashAlgo=SHA256)
encrypted = cipher.encrypt(plaintext)
return base64.b64encode(encrypted).decode('utf-8')
def decrypt(self, ciphertext):
rsa_key = RSA.importKey(self.getPrivateKey())
cipher = PKCS1_OAEP.new(rsa_key, hashAlgo=SHA256)
decrypted = cipher.decrypt(base64.b64decode(ciphertext))
return decrypted.decode('utf-8')