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

时间:2015-01-30 12:06:30

标签: java ruby ruby-on-rails-3 aes sha

我一直在尝试将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);

任何人都可以让我知道,如何在它中做到这一点。

  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

2 个答案:

答案 0 :(得分:1)

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

创建随机initialisationVector

iv = cipher.random_iv

运行加密

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

解密:

初始化密码以进行解密

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

加载密钥和initialisationVector

decipher.key = key
decipher.iv = iv

解密明文

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

是否匹配?

puts unencrypted == plain #=> true

有关更多信息,请查看类的Ruby文档 - OpenSSL::Cipher

答案 1 :(得分:0)

加密代码:

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是一个缺失的部分。所以在那之后,所有人都开始正常工作。

如果他们遇到这个问题,我希望能有所帮助。