[英]decrypting in RSA throws BadPaddingException when decrypting a string from file
我使用此程序輸出加密的字符串,然后將字符串復制並粘貼到我讀取並嘗試解密的文件中。 如果我嘗試解密程序中生成的字符串,則程序運行正常。 僅當我將加密的字符串復制到文件然后嘗試對其解密時,它才會失敗。 這是我得到的錯誤-
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
,該String
希望這些字節以某種編碼方案(可能是UTF-8或UTF-16)表示有效的Unicode文本,取決於您使用的操作系統。 由於加密的數據可能包含無效的UTF-8 / UTF-16字節序列,因此String
構造函數將忽略無效字節或將其替換為占位符,從而有效地破壞了數據。
如果您想以安全的格式顯示加密的數據,然后將其復制/粘貼為文本,則應將byte[]
轉換為十六進制字符串(就像您對密鑰所做的那樣),或使用Base64對其進行編碼,而不是直接將其傳遞給String
構造函數。
加密的唯一問題是,解密是您沒有通過使用某些編碼技術將加密的字節encoding
為Unicode
轉換。 我們使用Base64
作為生成此類encoded
字節序列的通用平台。 稍微修改一下編碼和解碼即可為您工作,
public byte[] encrypt(String 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.getBytes("UTF8"));
return org.apache.commons.codec.binary.Base64.encodeBase64(cipherData);
}
public byte[] decrypt(String 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[] byteCipherText = org.apache.commons.codec.binary.Base64.decodeBase64(data) ;
byte[] cipherData = cipher.doFinal(byteCipherText);
return cipherData; //// use new String(cipherData, "UTF8"); to get the original strings
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.