【问题标题】:I am getting BadPaddingException while decrypting an 128 bit AES key which has been encoded by using RSA generated public key(.jks)我在解密使用 RSA 生成的公钥(.jks)编码的 128 位 AES 密钥时遇到 BadPaddingException
【发布时间】:2020-04-19 17:53:56
【问题描述】:
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;

// RSA-AES 加密/解密的 Java 8 示例。

公共类 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 生成公钥和私钥

    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 Key

    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公钥解密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 公钥解密 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)));
}

//获取公私.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)

【问题讨论】:

  • 我的回答错了,所以删除了。无论如何我必须添加一些注释以避免一些弱点:不要使用ECB模式,任何其他都可以,使用显式算法声明,如AES/CBC/PKCS7Padding,使用某种完整性检查,如HMAC或GCM模式,不需要始终使用 base64 编码

标签: java encryption aes rsa badpaddingexception


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 2014-06-15
    相关资源
    最近更新 更多