Created
May 26, 2018 18:08
-
-
Save wagnerluis1982/6057de8d6fffd145e37a43ae160654ad to your computer and use it in GitHub Desktop.
Crypt functions in Python that mimic Java's PBEWithMD5AndDES algorithm to produce a DES key
This file contains 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
"""Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key | |
Closely based in https://stackoverflow.com/a/44509919 | |
""" | |
import base64 | |
import re | |
from Crypto.Cipher import DES | |
from Crypto.Hash import MD5 | |
def init_crypt_functions(): | |
password = b'0725W_37B610++MKLE7#@0PPY310' | |
salt = b'\xA9\x9B\xC8\x32\x56\x35\xE3\x03' | |
iterations = 1000 | |
hasher = MD5.new() | |
hasher.update(password) | |
hasher.update(salt) | |
result = hasher.digest() | |
for i in range(1, iterations): | |
hasher = MD5.new() | |
hasher.update(result) | |
result = hasher.digest() | |
def encrypt(data): | |
# Pad plaintext per RFC 2898 Section 6.1 | |
padding = 8 - len(data) % 8 | |
data += chr(padding) * padding | |
des = DES.new(result[:8], DES.MODE_CBC, result[8:16]) | |
encrypted = des.encrypt(data) | |
return base64.b64encode(encrypted).decode('UTF-8') | |
def decrypt(data): | |
encrypted = base64.b64decode(data) | |
des = DES.new(result[:8], DES.MODE_CBC, result[8:]) | |
decrypted = des.decrypt(encrypted) | |
# Remove padding | |
padding = decrypted[-1] | |
pattern = br'%s{%d}$' % (padding.to_bytes(1, 'little'), padding) | |
decrypted, subs = re.subn(pattern, b'', decrypted) | |
# Check if padding is valid | |
if subs != 1: | |
raise ValueError("decryption error: %d" % subs) | |
return decrypted | |
return encrypt, decrypt | |
encrypt, decrypt = init_crypt_functions() | |
del init_crypt_functions |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment