Created
July 1, 2016 23:54
-
-
Save tmarthal/b6f8c83aff9d643ce17385b07158f2f7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import binascii | |
# PyCryptodome, NOT pycrypto | |
from Crypto.Cipher import AES | |
from Crypto.Protocol.KDF import PBKDF2 | |
class AesCrypt256: | |
#Based on https://gist.github.com/pfote/5099161 | |
BLOCK_SIZE = 16 | |
def pkcs5_pad(self,s): | |
""" | |
padding to blocksize according to PKCS #5 | |
calculates the number of missing chars to BLOCK_SIZE and pads with | |
ord(number of missing chars) | |
@see: http://www.di-mgt.com.au/cryptopad.html | |
@param s: string to pad | |
@type s: string | |
@rtype: string | |
""" | |
return s + (self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) * chr(self.BLOCK_SIZE - len(s) % self.BLOCK_SIZE) | |
def pkcs5_unpad(self,s): | |
""" | |
unpadding according to PKCS #5 | |
@param s: string to unpad | |
@type s: string | |
@rtype: string | |
""" | |
return s[0:-ord(s[-1])] | |
def encrypt(self, key, value): | |
"""Encrypt value by key | |
@param key: key to encrypt with | |
@type key: string | |
@param value: value to encrypt | |
@type value: string | |
@rtype: string | |
""" | |
iv = bytes(bytearray(16)) | |
cipher = AES.new(key, AES.MODE_CBC, iv) | |
crypted = cipher.encrypt(self.pkcs5_pad(value).encode('utf-8')) | |
#return iv+crypted | |
return crypted | |
def decrypt(self, key, value): | |
"""Decrypt value by key | |
@param key: key to decrypt with | |
@type key: string | |
@param value: value to decrypt | |
@type value: string | |
@rtype: string | |
TM Note: does not unpad | |
""" | |
# we do not have an IV present | |
iv = bytes(bytearray(16)) | |
cipher = AES.new(key, AES.MODE_CBC, iv) | |
return cipher.decrypt(value) | |
def encryptHex(self, key, value): | |
""" | |
hex | |
""" | |
return binascii.hexlify(self.encrypt(key, value)) | |
def decryptHex(self, key, value): | |
""" | |
hex | |
""" | |
return self.decrypt(key, binascii.unhexlify(value)).decode("utf-8") | |
if __name__ == '__main__': | |
iterations = 1024 | |
password = 'password' | |
salt = binascii.unhexlify('5c0744940b5c369b') | |
# AES uses 256 bit encryption, 32 bytes | |
key = PBKDF2(password=password, salt=salt, dkLen=32, count=iterations) | |
java_string = 'a070fa1b40dafa6d7c55ee697c4cb448' | |
encryptor = AesCrypt256() | |
encrypted = encryptor.encryptHex(key, 'foo') | |
print(encryptor.decryptHex(key, encrypted)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment