@Override public AlgorithmIdentifier findEncryptionAlgorithm(AlgorithmIdentifier id) { // Use the default chooser, but replace dsaWithSha1 with dsa. This is because "dsa" is // accepted by any Android platform whereas "dsaWithSha1" is accepted only since // API Level 9. id = mDefault.findEncryptionAlgorithm(id); if (id != null) { ASN1ObjectIdentifier oid = id.getAlgorithm(); if (X9ObjectIdentifiers.id_dsa_with_sha1.equals(oid)) { return DSA; } } return id; } }
new JcaContentSignerBuilder(jcaSignatureAlgorithm) .build(signerConfig.privateKey); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); gen.addSignerInfoGenerator( new SignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().build(), SignerInfoSignatureAlgorithmFinder.INSTANCE) .setDirectSignature(true) .build(signer, new JcaX509CertificateHolder(signerCert))); gen.addCertificates(certs); gen.generate(new CMSProcessableByteArray(signatureFileBytes), false); try (ASN1InputStream asn1 = new ASN1InputStream(sigData.getEncoded())) { DEROutputStream dos = new DEROutputStream(out); dos.writeObject(asn1.readObject());
public boolean verify(PublicKey publicKey) throws Exception { for (Object info : data.getSignerInfos().getSigners()) { SignerInformation signer = (SignerInformation)info; if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(publicKey))) { return true; } } return false; }
@SuppressWarnings(value = "unchecked") public static byte[] sign(Providers providers, SignedOutput out) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, CMSException, OperatorCreationException, CertificateEncodingException { ByteArrayOutputStream bodyOs = new ByteArrayOutputStream(); MessageBodyWriter writer = providers.getMessageBodyWriter(out.getType(), out.getGenericType(), null, out.getMediaType()); if (writer == null) { throw new WriterException(Messages.MESSAGES.failedToFindWriter(out.getType().getName())); } MultivaluedMapImpl<String, Object> bodyHeaders = new MultivaluedMapImpl<String, Object>(); bodyHeaders.add("Content-Type", out.getMediaType().toString()); writer.writeTo(out.getEntity(), out.getType(), out.getGenericType(), null, out.getMediaType(), bodyHeaders, bodyOs); CMSSignedDataGenerator signGen = new CMSSignedDataGenerator(); ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(out.getPrivateKey()); signGen.addSignerInfoGenerator( new JcaSignerInfoGeneratorBuilder( new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()) .build(sha1Signer, out.getCertificate())); CMSTypedData content = new CMSProcessableByteArray(bodyOs.toByteArray()); CMSSignedData signedData = signGen.generate(content, true); return signedData.getEncoded(); } }
/** * get certificate info */ @SuppressWarnings("unchecked") public List<CertificateMeta> parse() throws CertificateException { CMSSignedData cmsSignedData; try { cmsSignedData = new CMSSignedData(data); } catch (CMSException e) { throw new CertificateException(e); } Store<X509CertificateHolder> certStore = cmsSignedData.getCertificates(); SignerInformationStore signerInfos = cmsSignedData.getSignerInfos(); Collection<SignerInformation> signers = signerInfos.getSigners(); List<X509Certificate> certificates = new ArrayList<>(); for (SignerInformation signer : signers) { Collection<X509CertificateHolder> matches = certStore.getMatches(signer.getSID()); for (X509CertificateHolder holder : matches) { certificates.add(new JcaX509CertificateConverter().setProvider(provider).getCertificate(holder)); } } return CertificateMetas.from(certificates); }
/** * Processes a signer store and goes through the signers certificate-chain. Adds the found data * to the certInfo. Handles only the first signer, although multiple would be possible, but is * not yet practicable. * * @param certificatesStore To get the certificate information from. Certificates will be saved * in certificatesMap. * @param signedData data from which to get the SignerInformation * @param certInfo where to add certificate information * @return Signer Information of the processed certificatesStore for further usage. * @throws IOException on data-processing error * @throws CertificateProccessingException on a specific error with a certificate */ private SignerInformation processSignerStore(Store<X509CertificateHolder> certificatesStore, CMSSignedData signedData, CertSignatureInformation certInfo) throws IOException, CertificateProccessingException { Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners(); SignerInformation signerInformation = signers.iterator().next(); @SuppressWarnings("unchecked") Collection<X509CertificateHolder> matches = certificatesStore .getMatches((Selector<X509CertificateHolder>) signerInformation.getSID()); X509Certificate certificate = getCertFromHolder(matches.iterator().next()); Collection<X509CertificateHolder> allCerts = certificatesStore.getMatches(null); addAllCerts(allCerts); traverseChain(certificate, certInfo, MAX_CERTIFICATE_CHAIN_DEPTH); return signerInformation; }
/** * Extend cms signed data with TimeStamp first or to all signers * * @param signedData Generated CMS signed data * @return CMSSignedData Extended CMS signed data * @throws IOException */ public CMSSignedData addSignedTimeStamp(CMSSignedData signedData) throws IOException { SignerInformationStore signerStore = signedData.getSignerInfos(); List<SignerInformation> newSigners = new ArrayList<>(); for (SignerInformation signer : signerStore.getSigners()) { // This adds a timestamp to every signer (into his unsigned attributes) in the signature. newSigners.add(signTimeStamp(signer)); } // Because new SignerInformation is created, new SignerInfoStore has to be created // and also be replaced in signedData. Which creates a new signedData object. return CMSSignedData.replaceSigners(signedData, new SignerInformationStore(newSigners)); }
public Object getEntity(Class t, Type gt, Annotation[] ann, PrivateKey pKey, X509Certificate cert) { MimeBodyPart decrypted = null; try { MimeBodyPart encryptedBodyPart = body; SMIMEEnveloped m = new SMIMEEnveloped(encryptedBodyPart); JceKeyTransRecipientId recId = new JceKeyTransRecipientId(cert); RecipientInformationStore recipients = m.getRecipientInfos(); RecipientInformation recipient = recipients.get(recId); JceKeyTransRecipient pKeyRecp = new JceKeyTransEnvelopedRecipient(pKey); decrypted = SMIMEUtil.toMimeBodyPart(recipient.getContent(pKeyRecp)); } catch (Exception e1) { throw new RuntimeException(e1); } return extractEntity(t, gt, ann, decrypted, providers); }
private TimeStampToken extractTimeStampTokenFromSignerInformation(SignerInformation signerInformation) throws CMSException, IOException, TSPException { if (signerInformation.getUnsignedAttributes() == null) { return null; } AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes(); // https://stackoverflow.com/questions/1647759/how-to-validate-if-a-signed-jar-contains-a-timestamp Attribute attribute = unsignedAttributes.get( PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (attribute == null) { return null; } ASN1Object obj = (ASN1Object) attribute.getAttrValues().getObjectAt(0); CMSSignedData signedTSTData = new CMSSignedData(obj.getEncoded()); return new TimeStampToken(signedTSTData); }
/** * Processes one signature and its including certificates. * * @param signatureContent the byte[]-Content of the signature * @return the CertSignatureInformation for this signature * @throws IOException * @throws CertificateProccessingException */ private CertSignatureInformation getCertInfo(byte[] signatureContent) throws CertificateProccessingException, IOException { rootCertInfo = new CertSignatureInformation(); rootCertInfo.signatureHash = CertInformationHelper.getSha1Hash(signatureContent); try { CMSSignedData signedData = new CMSSignedData(signatureContent); Store<X509CertificateHolder> certificatesStore = signedData.getCertificates(); SignerInformation signerInformation = processSignerStore(certificatesStore, signedData, rootCertInfo); addTimestampCerts(signerInformation); } catch (CMSException e) { LOG.error("Error occurred getting Certificate Information from Signature", e); throw new CertificateProccessingException(e); } return rootCertInfo; }
/** * PKS Encoded bytes * * @param bytes data */ public PKCS7SignatureInput(final byte[] bytes) { try { this.data = new CMSSignedData(bytes); } catch (CMSException e) { throw new RuntimeException(e); } }
BigInteger signerCertSerialNumber = signerId.getSerialNumber(); X500Name signerCertIssuer = signerId.getIssuer(); LOG.log(POILogger.DEBUG, "signer cert serial number: " + signerCertSerialNumber); LOG.log(POILogger.DEBUG, "signer cert issuer: " + signerCertIssuer); DefaultCMSSignatureAlgorithmNameGenerator nameGen = new DefaultCMSSignatureAlgorithmNameGenerator(); DefaultSignatureAlgorithmIdentifierFinder sigAlgoFinder = new DefaultSignatureAlgorithmIdentifierFinder(); DefaultDigestAlgorithmIdentifierFinder hashAlgoFinder = new DefaultDigestAlgorithmIdentifierFinder(); BcDigestCalculatorProvider calculator = new BcDigestCalculatorProvider(); BcRSASignerInfoVerifierBuilder verifierBuilder = new BcRSASignerInfoVerifierBuilder(nameGen, sigAlgoFinder, hashAlgoFinder, calculator); SignerInformationVerifier verifier = verifierBuilder.build(holder);
Signature signature = Signature.getInstance(algorithm, BC); signature.initSign(privateKey); signature.update(docForSign.getBytes()); CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
@SuppressWarnings({"rawtypes", "unchecked"}) public <T2> T2 getEntity(Class<T2> t, Type gt, Annotation[] ann, MediaType mediaType) { if (entity != null) return (T2)entity; byte[] bytes = (byte[])data.getSignedContent().getContent(); MessageBodyReader reader = providers.getMessageBodyReader(t, gt, ann, mediaType); ByteArrayInputStream is = new ByteArrayInputStream(bytes); try { entity = reader.readFrom(t, gt, ann, mediaType, new MultivaluedMapImpl<String, String>(), is); } catch (Exception e) { throw new RuntimeException(e); } return (T2)entity; }
public void parse( InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { try { DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build(); CMSSignedDataParser parser = new CMSSignedDataParser(digestCalculatorProvider, new CloseShieldInputStream(stream)); try { CMSTypedStream content = parser.getSignedContent(); if (content == null) { throw new TikaException("cannot parse detached pkcs7 signature (no signed data to parse)"); } try (InputStream input = content.getContentStream()) { Parser delegate = context.get(Parser.class, EmptyParser.INSTANCE); delegate.parse(input, handler, metadata, context); } } finally { parser.close(); } } catch (OperatorCreationException e) { throw new TikaException("Unable to create DigestCalculatorProvider", e); } catch (CMSException e) { throw new TikaException("Unable to parse pkcs7 signed data", e); } }
private void appendCertInfo(StringBuilder extraInfo, KeyTransRecipientId ktRid, X509Certificate certificate, X509CertificateHolder materialCert) { BigInteger ridSerialNumber = ktRid.getSerialNumber(); if (ridSerialNumber != null) { String certSerial = "unknown"; BigInteger certSerialNumber = certificate.getSerialNumber(); if (certSerialNumber != null) { certSerial = certSerialNumber.toString(16); } extraInfo.append("serial-#: rid "); extraInfo.append(ridSerialNumber.toString(16)); extraInfo.append(" vs. cert "); extraInfo.append(certSerial); extraInfo.append(" issuer: rid \'"); extraInfo.append(ktRid.getIssuer()); extraInfo.append("\' vs. cert \'"); extraInfo.append(materialCert == null ? "null" : materialCert.getIssuer()); extraInfo.append("\' "); } }
public boolean verify(X509Certificate certificate) throws Exception { for (Object info : data.getSignerInfos().getSigners()) { SignerInformation signer = (SignerInformation)info; if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificate))) { return true; } } return false; } public boolean verify(PublicKey publicKey) throws Exception
throws IOException, CertificateProccessingException AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes(); if (unsignedAttributes == null) Attribute tsAttribute = signerInformation.getUnsignedAttributes() .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken); if (tsAttribute.getAttrValues() instanceof DERSet) new CMSSignedData(tsSeq.getEncoded("DER")));
/** * Base64 encoded pks bytes. * * @param base64 Base64 encoded string */ public PKCS7SignatureInput(final String base64) { try { byte[] bytes = Base64.decode(base64); this.data = new CMSSignedData(bytes); } catch (Exception e) { throw new RuntimeException(e); } }
public boolean verify(PublicKey publicKey) throws Exception { SMIMESigned signed = new SMIMESigned(body); SignerInformationStore signers = signed.getSignerInfos(); SignerInformation signer = (SignerInformation) signers.getSigners().iterator().next(); return (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(publicKey))); }