2014-10-13 6 views
0

암호화 및 암호 해독에 RSA 알고리즘을 사용했습니다. 문자열을 암호화 할 때 제대로 작동합니다. 암호를 해독하면 오류가 발생합니다. 아래, 내 코드를 게시합니다.왜 RSA 암호 해독에서 BadPaddingException이 발생합니까?

public final String modulusString =".............."; 
public final String publicExponentString = "AQAB"; 

/* Encryption */ 
byte[] modulebytes = Base64.decode(modulusString); 
byte[] exponentbytes = Base64.decode(publicExponentString); 
BigInteger module = new BigInteger(1,modulebytes); 
BigInteger publicexponent = new BigInteger(1,exponentbytes); 
RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(module, publicexponent); 
KeyFactory fact = KeyFactory.getInstance("RSA"); 
PublicKey pubKey = fact.generatePublic(rsaPubKey); 

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
cipher.init(Cipher.ENCRYPT_MODE, pubKey); 

byte[] plainBytes = EncryptionValue.getBytes("UTF-8"); 
byte[] cipherData = cipher.doFinal(plainBytes); 
String encryptedString = Base64.encode(cipherData); 

return encryptedString; 

/* Decryption */ 
byte[] modulebytes = Base64.decode(modulusString); 
byte[] exponentbytes = Base64.decode(publicExponentString); 

BigInteger modulus = new BigInteger(1, modulebytes); 
BigInteger exponent = new BigInteger(1, exponentbytes); 

RSAPrivateKeySpec rsaPrivKey = new RSAPrivateKeySpec(modulus, exponent); 
KeyFactory fact = KeyFactory.getInstance("RSA"); 
PrivateKey privKey = fact.generatePrivate(rsaPrivKey); 

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); 
cipher.init(Cipher.DECRYPT_MODE, privKey); 

byte[] base64String = Base64.decode(DecryptionValue); 
byte[] plainBytes = new String(base64String).getBytes("UTF-8"); 
plainBytes = cipher.update(plainBytes); 
byte[] values = cipher.doFinal(plainBytes); 

return new String(values, "UTF-8"); 
 
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:2121) 
    at cryptocodefinal.CryptoCodeFinal.DecryptionValue(CryptoCodeFinal.java:79) 
    at cryptocodefinal.CryptoCodeFinal.main(CryptoCodeFinal.java:148) 

답변

2

당신은 공개 키 암호 해독을 한 것으로 나타났습니다. 그것은 작동하지 않습니다. 암호화에 사용 된 공개 지수와 연결된 개인 지수로 해독해야합니다.

개인 키없이 암호를 해독 할 수 없습니다. 이것이 비대칭 암호화의 핵심입니다.

+0

서명이 공개 키인 경우 –

+0

@KirillBazarov 예, 가능하지만이 질문과 관련이 없습니다. – erickson

관련 문제