将 java 中的加密代码转换为 Ruby

Convert Encrypt code in java to Ruby

我一直在尝试将 java 中的加密代码转换为 ruby,但我无法完全做到。我得到不同的值。

   passphrase = passphrase + STATIC_KEY;
   byte[] key = passphrase.getBytes("UTF-8");

   MessageDigest sha = MessageDigest.getInstance("SHA-1");
   key = sha.digest(key);
   key = Arrays.copyOf(key, 16);
   SecretKey secretKey = new SecretKeySpec(key, "AES");

   Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
   IvParameterSpec initialisationVector = new IvParameterSpec(
           new byte[16]);
   cipher.init(Cipher.ENCRYPT_MODE, secretKey, initialisationVector);

   byte[] encryptedData = cipher.doFinal(plainText.getBytes("UTF-8"));

   return SimpleCrypto.toHex(encryptedData);

任何人都可以让我知道如何在其中完成此操作ruby。

  unencrypted = "passphrase"
  c = OpenSSL::Cipher.new("aes-128-cbc")
  c.encrypt
  c.key = Digest::SHA1.hexdigest('secret_key')[0...32]
  e = c.update(unencrypted)
  e << c.final
  return e
require 'openssl'

加密:

unencrypted = "I am a secret!"

为加密初始化密码

cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt

使用 SHA1 创建密钥

key = Digest::SHA1.hexdigest('secret_key')[0...32]
cipher.key = key

使用输入创建 initialisationVector

iv = Digest::SHA1.hexdigest('secret_iv')[0...32]
cipher.iv = iv

创建一个随机初始化向量

iv = cipher.random_iv

运行加密

encrypted = cipher.update(unencrypted) + cipher.final

解密:

为解密初始化密码

decipher = OpenSSL::Cipher::AES.new(128, :CBC)
decipher.decrypt

加载密钥和初始化向量

decipher.key = key
decipher.iv = iv

解密明文

plain = decipher.update(encrypted) + decipher.final

匹配吗?

puts unencrypted == plain #=> true

有关详细信息,请查看 Ruby 文档 Class - OpenSSL::Cipher

加密代码:

def aes(key,string)
  cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
  cipher.encrypt
  cipher.padding = 1
  cipher.key = hex_to_bin(Digest::SHA1.hexdigest('secret_key')[0..32])
  cipher_text = cipher.update(string)
  cipher_text << cipher.final
  return bin_to_hex(cipher_text).upcase
end

解密代码:

def aes_decrypt(key, encrypted)
  encrypted = hex_to_bin(encrypted.downcase)
  cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
  cipher.decrypt
  cipher.padding = 1
  cipher.key = hex_to_bin(Digest::SHA1.hexdigest('secret_key')[0..32])
  d = cipher.update(encrypted)
  d << cipher.final
end

hex_to_bin 和 bin_to_hex

def hex_to_bin(str)
  [str].pack "H*"
end

def bin_to_hex(s)
  s.unpack('C*').map{ |b| "%02X" % b }.join('')
end

在我的例子中,java 代码使用默认的初始化向量,所以我没有设置任何 iv,另外,hex_to_bin 是一个缺失的部分。所以在那之后,一切都开始正常工作了。

希望对遇到此问题的人有所帮助。