【问题标题】:Ruby OpenSSL encrypt with hex key returns empty string使用十六进制密钥加密的 Ruby OpenSSL 返回空字符串
【发布时间】:2015-11-29 16:21:47
【问题描述】:

大家好,这是我在这里的第一个问题。我会直奔主题。提前感谢您的帮助。

我正在尝试使用从 32 字节十六进制字符串创建的 base64 密钥和从 16 字节十六进制字符串和 AES-128-CBC 算法创建的 base64 盐来加密字符串。

这是代码(红宝石):

base64_key = 'NTQ2ODY5NzMyMDY5NzMyMDYxNmUyMDY1Nzg2MTZkNzA='
base64_iv  = 'NTQ2ODY5NzMyMDY5NzMyMA=='

# create an OpenSSL Cipher to encrypt the user name
encrypter = OpenSSL::Cipher.new('AES-128-CBC')
encrypter.encrypt

# the key and iv must be a byte array
encrypter.key = Base64.decode64(base64_key)
encrypter.iv  = Base64.decode64(base64_iv)

# add the username to encrypt
enc_string = encrypter.update 'somestring'
# push the rest of the string encrypted
enc_string << encrypter.final

# the enc_string value must be sent encoded as base64
enc_string = Base64.encode64(enc_string)

问题是 enc_string 最终为空。

我使用从类似短语生成的 base64 密钥尝试了这段代码

key = Base64.encode64('This_is_test')
encrypter.key = Base64.decode64(key)

这行得通。

有什么见解吗?任何帮助将不胜感激。

【问题讨论】:

  • 如果您想使用 AES-256(从 256 位密钥中可以看出),为什么要请求 AES-128-CBC 密码而不是 AES-256-CBC?
  • 尝试使用 AES-256-CBC,现在有时我得到一些东西,有时是空字符串。而且它应该总是相同的字符串,不是吗?
  • 每次运行它都对我很好
  • 它可以工作 (ideone.com/L8OynE),所以可能你的环境坏了。
  • 我发现对于coldfusion,您需要一些额外的Java 策略文件才能完成这项工作。我需要额外的 ruby​​ 库来使用这种加密吗?默认情况下未安装的额外库?

标签: ruby encryption openssl base64 aes


【解决方案1】:

经过一番反复,我想出了如何让它发挥作用。

我必须在实例化 Cipher 后添加 encrypter.padding = 1

这就是代码现在的样子:

require 'openssl'
require 'base64'

base64_key = 'NTQ2ODY5NzMyMDY5NzMyMDYxNmUyMDY1Nzg2MTZkNzA='
base64_iv  = 'NTQ2ODY5NzMyMDY5NzMyMA=='

# create an OpenSSL Cipher to encrypt the user name
encrypter = OpenSSL::Cipher.new('AES-256-CBC')
encrypter.padding = 1
encrypter.encrypt

# the key and iv must be a byte array
encrypter.key = Base64.decode64(base64_key)
encrypter.iv  = Base64.decode64(base64_iv)

# add the username to encrypt
enc_string = encrypter.update 'somestring'
# push the rest of the string encrypted
enc_string << encrypter.final

# the enc_string value must be sent encoded as base64
enc_string = Base64.encode64(enc_string)

【讨论】:

    猜你喜欢
    • 2011-11-13
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-10
    • 1970-01-01
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多