Java 相当于 Ruby AES CBC 解密

Java equivalent of Ruby AES CBC Decryption

下面的 ruby 代码有效

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 中使用相同的 key/iv/cipher 执行相同的操作,但它不会 return '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 是硬编码的

你是在告诉它加密,而不是解密。更正后的代码行是

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);