将java中的加密代码转换为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
或者创建一个随机的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 Docs – 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
是一个缺少的部分。 所以在那之后,所有人都开始正常工作。
如果他们遇到这个问题,我希望能有所帮助。
- 使用IGE解密Java AES-256
- 是什么导致错误“java.security.InvalidKeyException:参数缺失”?
- 如何使用java解码用openssl aes-128-cbc编码的字符串?
- ruby-aes默认使用填充吗?
- 用于加密/解密的Java SimpleCrypto类在Coldfusion 9和Java(Android)中产生不同的结果
- 如何处理AES CTR的IV / Nonce / Counter?
- 使用C#进行AES加密和使用Java进行解密
- 使用密码短语的CBC的Java AES
- 想要使用带有32字节的AES 256 CBC,但它显示了java.security.InvalidAlgorithmParameterException