I have been trying to convert a code for encrypt in java to ruby, but I am not able to do it completely. I getting different values.
passphrase = passphra
require 'openssl'
unencrypted = "I am a secret!"
initialize the Cipher for encrypt
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
create the key using SHA1
key = Digest::SHA1.hexdigest('secret_key')[0...32]
cipher.key = key
create the initialisationVector with an input
iv = Digest::SHA1.hexdigest('secret_iv')[0...32]
cipher.iv = iv
or create a random initialisationVector
iv = cipher.random_iv
run the encryption
encrypted = cipher.update(unencrypted) + cipher.final
initialize the Cipher for decrypt
decipher = OpenSSL::Cipher::AES.new(128, :CBC)
decipher.decrypt
load the key and initialisationVector
decipher.key = key
decipher.iv = iv
decrypt the plaintext
plain = decipher.update(encrypted) + decipher.final
puts unencrypted == plain #=> true
For more information look at the Ruby Docs for the Class - OpenSSL::Cipher
Encrypt Code:
def aes(key,string)
cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
cipher.encrypt
cipher.padding = 1
cipher.key = hex_to_bin(Digest::SHA1.hexdigest('secret_key')[0..32])
cipher_text = cipher.update(string)
cipher_text << cipher.final
return bin_to_hex(cipher_text).upcase
end
Decrypt Code:
def aes_decrypt(key, encrypted)
encrypted = hex_to_bin(encrypted.downcase)
cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
cipher.decrypt
cipher.padding = 1
cipher.key = hex_to_bin(Digest::SHA1.hexdigest('secret_key')[0..32])
d = cipher.update(encrypted)
d << cipher.final
end
hex_to_bin and bin_to_hex
def hex_to_bin(str)
[str].pack "H*"
end
def bin_to_hex(s)
s.unpack('C*').map{ |b| "%02X" % b }.join('')
end
In My case, The java code was using default initialization vector, So I did not set any iv, Also, there was hex_to_bin
was a missing piece there. So after that, all started working properly.
I hope it helps someone if they come across this issue.