gpt4 book ai didi

java - 从文件中解密字符串时,RSA 中的解密会抛出 BadPaddingException

转载 作者:行者123 更新时间:2023-11-30 04:08:55 25 4
gpt4 key购买 nike

我使用这个程序输出加密的字符串,并将该字符串复制并粘贴到我读取并尝试解密的文件中。如果我尝试解密程序中生成的字符串,该程序工作正常。仅当我将加密字符串复制到文件然后尝试解密它时才会失败。这是我得到的错误 -

Nov 21, 2013 11:40:01 AM rsademo.RSADemo main
SEVERE: null
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(RSAPadding.java:325)
at sun.security.rsa.RSAPadding.unpad(RSAPadding.java:272)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:356)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
at rsademo.RSAUtil.decrypt(RSAUtil.java:112)
at rsademo.RSADemo.main(RSADemo.java:65)

这是我使用的代码 -

package rsademo;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
*
* @author Test01
*/
public class RSADemo {

/**
* @param args the command line arguments
*/
public static void main(String[] args) throws InvalidKeySpecException {
RSAUtil util = new RSAUtil();
String path = "c:";
try {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair generatedKeyPair = keyGen.genKeyPair();
util.dumpKeyPair(generatedKeyPair);
//util.SaveKeyPair(path, generatedKeyPair);

KeyPair loadedKeyPair = util.LoadKeyPair(path, "RSA");
System.out.println("Loaded Key Pair");
util.dumpKeyPair(loadedKeyPair);

PublicKey pub=generatedKeyPair.getPublic();
PrivateKey priv=generatedKeyPair.getPrivate();
byte[] data="in153".getBytes();
System.out.println("Original: "+new String(data));
byte[] encrypted=util.encrypt(data, pub);

FileReader fr=new FileReader("D:\\Pankaj\\beta\\signageplus.conf");
BufferedReader br=new BufferedReader(fr);
String s;
String[] splits=null;
while((s=br.readLine())!=null){
if(s.startsWith("PASS")){
splits=s.split(";");
encrypted=splits[1].getBytes();
break;
}
}
br.close();
System.out.println("Encrypted: "+new String(encrypted));
byte[] decrypted=util.decrypt(encrypted);
System.out.println("Decrypted: "+new String(decrypted));
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(RSADemo.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(RSADemo.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchPaddingException ex) {
Logger.getLogger(RSADemo.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeyException ex) {
Logger.getLogger(RSADemo.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(RSADemo.class.getName()).log(Level.SEVERE, null, ex);
} catch (BadPaddingException ex) {
Logger.getLogger(RSADemo.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

util类如下-

package rsademo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

/**
*
* @author Test01
*/
public class RSAUtil {

public void dumpKeyPair(KeyPair keyPair) {
PublicKey pub = keyPair.getPublic();
System.out.println("Public Key: " + getHexString(pub.getEncoded()));

PrivateKey priv = keyPair.getPrivate();
System.out.println("Private Key: " + getHexString(priv.getEncoded()));
}

public String getHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}

public void SaveKeyPair(String path, KeyPair keyPair) throws IOException {
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publicKey.getEncoded());
FileOutputStream fos = new FileOutputStream(path + "/public.key");
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();

// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
privateKey.getEncoded());
fos = new FileOutputStream(path + "/private.key");
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}

public KeyPair LoadKeyPair(String path, String algorithm)
throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
// Read Public Key.
File filePublicKey = new File(path + "/public.key");
FileInputStream fis = new FileInputStream(path + "/public.key");
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();

// Read Private Key.
File filePrivateKey = new File(path + "/private.key");
fis = new FileInputStream(path + "/private.key");
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();

// Generate KeyPair.
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

return new KeyPair(publicKey, privateKey);
}

public byte[] encrypt(byte[] data, PublicKey key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] cipherData = cipher.doFinal(data);
return cipherData;

}

public byte[] decrypt(byte[] data) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, InvalidKeySpecException, InvalidKeyException {
Cipher cipher = Cipher.getInstance("RSA");
KeyPair pair=LoadKeyPair("c:", "RSA");
PrivateKey key=pair.getPrivate();
cipher.init(Cipher.DECRYPT_MODE, key);

byte[] cipherData = cipher.doFinal(data);
return cipherData;
}
}

感谢任何帮助。提前致谢。

最佳答案

您的加密数据是一个包含二进制数据(而不是文本)的byte[],但您使用它来构造一个String,它期望字节代表某种编码方案中的有效 Unicode 文本 — 可能是 UTF-8 或 UTF-16,具体取决于您使用的操作系统。由于加密的数据可能包含无效的 UTF-8/UTF-16 字节序列,因此 String 构造函数将忽略无效字节或用占位符字符替换它们,从而有效地损坏数据。

如果您想以可以安全显示和复制/粘贴为文本的形式显示加密数据,您应该将 byte[] 转换为十六进制字符串(就像您所做的那样)键),或使用 Base64 对其进行编码,而不是将其直接传递给 String 构造函数。

关于java - 从文件中解密字符串时,RSA 中的解密会抛出 BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20113934/

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