下面的红宝石代码可以使用
require 'openssl'
require "base64"
cipher = OpenSSL::Cipher::AES256.new(:CBC)
cipher.decrypt
cipher.key = Base64.strict_decode64("LLkRRMSAlD16lrfbRLdIELdj0U1+Uiap0ihQrRz7HSQ=")
cipher.iv = Base64.strict_decode64("A23OFOSvsC4UyejA227d8g==")
crypt = cipher.update(Base64.strict_decode64("D/e0UjAwBF+d8aVqZ0FpXA=="))
crypt << cipher.final
puts crypt # prints Test123
但尝试在java中使用相同的密钥/ iv / cipher执行相同的操作,但它不会返回'Test123'
Security.addProvider(new BouncyCastleProvider());
byte[] key = Base64.getDecoder().decode("LLkRRMSAlD16lrfbRLdIELdj0U1+Uiap0ihQrRz7HSQ=");
byte[] iv = Base64.getDecoder().decode("A23OFOSvsC4UyejA227d8g==");
byte[] input = Base64.getDecoder().decode("D/e0UjAwBF+d8aVqZ0FpXA==");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
byte[] output = cipher.doFinal(input);
System.out.println("[" + new String(output) + "] - "+output.length);
为简单起见,key和iv是硬编码的
答案 0 :(得分:1)
你告诉它加密,而不是解密。更正的代码行是
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
此外,如果您想使用BouncyCastle,请使用
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", BouncyCastleProvider.PROVIDER_NAME);
或将BouncyCastle设为默认值:
Security.insertProviderAt(new BouncyCastleProvider(), 1);