Search code examples
python-3.xcryptojs

Equivalent Python3 code to JS DES encryption with CryptoJS


I have a js DES encryption code uses CryptoJS as below:

const CryptoJS = require('crypto-js');

function encryptByDES(message, key) {
        var keyHex = CryptoJS.enc.Utf8.parse(key);
        var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
      }

and if input message="123456789", key="123456abcdefghijklmnopqrstuvwxyz", the output is J6cwLeYoidP5U1V6MT67Ig==.

I want to know the Python3 version of the code. I trid PyCrytodome with no luck ( I'm not much understand this package), recent code is as below:

from Crypto.Util.Padding import pad, unpad
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
import binascii

data = b'123456789'
key = b'123456abcdefghijklmnopqrstuvwxyz'
iv = get_random_bytes(16)
# below line triggers error
cipher1 = DES.new(key, DES.MODE_CFB, iv)
ct = cipher1.encrypt(pad(data, 16))
print(binascii.b2a_base64(ct))

the error is

ValueError: Incorrect DES key length (32 bytes)

please help me out.


Solution

  • Based on Topaco's suggestion, finally it's working, the code is as below:

    data = b'123456789'
    # the next cdefghijklmnopqrstuvwxyz is no needed
    key = b'123456ab'
    cipher = DES.new(key, DES.MODE_ECB)
    ct = cipher.encrypt(pad(data, 8))
    print(binascii.b2a_base64(ct))
    

    FYI.