【发布时间】:2021-03-16 17:46:25
【问题描述】:
我在 Rails 中有一个应用程序,它具有以下方法来加密和解密文本并与 java 客户端通信。
def encrypt(string, key)
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
cipher.padding = 1
cipher.key = hex_to_bin(Digest::SHA1.hexdigest(key)[0..32])
cipher_text = cipher.update(string)
cipher_text << cipher.final
return bin_to_hex(cipher_text).upcase
end
def decrypt(encrypted, key)
encrypted = hex_to_bin(encrypted.downcase)
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.decrypt
cipher.padding = 1
cipher.key = hex_to_bin(Digest::SHA1.hexdigest(key)[0..32])
d = cipher.update(encrypted)
d << cipher.final
rescue Exception => exc
end
def hex_to_bin(str)
[str].pack "H*"
end
def bin_to_hex(str)
str.unpack('C*').map{ |b| "%02X" % b }.join('')
end
我需要在 Elixir 中为 phoenix 框架做同样的事情。由于我是 Elixir 的新手,所以我找不到解决方法。
我发现 Elixir 为此使用了 Erlang 的 :crypto 模块。在文档中没有AES CBC 加密的方法。
【问题讨论】:
-
:crypto.block_encrypt/4with first argument =:aes_cbc128可能是你想要的,但我找不到在:crypto中设置padding = 1的等价物。见erlang.org/doc/man/crypto.html#block_encrypt-4。 -
@Dogbert 它看起来像 Erlang 的加密库 explicitly disables padding,这似乎有点奇怪,因为这是 OpenSSL“免费”做的事情,现在用户必须自己做填充。 (它也有自己的check for the data being a multiple of 16 bytes)。
-
@matt,所以这意味着我应该更改我的android客户端中的加密方法,对吧?因为我在 java 中的数据不是 16 字节的倍数。
标签: ruby erlang elixir phoenix-framework