5

If it's not immediately obvious, let me start by saying I am not a crypto person.

I have been tasked with replicating the behavior of Java's PBEWithMD5AndDES (MD5 digest with DES encryption) in Python 2.7.

I do have access to Python's cryptography toolkit PyCrypto.

Here is the Java code whose behavior I am trying to replicate:

import java.security.spec.KeySpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.Cipher;
import javax.xml.bind.DatatypeConverter;

public class EncryptInJava
{
    public static void main(String[] args)
    {
      String encryptionPassword = "q1w2e3r4t5y6";
      byte[] salt = { -128, 64, -32, 16, -8, 4, -2, 1 };
      int iterations = 50;

      try
      {
        KeySpec keySpec = new PBEKeySpec(encryptionPassword.toCharArray(), salt, iterations);
        SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterations);

        Cipher encoder = Cipher.getInstance(key.getAlgorithm());
        encoder.init(Cipher.ENCRYPT_MODE, key, paramSpec);

        String str_to_encrypt = "MyP455w0rd";
        byte[] enc = encoder.doFinal(str_to_encrypt.getBytes("UTF8"));

        System.out.println("encrypted = " + DatatypeConverter.printBase64Binary(enc));
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }
}

For the given values, it outputs the following:

encrypted = Icy6sAP7adLgRoXNYe9N8A==

Here's my ham-handed attempt to port the above to Python, encrypt_in_python.py:

from Crypto.Hash import MD5
from Crypto.Cipher import DES

_password = 'q1w2e3r4t5y6'
_salt = '\x80\x40\xe0\x10\xf8\x04\xfe\x01'
_iterations = 50
plaintext_to_encrypt = 'MyP455w0rd'

if "__main__" == __name__:

    """Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key"""
    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()

    key = result[:8]

    encoder = DES.new(key)
    encrypted = encoder.encrypt(plaintext_to_encrypt + ' ' * (8 - (len(plaintext_to_encrypt) % 8)))
    print encrypted.encode('base64')

It outputs a completely different string.

Is it possible to port the Java implementation to a Python implementation with standard Python libraries?

Apparently the Python implementation requires that the plaintext that I encrypt be a multiple of eight characters, and I'm not even sure exactly how to pad my plaintext input to meet that condition.

Thanks for your help.

Tebbe
  • 1,372
  • 9
  • 12
  • See [rfc 2898](http://tools.ietf.org/html/rfc2898), specifically [section 6.1](http://tools.ietf.org/html/rfc2898#section-6.1). You need to use DES in CBC mode with the key being the first 8 bytes and the IV being the second 8 bytes of your hash result. – President James K. Polk Jun 11 '14 at 22:25
  • This is a bad password derivation method and shouldn't be used. Instead iterate over an HMAC with a random salt for about a 100ms duration (the salt needs to be saved with the hash). Use functions such as password_hash, PBKDF2, Bcrypt and similar functions. The point is to make the attacker spend a lot of time finding passwords by brute force. See OWASP (Open Web Application Security Project) [Password Storage Cheat Sheet](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet#Leverage_an_adaptive_one-way_function). – zaph Jul 10 '16 at 14:00
  • Also see [How to securely hash passwords, The Theory](http://security.stackexchange.com/questions/211/how-to-securely-hash-passwords/31846#31846) on Security Stackexchange. – zaph Jul 10 '16 at 14:00

4 Answers4

3

For Python 3.6, I tested with following code and it works with a little change from above:

from Crypto.Hash import MD5
from Crypto.Cipher import DES
import base64
import re

_password = b'q1w2e3r4t5y6'
_salt = b'\x80\x40\xe0\x10\xf8\x04\xfe\x01'

_iterations = 50

plaintext_to_encrypt = 'MyP455w0rd'

# Pad plaintext per RFC 2898 Section 6.1
padding = 8 - len(plaintext_to_encrypt) % 8
plaintext_to_encrypt += chr(padding) * padding

if "__main__" == __name__:

    """Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key"""
    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()

    encoder = DES.new(result[:8], DES.MODE_CBC, result[8:16])
    encrypted = encoder.encrypt(plaintext_to_encrypt)

    print (str(base64.b64encode(encrypted),'utf-8'))

    decoder = DES.new(result[:8], DES.MODE_CBC, result[8:])
    d = str(decoder.decrypt(encrypted),'utf-8')
    print (re.sub(r'[\x01-\x08]','',d))

Output:

Icy6sAP7adLgRoXNYe9N8A==

MyP455w0rd

Community
  • 1
  • 1
Edmond Wong
  • 141
  • 1
  • 4
2

Thanks to GregS's comment, I was able to sort this conversion out!

For future reference, this Python code mimics the behavior of the Java code above:

from Crypto.Hash import MD5
from Crypto.Cipher import DES

_password = 'q1w2e3r4t5y6'
_salt = '\x80\x40\xe0\x10\xf8\x04\xfe\x01'
_iterations = 50
plaintext_to_encrypt = 'MyP455w0rd'

# Pad plaintext per RFC 2898 Section 6.1
padding = 8 - len(plaintext_to_encrypt) % 8
plaintext_to_encrypt += chr(padding) * padding

if "__main__" == __name__:

    """Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key"""
    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()

    encoder = DES.new(result[:8], DES.MODE_CBC, result[8:16])
    encrypted = encoder.encrypt(plaintext_to_encrypt)

    print encrypted.encode('base64')

This Python code outputs the following in Python 2.7:

Icy6sAP7adLgRoXNYe9N8A==

Thanks again to GregS for pointing me in the right direction!

Alexander.Iljushkin
  • 4,519
  • 7
  • 29
  • 46
Tebbe
  • 1,372
  • 9
  • 12
  • Actually just in case someone (like me) is wondering how was \xe0 calculated as the hex for -32, the way you do it is as follows: so you find the hex of 31, which is 0x1f and subtract it from 0xff. So 0xff - 0x1f = 0xe0. So that's how you derive the hexadecimal equivalents of negative integers. For an explanation of the same (why and how) Google for number systems and negative number representations in different number systems. – qre0ct Aug 26 '16 at 15:04
0

I found one from here

import base64
import hashlib
import re
import os
from Crypto.Cipher import DES
def get_derived_key(password, salt, count):
    key = password + salt
    for i in range(count):
        m = hashlib.md5(key)
        key = m.digest()
    return (key[:8], key[8:])
def decrypt(msg, password):
    msg_bytes = base64.b64decode(msg)
    salt = '\xA9\x9B\xC8\x32\x56\x35\xE3\x03'
    enc_text = msg_bytes
    (dk, iv) = get_derived_key(password, salt, 2)
    crypter = DES.new(dk, DES.MODE_CBC, iv)
    text = crypter.decrypt(enc_text)
    return re.sub(r'[\x01-\x08]','',text)
def encrypt(msg, password):
    salt = '\xA9\x9B\xC8\x32\x56\x35\xE3\x03'
    pad_num = 8 - (len(msg) % 8)
    for i in range(pad_num):
        msg += chr(pad_num)
    (dk, iv) = get_derived_key(password, salt, 2)
    crypter = DES.new(dk, DES.MODE_CBC, iv)
    enc_text = crypter.encrypt(msg)
    return base64.b64encode(enc_text)
def main():
    msg = "hello"
    passwd = "xxxxxxxxxxxxxx"
    encrypted_msg = encrypt(msg, passwd)
    print encrypted_msg
    plain_msg = decrypt(encrypted_msg, passwd)
    print plain_msg
if __name__ == "__main__":
    main()
fehrlich
  • 2,497
  • 2
  • 26
  • 44
kai
  • 1,640
  • 18
  • 11
0

If you're using the newer Cryptodome library with Python 3, you'll need to also encode your plaintext_to_encrypt to 'latin-1', as is shown below.

from Cryptodome.Hash import MD5
from Cryptodome.Cipher import DES
import base64
import re

_password = b'q1w2e3r4t5y6'
_salt = b'\x80\x40\xe0\x10\xf8\x04\xfe\x01'

_iterations = 50

plaintext_to_encrypt = 'MyP455w0rd'

# Pad plaintext per RFC 2898 Section 6.1
padding = 8 - len(plaintext_to_encrypt) % 8
plaintext_to_encrypt += chr(padding) * padding

if "__main__" == __name__:

    """Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key"""
    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()

    encoder = DES.new(result[:8], DES.MODE_CBC, result[8:16])
    encrypted = encoder.encrypt(plaintext_to_encrypt.encode('latin-1'))  #encoded plaintext

    print (str(base64.b64encode(encrypted),'utf-8'))

    decoder = DES.new(result[:8], DES.MODE_CBC, result[8:])
    d = str(decoder.decrypt(encrypted),'utf-8')
    print (re.sub(r'[\x01-\x08]','',d))