List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector size
public int size()
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
@Override public byte[] getArchiveTimestampData(int index, Document originalDocument) throws IOException { ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream(); ContentInfo contentInfo = cmsSignedData.getContentInfo(); SignedData signedData = SignedData.getInstance(contentInfo.getContent()); /* The encapContentInfo should always be present according to the standard, but sometimes it's omitted */ // 5.4.1/*from w w w . j a v a 2 s.c o m*/ if (signedData.getEncapContentInfo() == null || signedData.getEncapContentInfo().getContent() == null) { /* Detached signatures have either no encapContentInfo in signedData, or it exists but has no eContent */ if (originalDocument != null) { toTimestamp.write(originalDocument.openStream()); } else { throw new RuntimeException("Signature is detached and no original data provided."); } } else { ContentInfo content = signedData.getEncapContentInfo(); DEROctetString octet = (DEROctetString) content.getContent(); ContentInfo info2 = new ContentInfo(new ASN1ObjectIdentifier("1.2.840.113549.1.7.1"), new BERConstructedOctetString(octet.getOctets())); toTimestamp.write(info2.getEncoded()); } if (signedData.getCertificates() != null) { DEROutputStream output = new DEROutputStream(toTimestamp); output.writeObject(signedData.getCertificates()); output.close(); } if (signedData.getCRLs() != null) { toTimestamp.write(signedData.getCRLs().getEncoded()); } if (signerInformation.getUnsignedAttributes() != null) { ASN1EncodableVector original = signerInformation.getUnsignedAttributes().toASN1EncodableVector(); List<Attribute> timeStampToRemove = getTimeStampToRemove(index); ASN1EncodableVector filtered = new ASN1EncodableVector(); for (int i = 0; i < original.size(); i++) { DEREncodable enc = original.get(i); if (!timeStampToRemove.contains(enc)) { filtered.add(original.get(i)); } } SignerInformation filteredInfo = SignerInformation.replaceUnsignedAttributes(signerInformation, new AttributeTable(filtered)); toTimestamp.write(filteredInfo.toASN1Structure().getEncoded()); } return toTimestamp.toByteArray(); }
From source file:eu.europa.ec.markt.dss.validation.cades.CAdESSignature.java
License:Open Source License
private List<Attribute> getTimeStampToRemove(int archiveTimeStampToKeep) { List<Attribute> ts = new ArrayList<Attribute>(); /*//from ww w. j a va 2 s .co m * We need to remove every ArchiveTimeStamp with index < index. Every timestamp is retrieved, then the list is * sorted */ if (signerInformation.getUnsignedAttributes() != null) { ASN1EncodableVector v = signerInformation.getUnsignedAttributes().getAll(id_aa_ets_archiveTimestampV2); for (int i = 0; i < v.size(); i++) { DEREncodable enc = v.get(i); ts.add((Attribute) enc); } Collections.sort(ts, new AttributeTimeStampComparator()); /* * TS will contain the list of TimeStamps we must remove the (index) first timestamp. The list is sorted * with timestaps descending. */ for (int i = 0; i < archiveTimeStampToKeep; i++) { ts.remove(0); } } return ts; }
From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java
License:Open Source License
private List<TimestampToken> getTimestampList(final ASN1ObjectIdentifier attrType, final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) { final List<TimestampToken> list = new ArrayList<TimestampToken>(); final AttributeTable attributes; if (attrType.equals(PKCSObjectIdentifiers.id_aa_ets_contentTimestamp)) { attributes = signerInformation.getSignedAttributes(); } else {// w w w . j a v a 2s . co m attributes = signerInformation.getUnsignedAttributes(); } if (attributes == null) { return list; } final ASN1EncodableVector archiveList = attributes.getAll(attrType); for (int i = 0; i < archiveList.size(); i++) { final Attribute attribute = (Attribute) archiveList.get(i); final ASN1Set attrValues = attribute.getAttrValues(); for (final ASN1Encodable value : attrValues.toArray()) { try { TimeStampToken token = new TimeStampToken( new CMSSignedData(value.toASN1Primitive().getEncoded(ASN1Encoding.DER))); final TimestampToken timestampToken = new TimestampToken(token, timestampType, certPool); timestampToken.setArchiveTimestampType(archiveTimestampType); list.add(timestampToken); } catch (Exception e) { throw new RuntimeException("Parsing error", e); } } } return list; }
From source file:eu.europa.esig.dss.cades.signature.CadesLevelBaselineLTATimestampExtractor.java
License:Open Source License
/** * The field unsignedAttrsHashIndex is a sequence of octet strings. Each one contains the hash value of one * instance of Attribute within unsignedAttrs field of the SignerInfo. A hash value for every instance of * Attribute, as present at the time when the corresponding archive time-stamp is requested, shall be included in * unsignedAttrsHashIndex. No other hash values shall be included in this field. * * We check that every hash attribute found in the timestamp token is found if the signerInformation. * * If there is more unsigned attributes in the signerInformation than present in the hash attributes list * (and there is at least the archiveTimestampAttributeV3), we don't report any error nor which attributes are * signed by the timestamp./* ww w .j a v a 2 s . c o m*/ * If there is some attributes that are not present or altered in the signerInformation, we just return some empty * sequence to make * sure that the timestamped data will not match. We do not report which attributes hash are present if any. * * If there is not attribute at all in the archive timestamp hash index, that would means we didn't check anything. * * @param signerInformation * @param timestampToken * @return */ @SuppressWarnings("unchecked") private ASN1Sequence getVerifiedUnsignedAttributesHashIndex(SignerInformation signerInformation, TimestampToken timestampToken) throws DSSException { final ASN1Sequence unsignedAttributesHashes = getUnsignedAttributesHashIndex(timestampToken); final List<DEROctetString> timestampUnsignedAttributesHashesList = new ArrayList<DEROctetString>(); if (unsignedAttributesHashes != null) { timestampUnsignedAttributesHashesList.addAll(Collections.list(unsignedAttributesHashes.getObjects())); } AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation); final ASN1EncodableVector asn1EncodableVector = unsignedAttributes.toASN1EncodableVector(); for (int i = 0; i < asn1EncodableVector.size(); i++) { final Attribute attribute = (Attribute) asn1EncodableVector.get(i); final DEROctetString derOctetStringDigest = getAttributeDerOctetStringHash(attribute); final ASN1ObjectIdentifier attrType = attribute.getAttrType(); if (timestampUnsignedAttributesHashesList.remove(derOctetStringDigest)) { // attribute present in signature and in timestamp LOG.debug("Attribute {} present in timestamp", attrType.getId()); } else { LOG.debug("Attribute {} not present in timestamp", attrType.getId()); } } if (!timestampUnsignedAttributesHashesList.isEmpty()) { LOG.error("{} attribute hash in Timestamp have not been found in document attributes: {}", timestampUnsignedAttributesHashesList.size(), timestampUnsignedAttributesHashesList); // return a empty DERSequence to screw up the hash return new DERSequence(); } // return the original DERSequence return unsignedAttributesHashes; }
From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java
License:Open Source License
private List<TimestampToken> createTimestamps(final ASN1ObjectIdentifier attrType, final TimestampType timestampType, final ArchiveTimestampType archiveTimestampType) { final List<TimestampToken> timestampTokenList = new ArrayList<TimestampToken>(); final AttributeTable attributes = attrType.equals(id_aa_ets_contentTimestamp) ? signerInformation.getSignedAttributes() : signerInformation.getUnsignedAttributes(); if (attributes != null) { final ASN1EncodableVector allAttributes = attributes.getAll(attrType); for (int ii = 0; ii < allAttributes.size(); ii++) { final Attribute attribute = (Attribute) allAttributes.get(ii); final ASN1Set attrValues = attribute.getAttrValues(); for (final ASN1Encodable value : attrValues.toArray()) { if (value instanceof DEROctetString) { LOG.warn("Illegal content for timestamp (OID : " + attrType + ") : OCTET STRING is not allowed !"); } else { try { byte[] encoded = value.toASN1Primitive().getEncoded(); final CMSSignedData signedData = new CMSSignedData(encoded); final TimeStampToken token = new TimeStampToken(signedData); final TimestampToken timestampToken = new TimestampToken(token, timestampType, certPool); timestampToken.setArchiveTimestampType(archiveTimestampType); timestampTokenList.add(timestampToken); } catch (Exception e) { throw new DSSException(e); }//from w w w.j a va 2 s . co m } } } } return timestampTokenList; }
From source file:mitm.common.security.asn1.ASN1Utils.java
License:Open Source License
public static void dump(AttributeTable attributeTable, StringBuilder sb) { if (attributeTable == null) { return;//w w w .ja v a 2s .c o m } ASN1EncodableVector vector = attributeTable.toASN1EncodableVector(); for (int i = 0; i < vector.size(); i++) { ASN1Encodable der = vector.get(i); sb.append(ASN1Dump.dumpAsString(der)); } }
From source file:mitm.common.security.asn1.DERUtils.java
License:Open Source License
/** * Bouncycastle DERSet sorts the entries in the set (required by DER encoding) but uses a slow * sort method. You can use this method to do a pre-sort using a faster method before creating * the DERSet.//w ww . j a v a 2 s. c o m * @param asn1Certificates * @return * @throws IOException */ public static ASN1EncodableVector sortASN1EncodableVector(ASN1EncodableVector asn1Certificates) throws IOException { ASN1EncodableVector sorted = new ASN1EncodableVector(); List<DEREntry> sortingList = new Vector<DEREntry>(asn1Certificates.size()); for (int i = 0; i < asn1Certificates.size(); i++) { DEREntry entry = new DEREntry(asn1Certificates.get(i)); sortingList.add(entry); } Collections.sort(sortingList); for (DEREntry entry : sortingList) { sorted.add(entry.derEncodable); } return sorted; }
From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectParser.java
License:BSD License
private boolean verifyOptionalSignedAttributes(SignerInformation signer) { //To loop over ASN1EncodableVector signedAttributes = signer.getSignedAttributes().toASN1EncodableVector(); boolean allAttributesCorrect = true; for (int i = 0; i < signedAttributes.size(); i++) { ASN1Encodable signedAttribute = signedAttributes.get(i); if (!isAllowedSignedAttribute((Attribute) signedAttribute)) { allAttributesCorrect = false; break; }/*w w w . jav a 2s .c o m*/ } if (allAttributesCorrect) { validationResult.pass(SIGNED_ATTRS_CORRECT); } else { validationResult.warn(SIGNED_ATTRS_CORRECT); } return allAttributesCorrect; }
From source file:org.cesecore.certificates.ca.X509CA.java
License:Open Source License
/** * Generate a CRL or a deltaCRL//from w w w . ja v a 2 s .com * * @param certs * list of revoked certificates * @param crlnumber * CRLNumber for this CRL * @param isDeltaCRL * true if we should generate a DeltaCRL * @param basecrlnumber * caseCRLNumber for a delta CRL, use 0 for full CRLs * @param certProfile * certificate profile for CRL Distribution point in the CRL, or null * @return CRL * @throws CryptoTokenOfflineException * @throws IllegalCryptoTokenException * @throws IOException * @throws SignatureException * @throws NoSuchProviderException * @throws InvalidKeyException * @throws CRLException * @throws NoSuchAlgorithmException */ private X509CRLHolder generateCRL(CryptoToken cryptoToken, Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL, int basecrlnumber) throws CryptoTokenOfflineException, IllegalCryptoTokenException, IOException, SignatureException, NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException { final String sigAlg = getCAInfo().getCAToken().getSignatureAlgorithm(); if (log.isDebugEnabled()) { log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", " + basecrlnumber); } // Make DNs final X509Certificate cacert = (X509Certificate) getCACertificate(); final X500Name issuer; if (cacert == null) { // This is an initial root CA, since no CA-certificate exists // (I don't think we can ever get here!!!) final X500NameStyle nameStyle; if (getUsePrintableStringSubjectDN()) { nameStyle = PrintableStringNameStyle.INSTANCE; } else { nameStyle = CeSecoreNameStyle.INSTANCE; } issuer = CertTools.stringToBcX500Name(getSubjectDN(), nameStyle, getUseLdapDNOrder()); } else { issuer = X500Name.getInstance(cacert.getSubjectX500Principal().getEncoded()); } final Date thisUpdate = new Date(); final Date nextUpdate = new Date(); nextUpdate.setTime(nextUpdate.getTime() + crlPeriod); final X509v2CRLBuilder crlgen = new X509v2CRLBuilder(issuer, thisUpdate); crlgen.setNextUpdate(nextUpdate); if (certs != null) { if (log.isDebugEnabled()) { log.debug("Adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final Iterator<RevokedCertInfo> it = certs.iterator(); while (it.hasNext()) { final RevokedCertInfo certinfo = (RevokedCertInfo) it.next(); crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(), certinfo.getReason()); } if (log.isDebugEnabled()) { log.debug("Finished adding " + certs.size() + " revoked certificates to CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } } // Authority key identifier if (getUseAuthorityKeyIdentifier() == true) { byte[] caSkid = (cacert != null ? CertTools.getSubjectKeyId(cacert) : null); if (caSkid != null) { // Use subject key id from CA certificate AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(caSkid); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } else { // Generate from SHA1 of public key ASN1InputStream asn1InputStream = new ASN1InputStream(new ByteArrayInputStream(cryptoToken .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN)) .getEncoded())); try { SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo( (ASN1Sequence) asn1InputStream.readObject()); AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki); crlgen.addExtension(Extension.authorityKeyIdentifier, getAuthorityKeyIdentifierCritical(), aki); } finally { asn1InputStream.close(); } } } // Authority Information Access final ASN1EncodableVector accessList = new ASN1EncodableVector(); if (getAuthorityInformationAccess() != null) { for (String url : getAuthorityInformationAccess()) { if (StringUtils.isNotEmpty(url)) { GeneralName accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } if (accessList.size() > 0) { AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess .getInstance(new DERSequence(accessList)); // "This CRL extension MUST NOT be marked critical." according to rfc4325 crlgen.addExtension(Extension.authorityInfoAccess, false, authorityInformationAccess); } // CRLNumber extension if (getUseCRLNumber() == true) { CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber)); crlgen.addExtension(Extension.cRLNumber, this.getCRLNumberCritical(), crlnum); } if (isDeltaCRL) { // DeltaCRLIndicator extension CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber)); crlgen.addExtension(Extension.deltaCRLIndicator, true, basecrlnum); } // CRL Distribution point URI and Freshest CRL DP if (getUseCrlDistributionPointOnCrl()) { String crldistpoint = getDefaultCRLDistPoint(); List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint); if (distpoints.size() > 0) { IssuingDistributionPoint idp = new IssuingDistributionPoint( distpoints.get(0).getDistributionPoint(), false, false, null, false, false); // According to the RFC, IDP must be a critical extension. // Nonetheless, at the moment, Mozilla is not able to correctly // handle the IDP extension and discards the CRL if it is critical. crlgen.addExtension(Extension.issuingDistributionPoint, getCrlDistributionPointOnCrlCritical(), idp); } if (!isDeltaCRL) { String crlFreshestDP = getCADefinedFreshestCRL(); List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP); if (freshestDistPoints.size() > 0) { CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints .toArray(new DistributionPoint[freshestDistPoints.size()])); // According to the RFC, the Freshest CRL extension on a // CRL must not be marked as critical. Therefore it is // hardcoded as not critical and is independent of // getCrlDistributionPointOnCrlCritical(). crlgen.addExtension(Extension.freshestCRL, false, ext); } } } final X509CRLHolder crl; if (log.isDebugEnabled()) { log.debug("Signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } final String alias = getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN); try { final ContentSigner signer = new BufferingContentSigner(new JcaContentSignerBuilder(sigAlg) .setProvider(cryptoToken.getSignProviderName()).build(cryptoToken.getPrivateKey(alias)), 20480); crl = crlgen.build(signer); } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } if (log.isDebugEnabled()) { log.debug("Finished signing CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } // Verify using the CA certificate before returning // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL // because something is wrong... final PublicKey verifyKey; if (cacert != null) { verifyKey = cacert.getPublicKey(); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA certificate."); } } else { verifyKey = cryptoToken.getPublicKey(alias); if (log.isTraceEnabled()) { log.trace("Got the verify key from the CA token."); } } try { final ContentVerifierProvider verifier = new JcaContentVerifierProviderBuilder().build(verifyKey); if (!crl.isSignatureValid(verifier)) { throw new SignatureException("Error verifying CRL to be returned."); } } catch (OperatorCreationException e) { // Very fatal error throw new RuntimeException("Can not create Jca content signer: ", e); } catch (CertException e) { throw new SignatureException(e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("Returning CRL. Free memory=" + Runtime.getRuntime().freeMemory()); } return crl; }
From source file:org.cesecore.certificates.certificate.certextensions.standard.AuthorityInformationAccess.java
License:Open Source License
@Override public ASN1Encodable getValue(final EndEntityInformation subject, final CA ca, final CertificateProfile certProfile, final PublicKey userPublicKey, final PublicKey caPublicKey, CertificateValidity val) throws CertificateExtensionException { final ASN1EncodableVector accessList = new ASN1EncodableVector(); GeneralName accessLocation;//from w w w. j a v a 2s .c o m String url; // caIssuers final List<String> caIssuers = certProfile.getCaIssuers(); if (caIssuers != null) { for (final Iterator<String> it = caIssuers.iterator(); it.hasNext();) { url = it.next(); if (StringUtils.isNotEmpty(url)) { accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_caIssuers, accessLocation)); } } } // ocsp url final X509CA x509ca = (X509CA) ca; url = certProfile.getOCSPServiceLocatorURI(); if (certProfile.getUseDefaultOCSPServiceLocator()) { url = x509ca.getDefaultOCSPServiceLocator(); } if (StringUtils.isNotEmpty(url)) { accessLocation = new GeneralName(GeneralName.uniformResourceIdentifier, new DERIA5String(url)); accessList.add(new AccessDescription(AccessDescription.id_ad_ocsp, accessLocation)); } org.bouncycastle.asn1.x509.AuthorityInformationAccess ret = null; if (accessList.size() > 0) { ret = org.bouncycastle.asn1.x509.AuthorityInformationAccess.getInstance(new DERSequence(accessList)); } if (ret == null) { log.error("AuthorityInformationAccess is used, but nor caIssuers not Ocsp url are defined!"); } return ret; }