public static Date getSignatureTime(SignerInformation signer) { AttributeTable atab = signer.getSignedAttributes(); Date result = null; if (atab != null) { Attribute attr = atab.get(CMSAttributes.signingTime); if (attr != null) { Time t = Time.getInstance(attr.getAttrValues().getObjectAt(0) .toASN1Primitive()); result = t.getDate(); } } return result; }
/** * return an Attribute object from the given object. * * @param o the object we want converted. * @exception IllegalArgumentException if the object cannot be converted. */ public static SMIMECapabilities getInstance( Object o) { if (o == null || o instanceof SMIMECapabilities) { return (SMIMECapabilities)o; } if (o instanceof ASN1Sequence) { return new SMIMECapabilities((ASN1Sequence)o); } if (o instanceof Attribute) { return new SMIMECapabilities( (ASN1Sequence)(((Attribute)o).getAttrValues().getObjectAt(0))); } throw new IllegalArgumentException("unknown object in factory: " + o.getClass().getName()); }
private static ASN1Set buildSignedAttributes(byte[] hash, Date dateTime, X509Certificate cert) throws Exception { ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new Attribute(CMSAttributes.contentType, new DERSet(PKCSObjectIdentifiers.data))); if (dateTime != null) v.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(dateTime)))); v.add(new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(hash)))); // CADES support section ASN1EncodableVector aaV2 = new ASN1EncodableVector(); AlgorithmIdentifier algoId = new AlgorithmIdentifier(new ASN1ObjectIdentifier(CMSSignedDataGenerator.DIGEST_SHA256), null); aaV2.add(algoId); byte[] dig = SignUtils.calculateHASH(CMSSignedDataGenerator.DIGEST_SHA256, cert.getEncoded()); aaV2.add(new DEROctetString(dig)); Attribute cades = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(new DERSequence(new DERSequence(new DERSequence(aaV2))))); v.add(cades); ASN1Set signedAttributes = new DERSet(v); return signedAttributes; }
@Override public Attribute getValue() throws SignerException { try { logger.info(cadesMessagesBundle.getString("info.tsa.connecting")); if (timeStampGenerator != null) { //Inicializa os valores para o timestmap timeStampGenerator.initialize(content, privateKey, certificates, hash); //Obtem o carimbo de tempo atraves do servidor TSA byte[] response = timeStampGenerator.generateTimeStamp(); //Valida o carimbo de tempo gerado timeStampGenerator.validateTimeStamp(content, response, hash); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(ASN1Primitive.fromByteArray(response))); } else { throw new SignerException(cadesMessagesBundle.getString("error.tsa.not.found")); } } catch (SecurityException | IOException ex) { } throw new UnsupportedOperationException(cadesMessagesBundle.getString("error.not.supported",getClass().getName())); }
@Override public Attribute getValue() { try { X509Certificate cert = (X509Certificate) certificates[0]; Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_1); byte[] hash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(cert.getSubjectDN().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serial = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serial); ESSCertID essCertId = new ESSCertID(hash, issuerSerial); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)}))); } catch (CertificateEncodingException ex) { throw new SignerException(ex.getMessage()); } }
@Override public Attribute getValue() throws SignerException { try { logger.info(cadesMessagesBundle.getString("info.tsa.connecting")); if (timeStampGenerator != null) { //Inicializa os valores para o timestmap timeStampGenerator.initialize(content, privateKey, certificates, hash); //Obtem o carimbo de tempo atraves do servidor TSA byte[] response = timeStampGenerator.generateTimeStamp(); //Valida o carimbo de tempo gerado timeStampGenerator.validateTimeStamp(content, response, hash); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(ASN1Primitive.fromByteArray(response))); } else { throw new SignerException(cadesMessagesBundle.getString("error.tsa.not.found")); } } catch (SecurityException | IOException ex) { throw new SignerException(ex.getMessage()); } }
@Override public Attribute getValue() throws SignerException { try { X509Certificate cert = (X509Certificate) certificates[0]; X509Certificate issuerCert = (X509Certificate) certificates[1]; Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_256); byte[] certHash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber); AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256);// SHA-256 ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(algId, certHash, issuerSerial); // return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(essCertIDv2))); return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence( new ASN1Encodable[] { new DERSequence(essCertIDv2) }))); } catch (CertificateEncodingException ex) { throw new SignerException(ex.getMessage()); } }
private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException { Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners(); // get signature of first signer (should be the only one) SignerInformation si = signerInfos.iterator().next(); byte[] signature = si.getSignature(); // send request to TSA byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1); // create new SignerInformation with TS attribute Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, new DERSet(ASN1Primitive.fromByteArray(token))); ASN1EncodableVector timestampVector = new ASN1EncodableVector(); timestampVector.add(tokenAttr); AttributeTable at = new AttributeTable(timestampVector); si = SignerInformation.replaceUnsignedAttributes(si, at); signerInfos.clear(); signerInfos.add(si); SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos); // create new signed data CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore); return newSignedData; }
/** * We are extending CMS Signature * * @param signer * information about signer * @return information about SignerInformation */ private SignerInformation signTimeStamp(SignerInformation signer) throws IOException, TSPException { AttributeTable unsignedAttributes = signer.getUnsignedAttributes(); ASN1EncodableVector vector = new ASN1EncodableVector(); if (unsignedAttributes != null) { vector = unsignedAttributes.toASN1EncodableVector(); } byte[] token = tsaClient.getTimeStampToken(signer.getSignature()); ASN1ObjectIdentifier oid = PKCSObjectIdentifiers.id_aa_signatureTimeStampToken; ASN1Encodable signatureTimeStamp = new Attribute(oid, new DERSet(ASN1Primitive.fromByteArray(token))); vector.add(signatureTimeStamp); Attributes signedAttributes = new Attributes(vector); SignerInformation newSigner = SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(signedAttributes)); return newSigner; }
private boolean verifySignedReferencesToSigningCertificate() { final IssuerSerial signingTokenIssuerSerial = DSSASN1Utils.getIssuerSerial(signingCertificateValidity.getCertificateToken()); final BigInteger signingTokenSerialNumber = signingTokenIssuerSerial.getSerial().getValue(); final GeneralNames signingTokenIssuerName = signingTokenIssuerSerial.getIssuer(); final AttributeTable signedAttributes = CMSUtils.getSignedAttributes(signerInformation); final Attribute signingCertificateAttributeV1 = signedAttributes.get(id_aa_signingCertificate); if (signingCertificateAttributeV1 != null) { signingCertificateValidity.setAttributePresent(true); verifySigningCertificateV1(signingTokenSerialNumber, signingTokenIssuerName, signingCertificateAttributeV1); return true; } final Attribute signingCertificateAttributeV2 = signedAttributes.get(id_aa_signingCertificateV2); if (signingCertificateAttributeV2 != null) { signingCertificateValidity.setAttributePresent(true); verifySigningCertificateV2(signingTokenSerialNumber, signingTokenIssuerName, signingCertificateAttributeV2); return true; } return false; }
@Override public String getContentHints() { final Attribute contentHintAttribute = getSignedAttribute(PKCSObjectIdentifiers.id_aa_contentHint); if (contentHintAttribute == null) { return null; } final ASN1Encodable asn1Encodable = contentHintAttribute.getAttrValues().getObjectAt(0); final ContentHints contentHints = ContentHints.getInstance(asn1Encodable); String contentHint = null; if (contentHints != null) { // content-type is mandatory contentHint = contentHints.getContentType().toString(); // content-description is optional if (contentHints.getContentDescription() != null) { contentHint += " [" + contentHints.getContentDescription().toString() + "]"; } } return contentHint; }
@Override public byte[] getTimestampX1Data(final TimestampToken timestampToken, String canonicalizationMethod) { try (ByteArrayOutputStream data = new ByteArrayOutputStream()) { data.write(signerInformation.getSignature()); // We don't include the outer SEQUENCE, only the attrType and // attrValues as stated by the TS §6.3.5, NOTE 2 final Attribute attribute = getUnsignedAttribute(id_aa_signatureTimeStampToken); if (attribute != null) { data.write(DSSASN1Utils.getDEREncoded(attribute.getAttrType())); data.write(DSSASN1Utils.getDEREncoded(attribute.getAttrValues())); } // Those are common to Type 1 and Type 2 data.write(getTimestampX2Data(timestampToken, null)); return data.toByteArray(); } catch (IOException e) { throw new DSSException(e); } }
@Override public byte[] getTimestampX2Data(final TimestampToken timestampToken, String canonicalizationMethod) { try (ByteArrayOutputStream data = new ByteArrayOutputStream()) { // Those are common to Type 1 and Type 2 final Attribute certAttribute = getUnsignedAttribute(id_aa_ets_certificateRefs); final Attribute revAttribute = getUnsignedAttribute(PKCSObjectIdentifiers.id_aa_ets_revocationRefs); if (certAttribute != null) { data.write(DSSASN1Utils.getDEREncoded(certAttribute.getAttrType())); data.write(DSSASN1Utils.getDEREncoded(certAttribute.getAttrValues())); } if (revAttribute != null) { data.write(DSSASN1Utils.getDEREncoded(revAttribute.getAttrType())); data.write(DSSASN1Utils.getDEREncoded(revAttribute.getAttrValues())); } return data.toByteArray(); } catch (IOException e) { throw new DSSException(e); } }
/** * Remove any archive-timestamp-v2/3 attribute added after the * timestampToken */ private ASN1Sequence filterUnauthenticatedAttributes(ASN1Set unauthenticatedAttributes, TimestampToken timestampToken) { ASN1EncodableVector result = new ASN1EncodableVector(); for (int ii = 0; ii < unauthenticatedAttributes.size(); ii++) { final Attribute attribute = Attribute.getInstance(unauthenticatedAttributes.getObjectAt(ii)); final ASN1ObjectIdentifier attrType = attribute.getAttrType(); if (id_aa_ets_archiveTimestampV2.equals(attrType) || id_aa_ets_archiveTimestampV3.equals(attrType)) { try { TimeStampToken token = new TimeStampToken( new CMSSignedData(DSSASN1Utils.getDEREncoded(attribute.getAttrValues().getObjectAt(0).toASN1Primitive()))); if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) { continue; } } catch (Exception e) { throw new DSSException(e); } } result.add(unauthenticatedAttributes.getObjectAt(ii)); } return new DERSequence(result); }
public byte[] getArchiveTimestampDataV3(SignerInformation signerInformation, Attribute atsHashIndexAttribute, byte[] originalDocumentDigest) throws DSSException { final CMSSignedData cmsSignedData = cadesSignature.getCmsSignedData(); final byte[] encodedContentType = getEncodedContentType(cmsSignedData); // OID final byte[] signedDataDigest = originalDocumentDigest; final byte[] encodedFields = getSignedFields(signerInformation); final byte[] encodedAtsHashIndex = DSSASN1Utils.getDEREncoded(atsHashIndexAttribute.getAttrValues().getObjectAt(0)); /** * The input for the archive-time-stamp-v3’s message imprint computation shall be the concatenation (in the * order shown by the list below) of the signed data hash (see bullet 2 below) and certain fields in their * binary encoded * form without any modification and including the tag, length and value octets: */ final byte[] dataToTimestamp = DSSUtils.concatenate(encodedContentType, signedDataDigest, encodedFields, encodedAtsHashIndex); if (LOG.isDebugEnabled()) { LOG.debug("eContentType={}", Utils.toHex(encodedContentType)); LOG.debug("signedDataDigest={}", Utils.toHex(signedDataDigest)); LOG.debug("encodedFields=see above"); LOG.debug("encodedAtsHashIndex={}", Utils.toHex(encodedAtsHashIndex)); // LOG.debug("Archive Timestamp Data v3 is: {}", Hex.encodeHexString(dataToTimestamp)); } return dataToTimestamp; }
private void addSigningTimeAttribute(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) { if (!padesUsage) { /* * In PAdES, we don't include the signing time : ETSI TS 102 778-3 V1.2.1 (2010-07): 4.5.3 signing-time * Attribute */ final Date signingDate = parameters.bLevel().getSigningDate(); if (signingDate != null) { final DERSet attrValues = new DERSet(new Time(signingDate)); final Attribute attribute = new Attribute(pkcs_9_at_signingTime, attrValues); signedAttributes.add(attribute); } } }
/** * ETSI TS 101 733 V2.2.1 (2013-04) * * 5.11.1 commitment-type-indication Attribute * There may be situations where a signer wants to explicitly indicate to a verifier that by signing the data, it * illustrates a * type of commitment on behalf of the signer. The commitment-type-indication attribute conveys such * information. * * @param parameters * @param signedAttributes */ private void addCommitmentType(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) { // TODO (19/08/2014): commitmentTypeQualifier is not implemented final BLevelParameters bLevelParameters = parameters.bLevel(); final List<String> commitmentTypeIndications = bLevelParameters.getCommitmentTypeIndications(); if (Utils.isCollectionNotEmpty(commitmentTypeIndications)) { final int size = commitmentTypeIndications.size(); ASN1Encodable[] asn1Encodables = new ASN1Encodable[size]; for (int ii = 0; ii < size; ii++) { final String commitmentTypeId = commitmentTypeIndications.get(ii); final ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(commitmentTypeId); // final CommitmentTypeIndication commitmentTypeIndication = new // CommitmentTypeIndication(objectIdentifier); // final ASN1Primitive asn1Primitive = commitmentTypeIndication.toASN1Primitive(); asn1Encodables[ii] = new DERSequence(objectIdentifier); } final DERSet attrValues = new DERSet(asn1Encodables); final Attribute attribute = new Attribute(id_aa_ets_commitmentType, attrValues); signedAttributes.add(attribute); } }
private void extractCertificateFromUnsignedAttribute(List<CertificateToken> encapsulatedCerts, Attribute attribute) { if (attribute != null) { final ASN1Sequence seq = (ASN1Sequence) attribute.getAttrValues().getObjectAt(0); for (int ii = 0; ii < seq.size(); ii++) { try { final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii)); final CertificateToken certToken = addCertificate(DSSUtils.loadCertificate(cs.getEncoded())); if (!encapsulatedCerts.contains(certToken)) { encapsulatedCerts.add(certToken); } } catch (Exception e) { LOG.warn("Unable to parse encapsulated certificate : " + e.getMessage()); } } } }
/** * Retorna a data da criacao da assinatura * NAO EH CARIMBO DE TEMPO * @return Date * @see Date */ public Date getDataAssinatura(){ try { getCertificadoAssinante(); } catch (Exception e) { return null; } AttributeTable attr = signerInfo.getSignedAttributes(); if (attr != null) { Attribute t = attr.get(CMSAttributes.signingTime); if (t != null) { Time time = Time.getInstance( t.getAttrValues().getObjectAt(0).getDERObject()); return time.getDate(); } } return null; }
private ASN1Primitive getSingleValuedSignedAttribute( ASN1ObjectIdentifier attrOID, String printableName) throws CMSException { AttributeTable unsignedAttrTable = this.getUnsignedAttributes(); if (unsignedAttrTable != null && unsignedAttrTable.getAll(attrOID).size() > 0) { throw new CMSException("The " + printableName + " attribute MUST NOT be an unsigned attribute"); } AttributeTable signedAttrTable = this.getSignedAttributes(); if (signedAttrTable == null) { return null; } ASN1EncodableVector v = signedAttrTable.getAll(attrOID); switch (v.size()) { case 0: return null; case 1: { Attribute t = (Attribute)v.get(0); ASN1Set attrValues = t.getAttrValues(); if (attrValues.size() != 1) { throw new CMSException("A " + printableName + " attribute MUST have a single attribute value"); } return attrValues.getObjectAt(0).toASN1Primitive(); } default: throw new CMSException("The SignedAttributes in a signerInfo MUST NOT include multiple instances of the " + printableName + " attribute"); } }
/** * Return a signer information object with passed in SignerInformationStore representing counter * signatures attached as an unsigned attribute. * * @param signerInformation the signerInfo to be used as the basis. * @param counterSigners signer info objects carrying counter signature. * @return a copy of the original SignerInformationObject with the changed attributes. */ public static SignerInformation addCounterSigners( SignerInformation signerInformation, SignerInformationStore counterSigners) { // TODO Perform checks from RFC 3852 11.4 SignerInfo sInfo = signerInformation.info; AttributeTable unsignedAttr = signerInformation.getUnsignedAttributes(); ASN1EncodableVector v; if (unsignedAttr != null) { v = unsignedAttr.toASN1EncodableVector(); } else { v = new ASN1EncodableVector(); } ASN1EncodableVector sigs = new ASN1EncodableVector(); for (Iterator it = counterSigners.getSigners().iterator(); it.hasNext();) { sigs.add(((SignerInformation)it.next()).toASN1Structure()); } v.add(new Attribute(CMSAttributes.counterSignature, new DERSet(sigs))); return new SignerInformation( new SignerInfo(sInfo.getSID(), sInfo.getDigestAlgorithm(), sInfo.getAuthenticatedAttributes(), sInfo.getDigestEncryptionAlgorithm(), sInfo.getEncryptedDigest(), new DERSet(v)), signerInformation.contentType, signerInformation.content, null); }
@Override public Attribute getValue() throws SignerException { try { int chainSize = certificates.length -1; OtherCertID[] arrayOtherCertID = new OtherCertID[chainSize]; for (int i = 1; i <= chainSize; i++ ){ X509Certificate issuerCert = null; X509Certificate cert = (X509Certificate) certificates[i]; if (i < chainSize){ issuerCert = (X509Certificate) certificates[i+1]; }else{ // raiz issuerCert = (X509Certificate) certificates[i]; } Digest digest = DigestFactory.getInstance().factoryDefault(); digest.setAlgorithm(DigestAlgorithmEnum.SHA_256); byte[] certHash = digest.digest(cert.getEncoded()); X500Name dirName = new X500Name(issuerCert.getSubjectX500Principal().getName()); GeneralName name = new GeneralName(dirName); GeneralNames issuer = new GeneralNames(name); ASN1Integer serialNumber = new ASN1Integer(cert.getSerialNumber()); IssuerSerial issuerSerial = new IssuerSerial(issuer, serialNumber); AlgorithmIdentifier algId = new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256); OtherCertID otherCertID = new OtherCertID(algId, certHash, issuerSerial); arrayOtherCertID[i -1] = otherCertID; } return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new ASN1Encodable[] { new DERSequence(arrayOtherCertID) })); } catch (CertificateEncodingException e) { throw new SignerException(e.getMessage()); } }
/** * org.bouncycastle.asn1.ASN1ObjectIdentifier sigPolicyId * org.bouncycastle.asn1.esf.OtherHashAlgAndValue sigPolicyHash * List<org.bouncycastle.asn1.esf.SigPolicyQualifierInfo> sigPolicyQualifierInfos */ @Override public Attribute getValue() { //Atributo 1 ASN1ObjectIdentifier sigPolicyId = new ASN1ObjectIdentifier(signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()); //Atributo 2 OtherHashAlgAndValue sigPolicyHash = new OtherHashAlgAndValue(new AlgorithmIdentifier( new ASN1ObjectIdentifier(signaturePolicy.getSignPolicyHashAlg().getAlgorithm().getValue())), signaturePolicy.getSignPolicyHash().getDerOctetString()); //Atributo 3 List<SigPolicyQualifierInfo> sigPolicyQualifierInfos = new ArrayList<SigPolicyQualifierInfo>(); ASN1ObjectIdentifier sigPolicyQualifierId = new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.5.1"); DERIA5String sigQualifier = new DERIA5String(signaturePolicy.getSignPolicyURI()); SigPolicyQualifierInfo bcSigPolicyQualifierInfo = new SigPolicyQualifierInfo(sigPolicyQualifierId, sigQualifier); sigPolicyQualifierInfos.add(bcSigPolicyQualifierInfo); SigPolicyQualifiers sigPolicyQualifiers = new SigPolicyQualifiers(sigPolicyQualifierInfos.toArray(new SigPolicyQualifierInfo[]{})); SignaturePolicyId signaturePolicyId = new SignaturePolicyId(sigPolicyId, sigPolicyHash, sigPolicyQualifiers); return new Attribute(new ASN1ObjectIdentifier(oid), new DERSet(signaturePolicyId)); }
@Override public Attribute getValue() { try { if (this.hash == null){ java.security.MessageDigest md = java.security.MessageDigest.getInstance(signaturePolicy.getSignPolicyHashAlg().getAlgorithm().getValue()); this.hash = md.digest(content); } return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DEROctetString(this.hash))); } catch (NoSuchAlgorithmException ex) { logger.info(ex.getMessage()); return null; } }
/** * validade a timestampo on signature * @param attributeTimeStamp * @param varSignature * @return */ private Timestamp validateTimestamp(Attribute attributeTimeStamp, byte[] varSignature){ try { TimeStampOperator timeStampOperator = new TimeStampOperator(); byte [] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded(); TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp)); Timestamp timeStampSigner = new Timestamp(timeStampToken); timeStampOperator.validate(varSignature,varTimeStamp , null); return timeStampSigner; } catch (CertificateCoreException | IOException | TSPException | CMSException e) { throw new SignerException(e); } }
/** * <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest"> * Create pkcs7 signature from file digest * </a> * <p> * The OP's <code>sign</code> method after fixing some errors. The * OP's original method is {@link #signBySnox(InputStream)}. The * errors were * </p> * <ul> * <li>multiple attempts at reading the {@link InputStream} parameter; * <li>convoluted creation of final CMS container. * </ul> * <p> * Additionally this method uses SHA256 instead of SHA-1. * </p> */ public byte[] signWithSeparatedHashing(InputStream content) throws IOException { try { // Digest generation step MessageDigest md = MessageDigest.getInstance("SHA256", "BC"); byte[] digest = md.digest(IOUtils.toByteArray(content)); // Separate signature container creation step List<Certificate> certList = Arrays.asList(chain); JcaCertStore certs = new JcaCertStore(certList); CMSSignedDataGenerator gen = new CMSSignedDataGenerator(); Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(digest))); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(attr); SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()) .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v))); AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream(chain[0].getEncoded()); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); gen.addSignerInfoGenerator(builder.build( new BcRSAContentSignerBuilder(sha256withRSA, new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA)) .build(PrivateKeyFactory.createKey(pk.getEncoded())), new JcaX509CertificateHolder(cert))); gen.addCertificates(certs); CMSSignedData s = gen.generate(new CMSAbsentContent(), false); return s.getEncoded(); } catch (Exception e) { e.printStackTrace(); throw new IOException(e); } }
private Attribute createContentType() { // // final DEREncodableVector desSeq = new DEREncodableVector(); // // desSeq.add(new DERObjectIdentifier(ID_CONTENT_TYPE)); final DEREncodableVector setEV = new DEREncodableVector(); setEV.add(new DERObjectIdentifier(ID_PKCS7_DATA)); DERSet set = new DERSet(setEV); // // desSeq.add(set); // // DERSequence seq = new DERSequence(desSeq); Attribute seq1 = new Attribute( new DERObjectIdentifier(ID_CONTENT_TYPE), set); return seq1; }
private Attribute createMessageDigest(byte[] origHash) { final DEREncodableVector setEV = new DEREncodableVector(); setEV.add(new DEROctetString(origHash)); DERSet set = new DERSet(setEV); Attribute seq1 = new Attribute(new DERObjectIdentifier( ID_MESSAGE_DIGEST), set); return seq1; }
private Attribute createSigningTime(Date now) { final DEREncodableVector setEV = new DEREncodableVector(); setEV.add(new DERUTCTime(now)); DERSet set = new DERSet(setEV); Attribute seq1 = new Attribute( new DERObjectIdentifier(ID_SIGNING_TIME), set); return seq1; }