Getting error like in `final': bad decrypt (OpenSSL::Cipher::CipherError) while decrypting array of objects

#1

require ‘openssl’
require ‘base64’
require ‘hex_string’
require ‘pry’
$data = [“suni”,“1”,“nagoore”,"@gmail.com"]
$enc = []

cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
key = cipher.random_key
iv = cipher.random_iv
#start the encryption process
$data.each do |k|
encrypted = cipher.update(k) + cipher.final
$enc << encrypted
end
puts $enc

#start the decryptuion process
$enc.each do |j|
decipher = OpenSSL::Cipher::AES.new(128, :CBC)
decipher.decrypt
decipher.padding = 0
decipher.key = key
decipher.iv = iv
plain = decipher.update(j) + decipher.final
puts plain
end

#2

So I think the key should be in the each loop.

Here’s the Code :lollipop:

#!/usr/bin/ruby -w
require 'openssl'

$data, $enc = ['suni', '1', 'nagoore', '@gmail.com'], []

cipher = OpenSSL::Cipher.new('AES-128-CBC').encrypt
key = cipher.random_key

# start the encryption process
$data.each do |k|
	cipher.key = key
	$enc << cipher.update(k) + cipher.final
end

decipher = OpenSSL::Cipher::AES.new(128, :CBC).decrypt

# start the decryption process
$enc.each do |j|
	decipher.key = key
	p decipher.update(j) << decipher.final
end

It works for me (on my machine) :joy::stuck_out_tongue_closed_eyes:

In `final': wrong final block length (OpenSSL::Cipher::CipherError)
#3

Thank you. your solution is working