-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcryptlib.py
More file actions
71 lines (61 loc) · 2.07 KB
/
cryptlib.py
File metadata and controls
71 lines (61 loc) · 2.07 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
65
66
67
68
69
70
71
import os
import sys
import config, Config
Config.config.disable_sslcompression = False
import CryptMessage
from lib import pyelliptic
from lib.pybitcointools import bitcoin as btctools
import base64
def encrypt(text, publickey):
encrypted = CryptMessage.encrypt(text, CryptMessage.toOpensslPublickey(publickey))
return encrypted
def decrypt(encrypted, privatekey):
back = CryptMessage.getEcc(privatekey).decrypt(encrypted)
return back.decode("utf8")
# Encrypt a text using the publickey
# Return: Encrypted text and AES key using base64 encoding
def eciesEncrypt(text, publickey):
aes_key, encrypted = encrypt(text.encode("utf8"), publickey.decode("base64"))
return (base64.b64encode(encrypted), base64.b64encode(aes_key))
# Decrypt a text using privatekey
# Return: Decrypted text
def eciesDecrypt(encrypted_text, privatekey):
try:
return decrypt(encrypted_text.decode("base64"), privatekey)
except Exception as err:
return None
# Encrypt a text using AES
# Return: Iv, AES key, Encrypted text
def aesEncrypt(text, key=None, iv=None):
if key:
key = key.decode("base64")
else:
key = os.urandom(32)
if iv: # Generate new AES key if not definied
iv = iv.decode("base64")
else:
iv = pyelliptic.Cipher.gen_IV('aes-256-cbc')
if text:
encrypted = pyelliptic.Cipher(key, iv, 1, ciphername='aes-256-cbc').ciphering(text.encode("utf8"))
else:
encrypted = ""
return (base64.b64encode(key), base64.b64encode(iv), base64.b64encode(encrypted))
# Decrypt a text using AES
# Return: Decrypted text
def aesDecrypt(iv, encrypted_text, key):
encrypted_text = encrypted_text.decode("base64")
iv = iv.decode("base64")
text = None
ctx = pyelliptic.Cipher(key.decode("base64"), iv, 0, ciphername='aes-256-cbc')
try:
decrypted = ctx.ciphering(encrypted_text)
if decrypted and decrypted.decode("utf8"): # Valid text decoded
return decrypted
except Exception, err:
pass
return None
# Transform private key to public key
def private_to_public(private):
public = btctools.encode_pubkey(btctools.privtopub(private), "bin_compressed")
public = base64.b64encode(public)
return public