Search code examples
rubyecb

How to port DES ECB encryption from Python to Ruby


I am trying to rewrite an encryption function from python to ruby, but not getting the same result. I know des ecb is insecure and not recommended, but is needed for the purpose of this porting from python and ruby.

Using pyDes in python, I have the following:

import pyDes
salt = 'HeresATwentyFourDigtSalt'
data = 'thing to encrypt'
cipher = pyDes.triple_des(salt, pyDes.ECB, pad=None, padmode=pyDes.PAD_PKCS5)
encrypted = cipher.encrypt(data)
base64.b64encode(encrypted)
'b4SlfbPj6BzFJ2djzu/DTbtmeZ6erKP8'

Now I want to get to the same cipher text with ruby:

require "base64"
require "openssl"
salt = 'HeresATwentyFourDigtSalt'
data = 'thing to encrypt'
cipher = OpenSSL::Cipher::Cipher.new('DES-ECB')
cipher.encrypt
cipher.padding=0
cipher.key = salt
encrypted = cipher.update(data)
encrypted_final = encrypted + cipher.final
Base64.encode64(encrypted_final)
"pfHDx7yTWZ4vh8+AqiklPrNb+VHhcCyA\n"

Solution

  • After spending a bit of time trying some variations while I was posting the question, I figured out the solution. Posting here for reference if it helps anyone - the cipher should have been DES-EDE3 and padding set to 1, with a newline trim.

    require "base64"
    require "openssl"
    salt = 'HeresATwentyFourDigtSalt'
    data = 'thing to encrypt'
    cipher = OpenSSL::Cipher::Cipher.new('DES-EDE3')
    cipher.encrypt
    cipher.padding=0
    cipher.key = salt
    encrypted = cipher.update(data)
    encrypted_final = encrypted + cipher.final
    Base64.encode64(encrypted_final).gsub(/\n/, "")
    'b4SlfbPj6BzFJ2djzu/DTbtmeZ6erKP8'