我在解密使用 RSA 生成的 public 密钥 (.jks) 编码的 128 位 AES 密钥时收到 BadPaddingException

I am getting BadPaddingException while decrypting an 128 bit AES key which has been encoded by using RSA generated public key(.jks)

package demo123;

import java.io.File;
import java.io.FileInputStream;
import java.nio.file.Files;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

// Java 8 个 RSA-AES 示例 encryption/decryption.

public class AESwithRSA {

public static void main(String[] args) throws Exception {
    String plainText = "{\"scope\":\"payments\",\"x-mig-bank\": \"ICICI\",\"x-mig-channel\": \"RC\",\"tpp_redirect_uri\": \"www.tpp-app.com?query=123\",\"x-tpp-client-id\": \"Ck234567890112\",\"tpp-app-name\": \"amazon\",\"Consent Id\": \"d25a6f26-3ad5-4dd8-96fd-2582abfa3f58\",\"Type\": \"Domestic Payment\" }";

// 使用 RSA

生成 public 和私钥
    Key privateKey = getPrivate("KeyPair/privateKey.jks");
    System.out.println("Private key success");
    System.out.println("Private key :" + privateKey);
    Key publicKey = getPublic("KeyPair/publicKey.");
    System.out.println("Public key success");
    System.out.println("Public key :" + publicKey);

// 首先创建一个AES密钥

    String secretAESKeyString = getSecretAESKeyAsString();
    System.out.println("Secret Key "+secretAESKeyString);

// 使用 AES 密钥加密我们的数据

    String encryptedText = encryptTextUsingAES(plainText, secretAESKeyString);
    System.out.println("Encrypted text "+encryptedText);

// 使用 RSA 私钥加密 AES 密钥

    byte[] encryptedAESKeyString = encryptAESKey(secretAESKeyString, publicKey);
    System.out.println("Encrypted AES key with RSA "+encryptedAESKeyString);

// 先用RSA Public key

解密AES Key
    String decryptedAESKeyString = decryptAESKey(encryptedAESKeyString, privateKey);
    System.out.println("Decrypted AES key with RSA "+decryptedAESKeyString);

// 现在使用解密的 AES 密钥解密数据!

    String decryptedText = decryptTextUsingAES(encryptedText, decryptedAESKeyString);

//显示所有输出

    System.out.println("input: " + encryptedText);
    System.out.println("AES Key: " + secretAESKeyString);
    System.out.println("decrypted: " + decryptedText);
    System.out.println("Text New:" + textNew);
    System.out.println("Encrypted New:" + encryptedTextNew);
    //System.out.println("Decrypted New:" + decryptedTextNew);

}

// 创建一个新的 AES 密钥。使用 128 位(弱)

public static String getSecretAESKeyAsString() throws Exception {
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128); // The AES key size in number of bits
    SecretKey secKey = generator.generateKey();
    String encodedKey = Base64.getEncoder().encodeToString(secKey.getEncoded());
    return encodedKey;
}

// 使用 AES 密钥加密文本

public static String encryptTextUsingAES(String plainText, String aesKeyString) throws Exception {
    byte[] decodedKey = Base64.getDecoder().decode(aesKeyString);
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");

    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    aesCipher.init(Cipher.ENCRYPT_MODE, originalKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return Base64.getEncoder().encodeToString(byteCipherText);
}

// 使用 AES 密钥解密文本

public static String decryptTextUsingAES(String encryptedText, String aesKeyString) throws Exception {

    byte[] decodedKey = Base64.getDecoder().decode(aesKeyString);
    SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");

    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, originalKey);
    byte[] bytePlainText = aesCipher.doFinal(Base64.getDecoder().decode(encryptedText));
    return new String(bytePlainText);
}

// 使用 RSA 私钥加密 AES 密钥

private static byte[] encryptAESKey(String plainAESKey, Key publicKey ) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.getEncoder().encode(cipher.doFinal(plainAESKey.getBytes()));
}

// 使用 RSA public 密钥解密 AES 密钥

private static String decryptAESKey(byte[] encryptedAESKey, Key privateKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return new String(cipher.doFinal(Base64.getDecoder().decode(encryptedAESKey)));
}

//获取public和私有.jks格式密钥

public static Key getPrivate(String filename) throws Exception {
        String password = "123456";
        FileInputStream is = new FileInputStream(filename);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, password.toCharArray());
        String alias = "rib_pub_priv_ob";
        Key key = keystore.getKey(alias, password.toCharArray());        
        return key;
    }

    // https://docs.oracle.com/javase/8/docs/api/java/security/spec/X509EncodedKeySpec.html
    public static Key getPublic(String filename) throws Exception {
        String password = "123456";
        FileInputStream is = new FileInputStream(filename);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, password.toCharArray());
        String alias = "tmsx_pub_priv_ob";
        Key key = keystore.getKey(alias, password.toCharArray());        
        return key;
    }

}

//输出如下

Private key success
Private key :sun.security.rsa.RSAPrivateCrtKeyImpl@ffd2dcac
Public key success
Public key :sun.security.rsa.RSAPrivateCrtKeyImpl@fff19d78
Secret Key XsZue3ATt4OAQFP5C4sa8Q==
Encrypted text mjynBmIDhsj9L3jhFmzb4CFaJr+i5k2B1luuTdg0ls3NoAvI3wLfeU54Sxo7IDBrqH3i3F3RNM4DDPhWdbtEMNQ+27EcQOugidB2BcTFigzIImNohZOVjBi+qrPC7KWGLf9JWlJHUsoUz+oKiuAJGjitrrIMg/qQN7He87hH6hxfNZ7vceZV2N6HihYsQ4R1S6YFRUDVBwuG+IjvEyzihkw4mmlmjq4FIspXmaYuxYE/6urevUD/dY7HSLVrVRst83VRKnqDrzf32RolGsM12Ebyk0XJGGOYHV/OWfYExkaQdfUaEVMhU3h/tTmSoVJHEHTf1YdMxv5x/HZd2aXoYw==
Encrypted AES key with RSA [B@5f150435
Exception in thread "main" javax.crypto.BadPaddingException: Decryption error
    at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:380)
    at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:291)
    at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:363)
    at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:389)
    at javax.crypto.Cipher.doFinal(Cipher.java:2165)
    at demo123.AESwithRSA.decryptAESKey(AESwithRSA.java:135)
    at demo123.AESwithRSA.main(AESwithRSA.java:60)

错误是由于在 getPublic 中加载 private 密钥而不是 public 密钥引起的。这可以在输出中很容易地看出:对于两个键,都显示了 sun.security.rsa.RSAPrivateCrtKeyImpl 类型的对象,而 public 键实际上应该是 sun.security.rsa.RSAPublicKeyImpl 类型的对象。要在 getPublic 中加载 public 键,请替换行

Key key = keystore.getKey(alias, password.toCharArray());    

来自

Key key = keystore.getCertificate(alias).getPublicKey(); 

另见 [1][2]。通过此修复,代码可以在我的机器上运行。

更新: 在当前代码中,Base64 编码的 AES 密钥(来自 getSecretAESKey)使用 RSA 加密,然后再次对该密钥进行 Base64 编码(在 encryptAESKey)。这样的双重 Base64 编码实际上是不必要的,因为用 RSA 加密 raw AES 密钥就足够了,因为每个 Base64 编码都有 33% 的开销。