在尝试设置可互操作的加密系统时,我在轻松的“概念验证”中遇到了一种奇怪的情况。
我在Ruby中编写了以下代码:
以下是代码:
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 #=> true
一切正常,此脚本输出“true”
然后我尝试使用openssl命令行使用以下命令解密我的文件:
openssl aes-256-cbc -d -a -in encrypted.txt -k somethingreallyreallycomplicated
但我得到了:bad magic number
怎么回事?