List of usage examples for org.bouncycastle.cms SignerInformation verify
public boolean verify(SignerInformationVerifier verifier) throws CMSException
From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java
License:Apache License
/** * Method to verify exCap's signature with the issuer certificate stored in * the signed data /*ww w . ja v a 2 s . c om*/ * @param text: the original signed text * @param signature: the signature in byte[] * @return: true if signature is valid, false otherwise * @throws CMSException * @throws OperatorException */ public static boolean validateCapSignature(String text, byte[] signature) throws CMSException, OperatorException { CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature); Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); X509CertificateHolder cert = (X509CertificateHolder) certs.getMatches(signer.getSID()).iterator() .next(); SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert); return signer.verify(verifier); } return false; }
From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java
License:Apache License
/** * Method to verify exCap's signature for the detached signature or the issuer * certificate is not stored in the signed data * @param text: the original signed text * @param signature: the signature in byte[] * @param cert: issuer certificate/*from w w w .j a v a 2 s. c o m*/ * @return: true if signature is valid, false otherwise * @throws CMSException * @throws OperatorException */ public static boolean validateCapSignature(String text, byte[] signature, X509CertificateHolder cert) throws CMSException, OperatorException { CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature); // Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); // X509CertificateHolder cert = (X509CertificateHolder)certs. // getMatches(signer.getSID()).iterator().next(); SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(cert); return signer.verify(verifier); } return false; }
From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java
License:Apache License
/** * Method to verify exCap's signature for the detached signature but the * signature is verified by the public key instead of the certificate * @param text: the original signed text * @param signature: the signature in byte[] * @param cert: issuer public key//from w w w. j a va 2 s .c o m * @return: true if signature is valid, false otherwise * @throws CMSException * @throws OperatorCreationException */ public static boolean validateCapSignature(String text, byte[] signature, AsymmetricKeyParameter pubKey) throws CMSException, OperatorCreationException { boolean ver = false; CMSSignedData signedData = new CMSSignedData(new CMSProcessableByteArray(text.getBytes()), signature); // Store certs = signedData.getCertificates(); SignerInformationStore signers = signedData.getSignerInfos(); Iterator it = signers.getSigners().iterator(); if (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); // X509CertificateHolder cert = (X509CertificateHolder)certs. // getMatches(signer.getSID()).iterator().next(); SignerInformationVerifier verifier = new BcECDSASignerInfoVerifierBuilder( new DefaultCMSSignatureAlgorithmNameGenerator(), new DefaultSignatureAlgorithmIdentifierFinder(), new DefaultDigestAlgorithmIdentifierFinder(), new BcDigestCalculatorProvider()).build(pubKey); log.debug("will now verify the signature..."); ver = signer.verify(verifier); } log.debug("Signature verification result: " + ver); return ver; }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public boolean checkIntegrity(Document detachedDocument) { JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder(); try {//w w w . jav a 2 s.com boolean ret = false; SignerInformation si = null; if (detachedDocument != null) { // Recreate a SignerInformation with the content using a CMSSignedDataParser CMSSignedDataParser sp = new CMSSignedDataParser(new CMSTypedStream(detachedDocument.openStream()), cmsSignedData.getEncoded()); sp.getSignedContent().drain(); si = sp.getSignerInfos().get(signerInformation.getSID()); } else { si = this.signerInformation; } ret = si.verify(verifier.build(getSigningCertificate())); return ret; } catch (OperatorCreationException e) { return false; } catch (CMSException e) { return false; } catch (IOException e) { return false; } }
From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java
License:Open Source License
@Override public SignatureCryptographicVerification checkSignatureIntegrity() { if (signatureCryptographicVerification != null) { return signatureCryptographicVerification; }//from www.j a va 2 s . c o m signatureCryptographicVerification = new SignatureCryptographicVerification(); try { final List<SigningCertificateValidity> signingCertificateValidityList; if (providedSigningCertificateToken == null) { // To determine the signing certificate it is necessary to browse through all candidates found before. final CandidatesForSigningCertificate candidatesForSigningCertificate = getCandidatesForSigningCertificate(); signingCertificateValidityList = candidatesForSigningCertificate .getSigningCertificateValidityList(); if (signingCertificateValidityList.size() == 0) { signatureCryptographicVerification .setErrorMessage("There is no signing certificate within the signature."); return signatureCryptographicVerification; } } else { candidatesForSigningCertificate = new CandidatesForSigningCertificate(); final SigningCertificateValidity signingCertificateValidity = new SigningCertificateValidity( providedSigningCertificateToken); candidatesForSigningCertificate.add(signingCertificateValidity); signingCertificateValidityList = candidatesForSigningCertificate .getSigningCertificateValidityList(); } boolean detached = cmsSignedData.getSignedContent() == null || cmsSignedData.getSignedContent().getContent() == null ? true : false; final SignerInformation signerInformationToCheck; if (detached) { if (detachedContents == null || detachedContents.size() == 0) { if (signingCertificateValidityList.size() > 0) { candidatesForSigningCertificate .setTheSigningCertificateValidity(signingCertificateValidityList.get(0)); } signatureCryptographicVerification.setErrorMessage("Detached file not found!"); return signatureCryptographicVerification; } // Recreate a SignerInformation with the content using a CMSSignedDataParser final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature final InputStream inputStream = dssDocument.openStream(); final CMSTypedStream signedContent = new CMSTypedStream(inputStream); final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent, cmsSignedData.getEncoded()); sp.getSignedContent().drain(); // Closes the stream final SignerId sid = signerInformation.getSID(); signerInformationToCheck = sp.getSignerInfos().get(sid); } else { // if (detachedContents == null || detachedContents.size() == 0) { signerInformationToCheck = signerInformation; } LOG.debug("CHECK SIGNATURE VALIDITY: "); for (final SigningCertificateValidity signingCertificateValidity : signingCertificateValidityList) { try { // In the case where one of the mandatory attributes is missing we set already the candidate for the signing certificate. // see: validation.at.nqs.bdc.TestNotQualifiedBDC.test1() candidatesForSigningCertificate.setTheSigningCertificateValidity(signingCertificateValidity); final JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder(); final CertificateToken certificateToken = signingCertificateValidity.getCertificateToken(); final X509Certificate certificate = certificateToken.getCertificate(); final SignerInformationVerifier signerInformationVerifier = verifier.build(certificate); LOG.debug(" - WITH SIGNING CERTIFICATE: " + certificateToken.getAbbreviation()); boolean signatureIntact = signerInformationToCheck.verify(signerInformationVerifier); signatureCryptographicVerification.setReferenceDataFound(signatureIntact); signatureCryptographicVerification.setReferenceDataIntact(signatureIntact); signatureCryptographicVerification.setSignatureIntact(signatureIntact); if (signatureIntact) { break; } } catch (RuntimeOperatorException e) { // Cest un problme de compatibilit avec Java 7. Limplmentation de la classe sun.security.rsa.RSASignature a chang entre la version 6 et 7. Bouncy castle ne // prend pas correctement en compte ce changement. En effet, une exception est leve par la version 7 que BC ne catch pas correctement ce qui se traduit par // lenvoi dune exception : org.bouncycastle.operator.RuntimeOperatorException (Bob) LOG.warn(e.getMessage(), e); } catch (CMSSignerDigestMismatchException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setReferenceDataFound(true); signatureCryptographicVerification.setReferenceDataIntact(false); signatureCryptographicVerification.setSignatureIntact(false); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (OperatorCreationException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (CMSException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (IllegalArgumentException e) { // Can arrive when for example: // java.lang.IllegalArgumentException: Unknown signature type requested: RIPEMD160WITH0.4.0.127.0.7.1.1.4.1.6 // at org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder.generate(Unknown Source) ~[bcpkix-jdk15on-1.49.jar:1.49.0] LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } } } catch (CMSException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } LOG.debug(" - RESULT: " + signatureCryptographicVerification.isReferenceDataFound() + "/" + signatureCryptographicVerification.isReferenceDataIntact() + "/" + signatureCryptographicVerification.isSignatureIntact()); return signatureCryptographicVerification; }
From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java
License:Open Source License
@Override public SignatureCryptographicVerification checkSignatureIntegrity() { if (signatureCryptographicVerification != null) { return signatureCryptographicVerification; }/*from w w w . ja v a 2 s . c o m*/ signatureCryptographicVerification = new SignatureCryptographicVerification(); try { final List<CertificateValidity> certificateValidityList = getCertificateValidityList(); if (certificateValidityList.size() == 0) { signatureCryptographicVerification .setErrorMessage("There is no signing certificate within the signature."); return signatureCryptographicVerification; } boolean detachedSignature = isDetachedSignature(); final SignerInformation signerInformationToCheck; if (detachedSignature) { if (CollectionUtils.isEmpty(detachedContents)) { if (certificateValidityList.size() > 0) { candidatesForSigningCertificate.setTheCertificateValidity(certificateValidityList.get(0)); } signatureCryptographicVerification.setErrorMessage("Detached file not found!"); return signatureCryptographicVerification; } signerInformationToCheck = recreateSignerInformation(); } else { signerInformationToCheck = signerInformation; } signatureCryptographicVerification.setReferenceDataFound(true); LOG.debug("CHECK SIGNATURE VALIDITY: "); if (signingCertificateValidity != null) { // for (final CertificateValidity certificateValidity : // certificateValidityList) { try { // In the case where one of the mandatory attributes is // missing we set already the candidate for the signing // certificate. // see: validation.at.nqs.bdc.TestNotQualifiedBDC.test1() candidatesForSigningCertificate.setTheCertificateValidity(signingCertificateValidity); final JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder(); final CertificateToken certificateToken = signingCertificateValidity.getCertificateToken(); final PublicKey publicKey = certificateToken.getPublicKey(); final SignerInformationVerifier signerInformationVerifier = verifier.build(publicKey); LOG.debug(" - WITH SIGNING CERTIFICATE: " + certificateToken.getAbbreviation()); boolean signatureIntact = signerInformationToCheck.verify(signerInformationVerifier); signatureCryptographicVerification.setReferenceDataIntact(signatureIntact); signatureCryptographicVerification.setSignatureIntact(signatureIntact); } catch (Exception e) { LOG.error("Unable to validate CMS Signature : " + e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); signatureCryptographicVerification.setReferenceDataIntact(false); signatureCryptographicVerification.setSignatureIntact(false); } } } catch (CMSException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } catch (IOException e) { LOG.error(e.getMessage(), e); signatureCryptographicVerification.setErrorMessage(e.getMessage()); } LOG.debug(" - RESULT: " + signatureCryptographicVerification.toString()); return signatureCryptographicVerification; }
From source file:eu.peppol.as2.MimeMessageHelperTest.java
License:EUPL
/** * verify the signature (assuming the cert is contained in the message) *//* w w w . j av a 2s. c o m*/ private boolean verify(String resourceName, boolean debug) { System.out.println("Verifying resource " + resourceName + " (debug=" + debug + ")"); String resourcePath = "real-mdn-examples/" + resourceName; try { // add provider Security.addProvider(new BouncyCastleProvider()); // shortcuts lots of steps in the above test (parseLegalMimeMessageWithHeaders) MimeMultipart multipartSigned = (MimeMultipart) MimeMessageHelper .createMimeMessage( MimeMessageHelperTest.class.getClassLoader().getResourceAsStream(resourcePath)) .getContent(); assertNotNull(multipartSigned); // verify signature SMIMESigned signedMessage = new SMIMESigned(multipartSigned); Store certs = signedMessage.getCertificates(); SignerInformationStore signers = signedMessage.getSignerInfos(); for (Object signerInformation : signers.getSigners()) { SignerInformation signer = (SignerInformation) signerInformation; Collection certCollection = certs.getMatches(signer.getSID()); Iterator certIterator = certCollection.iterator(); X509Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()) .getCertificate((X509CertificateHolder) certIterator.next()); if (debug) System.out.println("Signing certificate : " + cert); SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder() .setProvider(new BouncyCastleProvider()).build(cert); if (signer.verify(signerInformationVerifier)) return true; } } catch (Exception ex) { System.out.println("Verification failed with exception " + ex.getMessage()); } return false; }
From source file:eu.peppol.as2.SignedMimeMessage.java
License:EUPL
void parseSignedMessage() { SMIMESignedParser smimeSignedParser = null; try {//from w w w . j a v a 2 s .co m // MimeMessageHelper.dumpMimePartToFile("/tmp/parseSignedMessage.txt", mimeMessage); smimeSignedParser = new SMIMESignedParser(new JcaDigestCalculatorProviderBuilder().build(), (MimeMultipart) mimeMessage.getContent()); } catch (MessagingException | CMSException | IOException | OperatorCreationException e) { throw new IllegalStateException("Unable to create SMIMESignedParser: " + e.getMessage(), e); } Store certs = null; try { certs = smimeSignedParser.getCertificates(); } catch (CMSException e) { throw new IllegalStateException("Unable to retrieve the certificates from signed message."); } // // SignerInfo blocks which contain the signatures // SignerInformationStore signerInfos = null; try { signerInfos = smimeSignedParser.getSignerInfos(); } catch (CMSException e) { throw new IllegalStateException("Unable to get the Signer information from message. " + e.getMessage(), e); } Collection signers = signerInfos.getSigners(); Iterator signersIterator = signers.iterator(); // // Only a single signer, get the first and only certificate // if (signersIterator.hasNext()) { // Retrieves information on first and only signer SignerInformation signer = (SignerInformation) signersIterator.next(); // Retrieves the collection of certificates for first and only signer Collection certCollection = certs.getMatches(signer.getSID()); // Retrieve the first certificate Iterator certIt = certCollection.iterator(); if (certIt.hasNext()) { try { signersX509Certificate = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate((X509CertificateHolder) certIt.next()); } catch (CertificateException e) { throw new IllegalStateException("Unable to fetch certificate for signer. " + e.getMessage(), e); } } else { throw new IllegalStateException( "Signers certificate was not found, unable to verify the signature"); } // Verify that the signature is correct and that signersIterator was generated when the certificate was current try { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()) .build(signersX509Certificate))) { throw new IllegalStateException("Verification of signer failed"); } } catch (CMSException e) { throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e); } catch (OperatorCreationException e) { throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e); } String issuerDN = signersX509Certificate.getIssuerDN().toString(); log.debug("Certificate issued by: " + issuerDN); } else { throw new IllegalStateException("There is no signer information available"); } }
From source file:eu.peppol.as2.SignedMimeMessageInspector.java
License:Open Source License
void parseSignedMessage() { SMIMESignedParser smimeSignedParser = null; try {/*from ww w. java2 s .c o m*/ // MimeMessageHelper.dumpMimePartToFile("/tmp/parseSignedMessage.txt", mimeMessage); smimeSignedParser = new SMIMESignedParser(new BcDigestCalculatorProvider(), (MimeMultipart) mimeMessage.getContent()); } catch (MessagingException e) { throw new IllegalStateException("Unable to get content of message." + e.getMessage(), e); } catch (CMSException e) { throw new IllegalStateException("Unable to get content of message. " + e.getMessage(), e); } catch (IOException e) { throw new IllegalStateException("Unable to get content of message. " + e.getMessage(), e); } Store certs = null; try { certs = smimeSignedParser.getCertificates(); } catch (CMSException e) { throw new IllegalStateException("Unable to retrieve the certificates from signed message."); } // // SignerInfo blocks which contain the signatures // SignerInformationStore signerInfos = null; try { signerInfos = smimeSignedParser.getSignerInfos(); } catch (CMSException e) { throw new IllegalStateException("Unable to get the Signer information from message. " + e.getMessage(), e); } Collection signers = signerInfos.getSigners(); Iterator signersIterator = signers.iterator(); // // Only a single signer, get the first and only certificate // if (signersIterator.hasNext()) { // Retrieves information on first and only signer SignerInformation signer = (SignerInformation) signersIterator.next(); // Retrieves the collection of certificates for first and only signer Collection certCollection = certs.getMatches(signer.getSID()); // Retrieve the first certificate Iterator certIt = certCollection.iterator(); if (certIt.hasNext()) { try { signersX509Certificate = new JcaX509CertificateConverter().setProvider(provider) .getCertificate((X509CertificateHolder) certIt.next()); } catch (CertificateException e) { throw new IllegalStateException("Unable to fetch certificate for signer. " + e.getMessage(), e); } } else { throw new IllegalStateException( "Signers certificate was not found, unable to verify the signature"); } // Verify that the signature is correct and that signersIterator was generated when the certificate was current try { if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider) .build(signersX509Certificate))) { throw new IllegalStateException("Verification of signer failed"); } } catch (CMSException e) { throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e); } catch (OperatorCreationException e) { throw new IllegalStateException("Unable to verify the signer. " + e.getMessage(), e); } // Verify that the certificate issuer is trusted String issuerDN = signersX509Certificate.getIssuerDN().toString(); log.debug("Verify the certificate issuer : " + issuerDN); //TODO validateCertificate(signersX509Certificate); } else { throw new IllegalStateException("There is no signer information available"); } }
From source file:id.govca.detachedsignature.CMSController.java
public boolean VerifyCMS(CMSSignedData signedData, String content_digest) throws IOException, CMSException, CertificateException, OperatorCreationException, UnmatchedSignatureException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, StringFormatException, ParseException, GeneralSecurityException { rootCertCandidate = null;//from w ww. java 2 s. c om Security.addProvider(new BouncyCastleProvider()); byte[] dataku = (byte[]) signedData.getSignedContent().getContent(); System.out.format("%-32s%s\n", "Base64 of Signed Content", Hex.toHexString(dataku)); Store store = signedData.getCertificates(); CertStore certsAndCRLs = new JcaCertStoreBuilder().setProvider("BC") .addCertificates(signedData.getCertificates()).build(); // Verify signature SignerInformationStore signers = signedData.getSignerInfos(); Collection c = signers.getSigners(); System.out.format("%-32s%s\n", "Number of Signers", c.size()); Iterator it = c.iterator(); while (it.hasNext()) { SignerInformation signer = (SignerInformation) it.next(); AttributeTable att = signer.getSignedAttributes(); Attribute mdAtt = att.get(CMSAttributes.messageDigest); ASN1Primitive asp = mdAtt.getAttrValues().getObjectAt(0).toASN1Primitive(); byte[] hasil = asp.getEncoded("DER"); System.out.format("%-32s%s\n", "Digest of Signature", Hex.toHexString(hasil)); Collection certCollection = store.getMatches(signer.getSID()); JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC"); ArrayList<X509CertificateHolder> listCertDatFirm = new ArrayList(store.getMatches(null)); System.out.format("%-32s%d\n", "Number of cert Holders All", listCertDatFirm.size()); try { verifyChain(listCertDatFirm); } catch (CertificateVerificationException ex) { System.out.println("CERTIFICATE CHAIN VERIFICATION FAILED"); Logger.getLogger(CMSController.class.getName()).log(Level.SEVERE, null, ex); throw new UnmatchedSignatureException("Certificate Chain verification failed"); } System.out.println("CERTIFICATE CHAIN VERIFIED"); Collection<X509CertificateHolder> holders = store.getMatches(signer.getSID()); Iterator certIt = certCollection.iterator(); X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next(); X509Certificate certFromSignedData = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()).getCertificate(certHolder); Principal princ = certFromSignedData.getIssuerDN(); //Get Signer Name Principal p = certFromSignedData.getSubjectDN(); System.out.format("%-32s%s\n", "Signer Distinguished Name", p.getName()); this.setDN_fields(StringHelper.DNFieldsMapper(p.getName())); //Get Signing Time org.bouncycastle.asn1.cms.Attribute signingTime = att .get(new ASN1ObjectIdentifier("1.2.840.113549.1.9.5")); String asn1time = signingTime.getAttrValues().toString(); System.out.format("%-32s%s\n", "Signing Time (RAW format)", asn1time); Date signtime = StringHelper.ASN1DateParser(asn1time); SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz"); String formattedDate = formatter.format(signtime); System.out.format("%-32s%s\n", "Signing Time (Pretty format)", formattedDate); PublicKey pubkey = certFromSignedData.getPublicKey(); if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()) .build(certFromSignedData))) { System.out.println("SIGNATURE VERIFIED <BY BOUNCY CASTLE STANDARD>"); } else { System.out.println("SIGNATURE VERIFICATION <BY BOUNCY CASTLE STANDARD> FAILED"); throw new UnmatchedSignatureException( "Signature verification failed, probably the signature (CMS) has been altered!"); } Cipher RSADecrypter; RSADecrypter = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); //Initialize the Cipher using our the first key in the keystore works fine for both RSADecrypter.init(Cipher.DECRYPT_MODE, pubkey); byte[] try_decrypt = RSADecrypter.doFinal(dataku); String decrypt_result = Hex.toHexString(try_decrypt); //Because there is magic number for hash algorithm at the beginning of the string, //we only need the last 64 characters from the decryption result String sanitized_decrypt_result = decrypt_result.substring(decrypt_result.length() - 64); System.out.format("%-32s%s\n", "Decryption Result", decrypt_result); System.out.format("%-32s%s\n", "Sanitized Decryption Result", sanitized_decrypt_result); if (!content_digest.equals(sanitized_decrypt_result)) { System.out.println("CONTENT DIGEST VERIFICATION FAILED"); throw new UnmatchedSignatureException( "Content digest verification failed, probably the content has been altered!"); } System.out.println("CONTENT DIGEST VERIFIED"); try { RootCertChecker rc = new RootCertChecker(); rc.checkCertificate(rootCertCandidate, getRoot_cert_path()); } catch (FileNotFoundException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | SignatureException | CertificateException ex) { System.out.println("ROOT CERT VERIFICATION FAILED"); throw new UnmatchedSignatureException("The System does not recognized this root Certificate"); } System.out.println("ROOT CERTIFICATE VERIFIED"); } return true; }