проверка отдельной подписи с помощью BC

Как проверить отсоединенную подпись (подпись CMS/pkcs #7) с помощью провайдера BouncyCastle в Java?

В настоящее время мой код ниже выдает исключение с сообщением message-digest attribute value does not match calculated value

Security.addProvider(new BouncyCastleProvider());

File f = new File(filename);
byte[] buffer = new byte[(int)f.length()];
DataInputStream in = new DataInputStream(new FileInputStream(f));
in.readFully(buffer);
in.close();

CMSSignedData signature = new CMSSignedData(buffer);
SignerInformation signer = (SignerInformation) signature.getSignerInfos().getSigners().iterator().next();
CertStore cs = signature.getCertificatesAndCRLs("Collection", "BC");
Iterator iter = cs.getCertificates(signer.getSID()).iterator();
X509Certificate certificate = (X509Certificate) iter.next();

CMSProcessable sc = signature.getSignedContent();

signer.verify(certificate, "BC");

person meriem    schedule 23.11.2011    source источник
comment
Вы протестировали код, найденный здесь: bouncy-castle.1462172.n4.nabble.com/ ? В настоящее время нет конкретного места, где вы действительно принимаете во внимание отдельные данные.   -  person Maarten Bodewes    schedule 06.12.2011
comment
Я решил эту проблему, вы можете найти ответ [здесь] [1] [1]: stackoverflow.com/questions/8590426/   -  person Swapnil    schedule 18.12.2013


Ответы (3)


Вы можете проверить отсоединенную подпись с помощью следующего кода:

public static boolean verif_Detached(String signed_file_name,String original_file_name) throws IOException, CMSException, NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CertificateExpiredException, CertificateNotYetValidException{

    boolean result= false;
    Security.addProvider(new BouncyCastleProvider()); 

    File f = new File(signed_file_name);
    byte[] Sig_Bytes = new byte[(int)f.length()];
    DataInputStream in = new DataInputStream(new FileInputStream(f));
    in.readFully(Sig_Bytes);
    in.close();

    File fi = new File(original_file_name);
    byte[] Data_Bytes = new byte[(int)fi.length()];
    DataInputStream input = new DataInputStream(new FileInputStream(fi));
    input.readFully(Data_Bytes);
    input.close();

    try{
        CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(Data_Bytes), Sig_Bytes); 
        CertStore certStore = cms.getCertificatesAndCRLs("Collection", "BC"); 
        SignerInformationStore signers = cms.getSignerInfos(); 
        Collection c = signers.getSigners(); 
        Iterator it = c.iterator(); 
        while (it.hasNext()) { 
            SignerInformation signer = (SignerInformation) it.next(); 
            Collection certCollection = certStore.getCertificates(signer.getSID()); 
            Iterator certIt = certCollection.iterator(); 
            X509Certificate cert = (X509Certificate) certIt.next();
            cert_signer=cert;
            result=signer.verify(cert, "BC");
        }
    }catch(Exception e){
        e.printStackTrace();
        result=false;
    }
    return result; 
}
person meriem    schedule 13.02.2012
comment
Откуда взялся класс CMSSignedData? - person cgajardo; 30.09.2015
comment
@cgajardo org.bouncycastle.cms.CMSSignedData - person user2677034; 24.01.2020

ключом для проверки отсоединенного pKCS7 является использование CMSTypedStream, например код ниже:

public void verifySign(byte[] signedData,byte[]bPlainText) throws Exception {
                InputStream is  = new ByteArrayInputStream(bPlainText);             
                CMSSignedDataParser sp = new CMSSignedDataParser(new CMSTypedStream (is),signedData);
                CMSTypedStream signedContent = sp.getSignedContent();           

                 signedContent.drain();





                  //CMSSignedData s = new CMSSignedData(signedData); 
                  Store certStore = sp.getCertificates(); 

                  SignerInformationStore signers = sp.getSignerInfos(); 
                    Collection c = signers.getSigners();
                    Iterator it = c.iterator();
                    while (it.hasNext()) 
                    { 
                        SignerInformation signer = (SignerInformation)it.next(); 
                        Collection certCollection = certStore.getMatches(signer.getSID()); 

                        Iterator certIt = certCollection.iterator(); 

                        X509CertificateHolder certHolder = (X509CertificateHolder)certIt.next(); 




                        if ( !signer.verify(new 
            JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certHolder))) 
                        { 
                            throw new DENException("Verification FAILED! "); 

                        } 
                        else
                        {
                            logger.debug("verify success" );
                        }


                    } 
    }
person hoefer    schedule 23.12.2011
comment
вы можете проверить отсоединенную подпись с помощью этого кода: CMSSignedData cms = new CMSSignedData (новый CMSProcessableByteArray (Data_Bytes), Sig_Bytes); - person meriem; 13.02.2012

Вы можете найти ответ на этот пост здесь. Это происходит из-за того, как надувной замок/открытый ssl обрабатывает сообщение S/MIME, когда заголовки S/MIME отсутствуют. Решение состоит в том, чтобы добавить заголовки S/MIME в сообщение перед подписью.

person Community    schedule 19.12.2013