2015-01-08 1 views
3

JKS 내부의 cert를 사용하여 암호화 된 "test.txt.p7b"파일의 암호를 해독하려고합니다.예외 래핑 키 : 잘못된 채움 : 암호 해독 오류

코드를 디버깅하는 동안이 오류가 발생했습니다. 누군가가이 오류에 대해 설명 할 수 있다면 감사하게 생각하십시오. 내 키가 문제가 생겼거나 내 코드는 (주로, 난 그렇게 생각) 아래 .Many 덕분에

오류 메시지

Exception in thread "main" org.bouncycastle.cms.CMSException: exception unwrapping key: bad padding: Decryption error 
    at org.bouncycastle.cms.jcajce.JceKeyTransRecipient.extractSecretKey(Unknown Source) 
    at org.bouncycastle.cms.jcajce.JceKeyTransEnvelopedRecipient.getRecipientOperator(Unknown Source) 
    at org.bouncycastle.cms.KeyTransRecipientInformation.getRecipientOperator(Unknown Source) 
    at org.bouncycastle.cms.RecipientInformation.getContentStream(Unknown Source) 
    at org.bouncycastle.cms.RecipientInformation.getContent(Unknown Source) 
    at TestingB.decryptData(TestingB.java:299) 
    at TestingB.main(TestingB.java:161) 
Caused by: org.bouncycastle.operator.OperatorException: bad padding: Decryption error 
    at org.bouncycastle.operator.jcajce.JceAsymmetricKeyUnwrapper.generateUnwrappedKey(Unknown Source) 
    ... 7 more 
Caused by: javax.crypto.BadPaddingException: Decryption error 
    at sun.security.rsa.RSAPadding.unpadV15(Unknown Source) 
    at sun.security.rsa.RSAPadding.unpad(Unknown Source) 
    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) 
    ... 8 more 

을 문제가 생겼 그리고 여기 내 암호 해독 코드입니다.

FileInputStream fIn = new FileInputStream(_keyStorePath); 
    KeyStore keystore = KeyStore.getInstance("JKS"); 
    keystore.load(fIn, _password); 
    PrivateKey key = (PrivateKey) keystore.getKey("def","123456".toCharArray()); 
    fIn.close(); 


    File file = new File("C:\\1_Eclipse\\1_CS\\Encrypted\\test.txt.p7b"); 
    FileInputStream fileInputStream = new FileInputStream(file); 
    byte[] encryptedAndSignedByte = new byte[(int)file.length()]; 
    fileInputStream.read(encryptedAndSignedByte); 
    fileInputStream.close(); 


    X509Certificate cert9 = (X509Certificate) keystore.getCertificate("abc"); 
    KeyTransRecipientId recId = new JceKeyTransRecipientId(cert9.getIssuerX500Principal(), cert9.getSerialNumber()); 

    CMSEnvelopedData enveloped = new CMSEnvelopedData(encryptedAndSignedByte); 
    RecipientInformationStore recipients = enveloped.getRecipientInfos(); 
    RecipientInformation recipient = recipients.get(recId); 
    JceKeyTransEnvelopedRecipient ter = new JceKeyTransEnvelopedRecipient(key); 
    ter.setContentProvider(BouncyCastleProvider.PROVIDER_NAME); 
    System.out.println("content : " + recipient.getContent(ter)); 

답변

0

여기에서 나는 잘못 될 수는 없지만 RSA 비공개 키에 의해 대칭 키를 해독하는 동안 오류가 발생합니다.

CMS는 컨테이너 형식입니다. 여기에는 데이터를 처리하거나 포함하는 메소드가 들어 있습니다. 컨테이너를 포위하는 경우 RSA 공개 키로 데이터가 직접 암호화되지 않습니다. 대신 무작위 대칭 키 (종종 데이터 키 또는 세션 키라고도 함)로 암호화됩니다. 이 대칭 키는 공개 키로 암호화됩니다.

RSA 암호화는 먼저 데이터를 채운 다음 공개 지수로 모듈러 지수를 수행합니다. 암호 해독은 개인 지수와 모듈화 지수로 구성되며 패딩되지 않습니다. 이제 모듈러 지수는 데이터 또는 지수의 값이 무엇이든간에 항상 성공합니다. 따라서 데이터 또는 키가 유효하지 않은 경우 패딩 예외가 유일한 표시입니다.

컨테이너의 데이터가 유효 할 가능성이 있습니다 (그렇지 않은 경우 디코딩 오류가 발생할 것으로 예상됩니다). 개인 키가 공개 키와 일치하지 않을 가능성이 훨씬 큽니다. 그것은 CMS 라이브러리의 구현 실수를 배제하지 않지만, CMS 라이브러리가 잘 테스트 되었다면 상대적으로 어려울 것으로 생각합니다.

그래서 코드보다는 키 값을 의심 할 것입니다. 물론 키를 읽거나 쓰는 코드에서 실수를하는 것이 가능합니다.

모두 제가 코드에서 스트림 처리를 확실히 수정했습니다. encryptedAndSignedByte 버퍼를 만들고 read을 한 번 호출하는 것은 매우 순진합니다. 이 오류가 수정되면 저희에게 알려주십시오.

+0

안녕하세요. 감사합니다. 이제 파일을 해독 할 수 있습니다. :) 많은 감사합니다. 중요한 문제입니다. 위의 코드가 멋지다. – CSSC

+0

CSSC가 해결했으면 좋겠다. 대답을 받아들이는 것을 잊지 마라. –

0

코드를 수정했지만 동일한 문제가 발생합니다. 나는 암호화 부분이 어떤 문제도되어서는 안된다고 믿는다.

암호 해독 코드 : 나는 오류가 내 암호 해독이 부분에 의해 발생되었다고 판단 메인 클래스

new File("C:\\1_Eclipse\\1_CS\\Encrypted\\test_result.txt"); 
     FileOutputStream E_fileOuputStream = new FileOutputStream("C:\\1_Eclipse\\1_CS\\Encrypted\\test_result.txt"); 
     FileInputStream E_fileInputStream = new FileInputStream("C:\\1_Eclipse\\1_CS\\Encrypted\\test.txt.p7b"); 

     decrypt(E_fileInputStream,E_fileOuputStream,key,"BC"); 

에서

public static void decrypt(final InputStream is, OutputStream os, Key key, String providerName) throws Exception { 
     final InputStream bis = new BufferedInputStream(is, bufferSize); 
     final OutputStream bos = new BufferedOutputStream(os, bufferSize); 
     final Iterator it = new CMSEnvelopedDataParser(bis).getRecipientInfos().getRecipients().iterator(); 
     if (it.hasNext()) { 
      final RecipientInformation recipient = (RecipientInformation)it.next(); 
      JceKeyTransEnvelopedRecipient ter = new JceKeyTransEnvelopedRecipient((PrivateKey) key); 
      final CMSTypedStream recData = recipient.getContentStream(ter); 
      final InputStream ris = recData.getContentStream(); 
      fromInToOut(ris, bos); 
     } 
     os.close(); 
    } 

.

final RecipientInformation recipient = (RecipientInformation)it.next(); 
      JceKeyTransEnvelopedRecipient ter = new JceKeyTransEnvelopedRecipient((PrivateKey) key); 
      final CMSTypedStream recData = recipient.getContentStream(ter); 
+0

알다시피, 나는 답변으로 게시 됨으로서 이것을 완전히 놓쳤다. 질문에 대한 후속 답변을 작성하지 마십시오. 새로운 답변을 만들거나 현재 답변을 수정하십시오. –