[Answered ]-Encrypt String In Ruby and Decrypt in Python

2👍

After feedback by ArtjomB I looked deeper into the proposed library. It is nothing but a thin wrapper around ruby openssl. So you can write a ruby version of your AESCipher on your own.
It took some fiddling and research to find the right way:

require 'base64'
require 'securerandom'
require 'openssl'

class AESCipher
  attr_reader :key

  def initialize(key)
    @key = key
  end

  def encrypt(raw)
    iv = SecureRandom.random_bytes(16)
    cipher = build_encription_cipher(iv)
    encrypted = cipher.update(raw) + cipher.final
    Base64.encode64(iv + encrypted)
  end

  def decrypt(data)
    data = Base64.decode64(data)
    iv, raw = data[0..15], data[16..-1]
    cipher = build_decrypt_cipher(iv)
    cipher.update(raw) + cipher.final
  end

  private

  def build_encription_cipher(iv)
    OpenSSL::Cipher::AES.new(128, :CBC).tap do |cipher|
      cipher.encrypt
      cipher.key = key
      cipher.iv = iv
      cipher.padding = 0
    end
  end

  def build_decrypt_cipher(iv)
    OpenSSL::Cipher::AES.new(128, :CBC).tap do |cipher|
      cipher.decrypt
      cipher.key = key
      cipher.iv = iv
      cipher.padding = 0
    end
  end
end

In my testcases the ruby version decrypted strings encrypted by python and vice versa.

(i did one modification to your python code: remove the call to pad as I don’t know HOW it pads. And just used strings that are length multiple of 16).

The answer by colinm in AES Python encryption and Ruby encryption – different behaviour? was very useful.

👤Pascal

Leave a comment