-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsecure.py
executable file
·68 lines (56 loc) · 2.67 KB
/
secure.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
import time, base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from Crypto.Hash import SHA,SHA224,SHA256, SHA384, SHA512, HMAC
from Crypto.Random import random
from Crypto import Random
from string import ascii_lowercase
from Crypto.Cipher import PKCS1_v1_5,AES
from Crypto.Protocol.KDF import PBKDF2
BlockSize = 16
pad = lambda s: s + (BlockSize - len(s) % BlockSize) * chr(BlockSize - len(s) % BlockSize)
unpad = lambda s : s[:-ord(s[len(s)-1:])]
class Secure:
def SHA256(self, message):
return SHA256.new(message).digest()
###############################################SYMMETRIC############################################################
def AES(self, message, key): # iv vai encapsulado
message_b = bytes(message)
iv = Random.new().read(AES.block_size)
cipher = AES.new(key, AES.MODE_CBC, iv)
msg = iv + cipher.encrypt(pad(message_b))
return msg
def symmetricKey(self, bits):
bits = int(bits)
if bits == 128:
key = bytes(''.join(random.choice(ascii_lowercase) for i in range(16)))
if bits == 256:
key = bytes(''.join(random.choice(ascii_lowercase) for i in range(32)))
return key
def D_AES(self, symKey, message):
message_b = bytes(message)
cipher = AES.new(symKey, AES.MODE_CBC, message_b[:AES.block_size])
msg = cipher.decrypt(message_b[AES.block_size:])
return unpad(msg)
################################################ASSYMETRIC##########################################################
def get_keys(self, passphrase=None): # RSA Key Pairs
new_key = RSA.generate(2048)
return (new_key.publickey().exportKey(format='PEM'),new_key.exportKey(format='PEM', passphrase=passphrase))
## https://www.dlitz.net/software/pycrypto/api/2.6/
def rsaCipher(self, message, key):
h = SHA.new(message)
cipher = PKCS1_v1_5.new(key) #instance
ciphered_text = cipher.encrypt(message + h.digest())
return base64.b64encode(ciphered_text)
def rsaDecipher(self, message, key):
dsize = SHA.digest_size
ciphered_key = base64.b64decode(message)
flag = Random.new().read(len(ciphered_key) / 2 + dsize) # Let's assume that average data length is 15
cipher = PKCS1_v1_5.new(key)
symmetric_key = cipher.decrypt(ciphered_key, flag)
return symmetric_key[:-dsize]
# key derivation function
#https://www.dlitz.net/software/pycrypto/api/2.6/Crypto.Protocol.KDF-module.html
def kdf(self, pw, salt, klen, count, prf=None):
key = PBKDF2(password=pw, salt=salt, dkLen=klen, count=count,prf=prf)
return key