venturemoo venturemoo - 3 years ago 384
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( 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 ='AES-128-CBC')
    aes.iv = iv
    aes.key = ciphering_key
    aes.update(data) +

  def decrypt(iv, encrypted_data)
    aes ='AES-128-CBC')
    aes.iv = iv
    aes.key = ciphering_key
    aes.update(encrypted_data) +


  def ciphering_key
    # get from config or storage, etc

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 =
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download