0

I am encrypting a file with AES-256-CBC with the help of OpenSSL:

# Encrypt a file with openSSL
require 'openssl'

class Encryptor

  def initialize
    @src_file = 'test.txt'
    @dst_file = 'test.enc'
    @key = "1234567890ABCDEF1234567890ABCDEF"
    @iv  = "1234567890ABCDEF"
    @algorithm = 'AES-256-CBC'
  end

  #
  def encrypt
    cipher = OpenSSL::Cipher.new(@algorithm)
    cipher.encrypt
    cipher.key = @key
    cipher.iv = @iv
    buffer = ""
    File.open(@dst_file,'wb') do |outf|
      File.open(@src_file, 'rb') do |inf|
        while inf.read(4096, buffer)
          outf << cipher.update(buffer)
        end
        outf << cipher.final
      end
    end
  rescue Exception => e
    "#{e}"
  end

end

enc = Encryptor.new
enc.encrypt

and then I am trying to decrypt it by using terminal:

openssl enc -aes-256-cbc -d -in test.enc -K "1234567890ABCDEF1234567890ABCDEF" -iv "1234567890ABCDEF" -out test_dec.txt

What I get is an error:

bad decrypt
29152:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL098-64/src/crypto/evp/evp_enc.c:330:

mostly known as "bad_decrypt".

I've tried with & without an iv, changing -k to -K, using -a, decrypt with base64 first among other things and of course nothing worked. Any ideas how to fix this ?

ftshtw
  • 629
  • 1
  • 5
  • 19
  • I don't know if this is related to your actual problem but `puts iv` throws undefined, use `puts @iv`. – Halil Özgür Oct 11 '16 at 18:03
  • Encrypts (and decrypts) successfully on my Mac. AFAIK Apple has an older version of OpenSSL. My Ruby is 2.3.1, built by ruby-build through rbenv. I might have done something like pointing ruby-build to my Homebrew built OpenSSL rather than the OS one when I first installed rbenv but I can't recall for sure. This is similar to how some gems with native extensions like EventMachine require a bundler config pointing to a more recent OpenSSL. – Halil Özgür Oct 11 '16 at 18:10
  • This question is not duplicate. I found the problem which was related to the hex equivalent of the key. The terminal command requires -K . – ftshtw Oct 12 '16 at 09:24

0 Answers0