List of usage examples for org.bouncycastle.asn1 ASN1EncodableVector get
public ASN1Encodable get(int i)
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/*w w w . j av a 2s.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 w w w. j a v a2 s.c o 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 ww . j a v a 2 s . c o 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./*from w ww.jav a2 s.c om*/ * 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 ww . jav a 2 s . c om*/ } } } } 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;//from w w w. j a v a 2 s . com } 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./*from www . j a v a 2 s.co 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; }//from w ww. j a v a 2s . c o m } if (allAttributesCorrect) { validationResult.pass(SIGNED_ATTRS_CORRECT); } else { validationResult.warn(SIGNED_ATTRS_CORRECT); } return allAttributesCorrect; }
From source file:org.signserver.module.tsa.TimeStampSignerTest.java
License:Open Source License
private int testWithHash(final ASN1ObjectIdentifier hashAlgo) throws Exception { int reqid = random.nextInt(); TimeStampRequestGenerator timeStampRequestGenerator = new TimeStampRequestGenerator(); final TimeStampRequest timeStampRequest = timeStampRequestGenerator.generate(hashAlgo, new byte[getHashLength(hashAlgo)], BigInteger.valueOf(100)); byte[] requestBytes = timeStampRequest.getEncoded(); GenericSignRequest signRequest = new GenericSignRequest(reqid, requestBytes); final GenericSignResponse res = (GenericSignResponse) workerSession.process(WORKER1, signRequest, new RequestContext()); final CertificateFactory factory = CertificateFactory.getInstance("X.509"); final X509Certificate cert = (X509Certificate) factory .generateCertificate(new ByteArrayInputStream(Base64.decode(CERTSTRING.getBytes()))); TimeStampResponse timeStampResponse = null; try {/*from ww w . ja v a2 s . c o m*/ // check response timeStampResponse = new TimeStampResponse((byte[]) res.getProcessedData()); timeStampResponse.validate(timeStampRequest); if (timeStampResponse.getStatus() != PKIStatus.GRANTED) { // return early and don't attempt to get a token return timeStampResponse.getStatus(); } // check the hash value from the response TimeStampToken token = timeStampResponse.getTimeStampToken(); AlgorithmIdentifier algo = token.getTimeStampInfo().getHashAlgorithm(); assertEquals("Timestamp response is using incorrect hash algorithm", hashAlgo, algo.getAlgorithm()); Collection signerInfos = token.toCMSSignedData().getSignerInfos().getSigners(); // there should be one SignerInfo assertEquals("There should only be one signer in the timestamp response", 1, signerInfos.size()); for (Object o : signerInfos) { SignerInformation si = (SignerInformation) o; // test the response signature algorithm assertEquals("Timestamp used unexpected signature algorithm", TSPAlgorithms.SHA1.toString(), si.getDigestAlgOID()); assertEquals("Timestamp is signed with unexpected signature encryption algorithm", "1.2.840.113549.1.1.1", si.getEncryptionAlgOID()); final AttributeTable attrs = si.getSignedAttributes(); final ASN1EncodableVector scAttrs = attrs.getAll(PKCSObjectIdentifiers.id_aa_signingCertificate); assertEquals("Should contain a signingCertificate signed attribute", 1, scAttrs.size()); TestUtils.checkSigningCertificateAttribute(ASN1Sequence.getInstance(scAttrs.get(0)), cert); } } catch (TSPException e) { fail("Failed to verify response"); } catch (IOException e) { fail("Failed to verify response"); } final TimeStampToken token = timeStampResponse.getTimeStampToken(); try { token.validate(cert, "BC"); } catch (TSPException e) { fail("Failed to validate response token"); } return timeStampResponse.getStatus(); }
From source file:org.votingsystem.callable.MessageTimeStamper.java
License:Open Source License
public byte[] getDigestToken() { if (timeStampToken == null) return null; CMSSignedData tokenCMSSignedData = timeStampToken.toCMSSignedData(); Collection signers = tokenCMSSignedData.getSignerInfos().getSigners(); SignerInformation tsaSignerInfo = (SignerInformation) signers.iterator().next(); AttributeTable signedAttrTable = tsaSignerInfo.getSignedAttributes(); ASN1EncodableVector v = signedAttrTable.getAll(CMSAttributes.messageDigest); Attribute t = (Attribute) v.get(0); ASN1Set attrValues = t.getAttrValues(); DERObject validMessageDigest = attrValues.getObjectAt(0).getDERObject(); ASN1OctetString signedMessageDigest = (ASN1OctetString) validMessageDigest; byte[] digestToken = signedMessageDigest.getOctets(); //String digestTokenStr = new String(Base64.encode(digestToken)); //log.info(" digestTokenStr: " + digestTokenStr); return digestToken; }