43 lines
1020 B
Python
43 lines
1020 B
Python
# standard imports
|
|
import os
|
|
import logging
|
|
import hashlib
|
|
|
|
from Crypto.Cipher import AES
|
|
from Crypto.Util import Counter
|
|
|
|
from .base import Encrypter
|
|
|
|
logg = logging.getLogger(__name__)
|
|
|
|
|
|
class AESCTREncrypt(Encrypter):
|
|
|
|
aes_block_size = 1 << 7
|
|
counter_bytes = int(128 / 8)
|
|
|
|
def __init__(self, db_dir, secret):
|
|
self.secret = secret
|
|
|
|
|
|
def key_to_iv(self, k):
|
|
h = hashlib.sha256()
|
|
h.update(k.encode('utf-8'))
|
|
h.update(self.secret)
|
|
z = h.digest()
|
|
return int.from_bytes(z[:self.counter_bytes], 'big')
|
|
|
|
|
|
def encrypt(self, k, v):
|
|
iv = self.key_to_iv(k)
|
|
ctr = Counter.new(self.aes_block_size, initial_value=iv)
|
|
cipher = AES.new(self.secret, AES.MODE_CTR, counter=ctr)
|
|
return cipher.encrypt(v)
|
|
|
|
|
|
def decrypt(self, k, v):
|
|
iv = self.key_to_iv(k)
|
|
ctr = Counter.new(self.aes_block_size, initial_value=iv)
|
|
cipher = AES.new(self.secret, AES.MODE_CTR, counter=ctr)
|
|
return cipher.decrypt(v)
|