本文介绍了为什么我不能让" OpenSSL的使用Ruby"和"命令行OpenSSL的"互操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在试图建立一个可互操作的加密系统,我光时认识的一个奇怪的局面:证明的概念。

While trying to setup an interoperable encryption system, I met a weird situation during a light "proof-of-concept".

我写了下面code在Ruby中:

I wrote the following code in Ruby to:


  • 我的文件系统上创建一个从虚拟文本文件的加密文件

  • 解密加密文件

  • 与原始文件进行比较,并检查它们是否相同

下面是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 #=> true

一切正常,这个脚本输出真

Everything works fine, this script outputs "true"

然后我试图使用OpenSSL命令行解密文件我用下面的命令:

Then I tried to use the openssl command-line to decrypt my file with the following command:

openssl aes-256-cbc -d -a -in encrypted.txt -k somethingreallyreallycomplicated

但我得到:坏的幻数

为什么?

推荐答案

您需要使用 -K (大写)和 -IV在命令行上选项来指定密钥和IV明确为十六进制数字的字符串。如果你使用 -k (小写),OpenSSL的派生将使用一个密钥导出函数的口令密钥和IV。当OpenSSL的派生一个键,它也将使用一个咸鱼密文格式,它是与你所期望的普通列块CBC是不相容的。

You need to use the -K (upper case) and -iv options on the command line to specify key and IV explicitly as a string of hex digits. If you use -k (lower case), OpenSSL will derive key and IV from the password using a key derivation function. When OpenSSL derives a key, it will also use a "salted" ciphertext format which is incompatible with the plain blockwise CBC you are expecting.

请注意,在你的Ruby code,您使用的是ASCII字符串的第一个256位(32字节)直接作为重点,这是几乎可以肯定不是你想要的一个现实世界的应用程序,其中安全性是一个问题。你应该用一个(随机生成)的二进制键,或从派生密码的密钥使用密钥导出函数,如 ,或 scrypt

Note that in your Ruby code, you are using the first 256 bits (32 bytes) of an ASCII string directly as a key, which is almost certainly not what you want for a real world application where security is an issue. You should use a (randomly generated) binary key, or derive a key from a password using a key derivation function such as PBKDF2, bcrypt or scrypt.

这篇关于为什么我不能让" OpenSSL的使用Ruby"和"命令行OpenSSL的"互操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!