title: Why can't I make "OpenSSL with Ruby" and "Command line OpenSSL" interoperable?
body: <p>While trying to setup an interoperable encryption system, I met a weird situation during a light "proof-of-concept".</p>
  
  <p>I wrote the following code in Ruby to:</p>
  
  <ul>
  <li>create an encrypted file from a dummy text file on my file system</li>
  <li>decrypt the encrypted file</li>
  <li>compare with the original file and check if they are the same</li>
  </ul>
  
  <p>Here is the code:</p>
  
  <pre><code>require 'openssl'
  require 'base64'
  
  # Read the dummy file
  data = File.read("test.txt")
  
  # Create an encrypter
  cipher = OpenSSL::Cipher::AES.new(256, :CBC)
  cipher.encrypt
  key = "somethingreallyreallycomplicated"
  cipher.key = key
  
  # Encrypt and save to a file
  encrypted = cipher.update(data) + cipher.final
  open "encrypted.txt", "w" do |io| io.write Base64.encode64(encrypted) end
  
  # Create a decrypter
  decipher = OpenSSL::Cipher::AES.new(256, :CBC)
  decipher.decrypt
  decipher.key = key
  
  # Decrypt and save to a file
  encrypted_data = Base64.decode64(File.read("encrypted.txt"))
  plain = decipher.update(encrypted_data) + decipher.final
  open "decrypted.txt", "w" do |io| io.write plain end
  
  # Compare original message and decrypted message
  puts data == plain #=&gt; true
  </code></pre>
  
  <p>Everything works fine, this script outputs "true"</p>
  
  <p>Then I tried to use the openssl command-line to decrypt my file with the following command:</p>
  
  <pre><code>openssl aes-256-cbc -d -a -in encrypted.txt -k somethingreallyreallycomplicated
  </code></pre>
  
  <p>But I got: <code>bad magic number</code></p>
  
  <p>How come?</p>