gpt4 book ai didi

java - 我在解密使用 RSA 生成的公钥 (.jks) 编码的 128 位 AES key 时遇到 BadPaddingException

转载 作者:行者123 更新时间:2023-11-30 01:42:19 25 4
gpt4 key购买 nike

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 示例。

公共(public)类 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 key 加密我们的数据

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

//使用 RSA 私钥加密 AES key

    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 key 解密数据!

    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 key 。使用 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 key 加密文本

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 key 解密文本

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 Key

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 key

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

//获取公有和私有(private).jks格式 key

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 中加载私钥而不是公钥而导致的。这可以在输出中轻松看出:对于两个 key ,都会显示 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 key (来自 getSecretAESKey)使用 RSA 加密,然后该 key 再次进行 Base64 编码(在 加密AESKey)。这种双重 Base64 编码实际上是不必要的,因为用 RSA 加密原始 AES key 就足够了,因为每个 Base64 编码都有 33% 的开销。

关于java - 我在解密使用 RSA 生成的公钥 (.jks) 编码的 128 位 AES key 时遇到 BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59540084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com