-
Notifications
You must be signed in to change notification settings - Fork 7
/
rsa_wrapper.py
77 lines (63 loc) · 2.32 KB
/
rsa_wrapper.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
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env python
# basic rsa functions
import sys
import zlib
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA256
class rsa_wrapper():
def keygen(self):
key = RSA.generate(2048, e=65537)
public = key.publickey().exportKey("PEM")
private = key.exportKey("PEM")
return public, private
def encrypt(self, public, plaintext):
rsakey = RSA.importKey(public)
rsakey = PKCS1_OAEP.new(rsakey)
offset = 0
encrypted = ""
plaintext = zlib.compress(plaintext)
while offset < len(plaintext):
encrypted += rsakey.encrypt(plaintext[offset:offset+256])
offset += 256
encrypted = base64.b64encode(encrypted)
return encrypted
def decrypt(self, private, ciphertext):
rsakey = RSA.importKey(private)
rsakey = PKCS1_OAEP.new(rsakey)
offset = 0
decrypted = ""
ciphertext = base64.b64decode(ciphertext)
while offset < len(ciphertext):
decrypted += rsakey.decrypt(ciphertext[offset:offset+256])
offset += 256
decrypted = zlib.decompress(decrypted)
return decrypted
def sign(self, private, plaintext):
rsakey = RSA.importKey(private)
hashed = SHA256.new(plaintext).digest()
signature = rsakey.sign(hashed, '')
return signature
def verify(self, public, signature, plaintext):
rsakey = RSA.importKey(public)
hashed = SHA256.new(plaintext).digest()
verified = rsakey.verify(hashed, signature)
return verified
if __name__ == '__main__':
try:
message = sys.argv[1]
rsa = rsa_wrapper()
public, private = rsa.keygen()
print "Public Key is:\n{}\n".format(public)
print "Private Key is:\n{}\n".format(private)
encrypted_message = rsa.encrypt(public, message)
print "Test message encrypted with public key is:\n{}\n".format(encrypted_message)
decrypted_message = rsa.decrypt(private, encrypted_message)
print "Testing decryption function to return orginal message:\n{}\n".format(decrypted_message)
signature = rsa.sign(private, message)
print "Plaintext message signature is:\n{}\n".format(signature)
verified = rsa.verify(public, signature, message)
print "Verifying the plaintext against the signature results in:\n{}\n".format(verified)
except IndexError:
print "python rsa_wrapper.py <Test message to encrypt>"