venturemoo venturemoo - 1 month ago 48
Ruby Question

Encrypt byte data with Ruby

I am working on a project about AES encryption with Ruby . The encryption libraries for Ruby get the data as string and start to encrypt it, e.g(http://ruby-doc.org/stdlib-2.0.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html). However I have a byte array data like;

seed_V = [0x08,0x06,0x02,0x01,0x03,0x07,0x01]


I want to provide the data in bytes and encrypt like the way of Java or C# do ( Using AES encryption in C#)
How can I do the same type of encryption in Ruby?

Answer Source

Consider we are using AES-CBC:

require 'openssl'

class AesCrypto     
  def encrypt(iv, data)
    aes = ::OpenSSL::Cipher.new('AES-128-CBC')
    aes.encrypt
    aes.iv = iv
    aes.key = ciphering_key
    aes.update(data) + aes.final
  end

  def decrypt(iv, encrypted_data)
    aes = ::OpenSSL::Cipher.new('AES-128-CBC')
    aes.decrypt
    aes.iv = iv
    aes.key = ciphering_key
    aes.update(encrypted_data) + aes.final
  end

  private

  def ciphering_key
    # get from config or storage, etc
    'test_key_test_key'
  end
end

Please note the iv length should be equal to the block size for that CBC.

seed_v = [0x08,0x06,0x02,0x01,0x03,0x07,0x01,0x08,0x06,0x02,0x01,0x03,0x07,0x01,0x08,0x01]
iv = seed_v.pack('C*')
data = "hello!"

crypto = AesCrypto.new
ciphertext = crypto.encrypt(iv, data)
puts ciphertext
data = crypto.decrypt(iv, ciphertext)
puts data

This is an useful answer if you unsure how to choose the iv:

CBC with a fixed or random IV