将java中的加密代码转换为Ruby [英] Convert Encrypt code in java to Ruby
本文介绍了将java中的加密代码转换为Ruby的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试将java中的加密代码转换为ruby,但我无法完全完成。我得到了不同的价值。
I have been trying to convert a code for encrypt in java to ruby, but I am not able to do it completely. I getting different values.
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。
Can anyone let me know, how this can be done in it 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
推荐答案
加密代码:
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
hex_to_bin and 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
是一个缺失的部分。所以在那之后,所有人都开始正常工作。
In My case, The java code was using default initialization vector, So I did not set any iv, Also, there was hex_to_bin
was a missing piece there. So after that, all started working properly.
我希望如果他们遇到这个问题会帮助别人。
I hope it helps someone if they come across this issue.
这篇关于将java中的加密代码转换为Ruby的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文