0

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?

2 Answers2

0

You can pack your byte array into a string:

seed_V = [0x08,0x06,0x02,0x01,0x03,0x07,0x01]
=> [8, 6, 2, 1, 3, 7, 1]

seed_V.pack('C*')
=> "\b\x06\x02\x01\x03\a\x01"

seed_V.pack('C*').unpack('C*')
=> [8, 6, 2, 1, 3, 7, 1]

http://www.rubydoc.info/stdlib/core/Array%3Apack

Derek Wright
  • 1,452
  • 9
  • 11
0

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

eugene-nikolaev
  • 1,290
  • 1
  • 13
  • 21