当前位置: 首页 > 知识库问答 >
问题:

我在解密128位AES密钥时获得BadPaddingException,该密钥是通过使用RSA生成的公钥(.jks)进行编码的

方英耀
2023-03-14
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;
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\" }";
    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);
    String secretAESKeyString = getSecretAESKeyAsString();
    System.out.println("Secret Key "+secretAESKeyString);
    String encryptedText = encryptTextUsingAES(plainText, secretAESKeyString);
    System.out.println("Encrypted text "+encryptedText);
    byte[] encryptedAESKeyString = encryptAESKey(secretAESKeyString, publicKey);
    System.out.println("Encrypted AES key with RSA "+encryptedAESKeyString);
    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;
}
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);
}
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);
}
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()));
}
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 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)

共有1个答案

方高丽
2023-03-14

该错误是由于在getpublic中加载私钥而不是公钥造成的。在输出中可以很容易地看到这一点:对于这两个密钥,都显示了Sun.Security.rsa.rsaprivateCrtKeyImpl类型的对象,而公钥实际上应该是Sun.Security.rsa.rsapublicKeyImpl类型。若要加载getpublic中的公钥,请替换行

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

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

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

 类似资料:
  • 问题内容: 我正在编写一个用于传输文件的小型应用程序,或多或少地将其作为一种学习更多编程加密基础的方法。这个想法是生成一个RSA密钥对,交换公共密钥,并发送AES iv和密钥以进一步解密。我想用接收者的RSA公钥加密AES密钥,如下所示: 然后,我将密钥值写给接收器,并按如下方式解密: 在控制台的另一端,我将其作为输出: 此外,如果我创建一个大小为16的字节数组,并将cipher.doFinal(

  • 尝试将数据解密为用AES-128加密的字节数组,使用字符串密钥"keykeykeykey1" 代码: 给我BadPaddingExc0019。我错过了什么?

  • 这是我的密码 抱歉,如果我的代码一团糟。

  • 但这总是给我以下的例外- 我的键盘生成逻辑- 我的加密逻辑- Base64 Util方法-

  • 今天,我写了一些代码,用AES加密字符串,用RSA加密密钥。当我试图解密所有内容时,Java给了我一个BadPaddingException。这是我的代码: 测验爪哇: 钥匙匠。爪哇: 加密机。爪哇: 解密程序。爪哇:

  • 我想使用带有RSA算法的OpenSSL使用私钥加密文件: 现在,如果我执行解密操作: 此操作需要私钥 我知道我应该使用公钥进行加密,如果我使用私钥,我会得到一个签名。 然而,我想这样做是为了学习。