Java Code Examples for org.bouncycastle.asn1.ASN1Set

The following examples show how to use org.bouncycastle.asn1.ASN1Set. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: localization_nifi   Author: wangrenlei   File: CertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #2
Source Project: Websocket-Smart-Card-Signer   Author: damianofalcioni   File: CMSSignedDataWrapper.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #3
Source Project: nifi-registry   Author: apache   File: CertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #4
Source Project: signer   Author: demoiselle   File: CAdESTimeStampSigner.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
private Timestamp checkTimeStamp(byte[] timeStamp, byte[] content,  byte[] hash){
	try {
		Security.addProvider(new BouncyCastleProvider());
		ais = new ASN1InputStream(new ByteArrayInputStream(timeStamp));
	    ASN1Sequence seq=(ASN1Sequence)ais.readObject();
        Attribute attributeTimeStamp = new Attribute((ASN1ObjectIdentifier)seq.getObjectAt(0), (ASN1Set)seq.getObjectAt(1));
        byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
        TimeStampOperator timeStampOperator = new TimeStampOperator();
        if (content != null){
        	timeStampOperator.validate(content, varTimeStamp,null);
        }else{
        	timeStampOperator.validate(null, varTimeStamp,hash);
        }			
		TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
		Timestamp timeStampSigner = new Timestamp(timeStampToken);
		return timeStampSigner;
	} catch (CertificateCoreException | IOException | TSPException
			| CMSException e) {
		throw new SignerException(e);
	}

}
 
Example #5
Source Project: android-key-attestation   Author: google   File: AttestationApplicationId.java    License: Apache License 2.0 6 votes vote down vote up
private AttestationApplicationId(DEROctetString attestationApplicationId) throws IOException {
  ASN1Sequence attestationApplicationIdSequence =
      (ASN1Sequence) ASN1Sequence.fromByteArray(attestationApplicationId.getOctets());
  ASN1Set attestationPackageInfos =
      (ASN1Set)
          attestationApplicationIdSequence.getObjectAt(
              ATTESTATION_APPLICATION_ID_PACKAGE_INFOS_INDEX);
  this.packageInfos = new ArrayList<>();
  for (ASN1Encodable packageInfo : attestationPackageInfos) {
    this.packageInfos.add(new AttestationPackageInfo((ASN1Sequence) packageInfo));
  }

  ASN1Set digests =
      (ASN1Set)
          attestationApplicationIdSequence.getObjectAt(
              ATTESTATION_APPLICATION_ID_SIGNATURE_DIGESTS_INDEX);
  this.signatureDigests = new ArrayList<>();
  for (ASN1Encodable digest : digests) {
    this.signatureDigests.add(((ASN1OctetString) digest).getOctets());
  }
}
 
Example #6
Source Project: dss   Author: esig   File: CAdESTimestampDataBuilder.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] getCertificateDataBytes(final SignedData signedData) throws IOException {
	byte[] certificatesBytes = null;
	
	final ASN1Set certificates = signedData.getCertificates();
	if (certificates != null) {
		/*
		 * In order to calculate correct message imprint it is important
		 * to use the correct encoding.
		 */
		if (certificates instanceof BERSet) {
			certificatesBytes = new BERTaggedObject(false, 0, new BERSequence(certificates.toArray())).getEncoded();
		} else {
			certificatesBytes = new DERTaggedObject(false, 0, new DERSequence(certificates.toArray())).getEncoded();
		}
		
		if (LOG.isTraceEnabled()) {
			LOG.trace("Certificates: {}", DSSUtils.toHex(certificatesBytes));
		}
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("Certificates are not present in the SignedData.");
	}
	return certificatesBytes;
}
 
Example #7
Source Project: dss   Author: esig   File: CAdESTimestampDataBuilder.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private byte[] getCRLDataBytes(final SignedData signedData) throws IOException {
	byte[] crlBytes = null;
	
	final ASN1Set crLs = signedData.getCRLs();
	if (crLs != null) {
		
		if (signedData.getCRLs() instanceof BERSet) {
			crlBytes = new BERTaggedObject(false, 1, new BERSequence(crLs.toArray())).getEncoded();
		} else {
			crlBytes = new DERTaggedObject(false, 1, new DERSequence(crLs.toArray())).getEncoded();
		}
		if (LOG.isTraceEnabled()) {
			LOG.trace("CRLs: {}", DSSUtils.toHex(crlBytes));
		}
	}
	if (LOG.isDebugEnabled()) {
		LOG.debug("CRLs are not present in the SignedData.");
	}
	return crlBytes;
}
 
Example #8
Source Project: dss   Author: esig   File: CAdESTimestampDataBuilder.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 = DSSASN1Utils.getTimeStampToken(attribute);
				if (!token.getTimeStampInfo().getGenTime().before(timestampToken.getGenerationTime())) {
					continue;
				}
			} catch (Exception e) {
				throw new DSSException(e);
			}
		}
		result.add(unauthenticatedAttributes.getObjectAt(ii));
	}
	return new DERSequence(result);
}
 
Example #9
Source Project: dss   Author: esig   File: CAdESSignature.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private SignerAttribute getSignerAttributeV1() {
	final Attribute id_aa_ets_signerAttr = getSignedAttribute(PKCSObjectIdentifiers.id_aa_ets_signerAttr);
	if (id_aa_ets_signerAttr != null) {
		final ASN1Set attrValues = id_aa_ets_signerAttr.getAttrValues();
		final ASN1Encodable attrValue = attrValues.getObjectAt(0);
		try {
			return SignerAttribute.getInstance(attrValue);
		} catch (Exception e) {
			String warningMessage = "Unable to parse signerAttr - [{}]. Reason : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage(), e);
			} else {
				LOG.warn(warningMessage, Utils.toBase64(DSSASN1Utils.getDEREncoded(attrValue)), e.getMessage());
			}
		}
	}
	return null;
}
 
Example #10
/**
 * The field crlsHashIndex is a sequence of octet strings. Each one contains the
 * hash value of one instance of RevocationInfoChoice within crls field of the
 * root SignedData. A hash value for every instance of RevocationInfoChoice, as
 * present at the time when the corresponding archive time-stamp is requested,
 * shall be included in crlsHashIndex. No other hash values shall be included in
 * this field.
 *
 * @return
 * @throws eu.europa.esig.dss.model.DSSException
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getCRLsHashIndex() {

	final ASN1EncodableVector crlsHashIndex = new ASN1EncodableVector();

	final SignedData signedData = SignedData.getInstance(cmsSignedData.toASN1Structure().getContent());
	final ASN1Set signedDataCRLs = signedData.getCRLs();
	if (signedDataCRLs != null) {
		final Enumeration<ASN1Encodable> crLs = signedDataCRLs.getObjects();
		if (crLs != null) {
			while (crLs.hasMoreElements()) {
				final ASN1Encodable asn1Encodable = crLs.nextElement();
				digestAndAddToList(crlsHashIndex, DSSASN1Utils.getDEREncoded(asn1Encodable));
			}
		}
	}

	return new DERSequence(crlsHashIndex);
}
 
Example #11
Source Project: dss   Author: esig   File: AbstractRequirementChecks.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
@BeforeEach
public void init() throws Exception {
	DSSDocument signedDocument = getSignedDocument();

	ASN1InputStream asn1sInput = new ASN1InputStream(signedDocument.openStream());
	ASN1Sequence asn1Seq = (ASN1Sequence) asn1sInput.readObject();
	assertEquals(2, asn1Seq.size());
	ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1Seq.getObjectAt(0));
	assertEquals(PKCSObjectIdentifiers.signedData, oid);

	ASN1TaggedObject taggedObj = ASN1TaggedObject.getInstance(asn1Seq.getObjectAt(1));
	signedData = SignedData.getInstance(taggedObj.getObject());

	ASN1Set signerInfosAsn1 = signedData.getSignerInfos();
	assertEquals(1, signerInfosAsn1.size());

	signerInfo = SignerInfo.getInstance(ASN1Sequence.getInstance(signerInfosAsn1.getObjectAt(0)));

	Utils.closeQuietly(asn1sInput);
}
 
Example #12
Source Project: dss   Author: esig   File: CMSOCSPSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectRevocationRefs(AttributeTable unsignedAttributes, ASN1ObjectIdentifier revocationReferencesAttribute, RevocationRefOrigin origin) {
	final Attribute attribute = unsignedAttributes.get(revocationReferencesAttribute);
	if (attribute == null) {
		return;
	}
	final ASN1Set attrValues = attribute.getAttrValues();
	if (attrValues.size() <= 0) {
		return;
	}

	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final ASN1Sequence completeRevocationRefs = (ASN1Sequence) attrValue;
	for (int i = 0; i < completeRevocationRefs.size(); i++) {

		final CrlOcspRef otherCertId = CrlOcspRef.getInstance(completeRevocationRefs.getObjectAt(i));
		final OcspListID ocspListID = otherCertId.getOcspids();
		if (ocspListID != null) {
			for (final OcspResponsesID ocspResponsesID : ocspListID.getOcspResponses()) {
				final OCSPRef ocspRef = new OCSPRef(ocspResponsesID);
				addRevocationReference(ocspRef, origin);
			}
		}
	}
}
 
Example #13
Source Project: dss   Author: esig   File: CMSCertificateSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV1(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificate signingCertificate = SigningCertificate.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDs(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificate attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificate attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example #14
Source Project: dss   Author: esig   File: CMSCertificateSource.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractSigningCertificateV2(Attribute attribute) {
	final ASN1Set attrValues = attribute.getAttrValues();
	for (int ii = 0; ii < attrValues.size(); ii++) {
		final ASN1Encodable asn1Encodable = attrValues.getObjectAt(ii);
		try {
			final SigningCertificateV2 signingCertificate = SigningCertificateV2.getInstance(asn1Encodable);
			if (signingCertificate != null) {
				extractESSCertIDv2s(signingCertificate.getCerts(), CertificateRefOrigin.SIGNING_CERTIFICATE);
			} else {
				LOG.warn("SigningCertificateV2 attribute is null");
			}
		} catch (Exception e) {
			LOG.warn("SigningCertificateV2 attribute '{}' is not well defined!", Utils.toBase64(DSSASN1Utils.getDEREncoded(asn1Encodable)));
		}
	}
}
 
Example #15
Source Project: android-testdpc   Author: googlesamples   File: Asn1Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static Set<Integer> getIntegersFromAsn1Set(ASN1Encodable set)
        throws CertificateParsingException {
    if (!(set instanceof ASN1Set)) {
        throw new CertificateParsingException(
                "Expected set, found " + set.getClass().getName());
    }


    /*
    ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
    for (Enumeration<?> e = ((ASN1Set) set).getObjects(); e.hasMoreElements();) {
        builder.add(getIntegerFromAsn1((ASN1Integer) e.nextElement()));
    }
    return builder.build();
    */
    HashSet<Integer> ret = new HashSet<>();
    for (Enumeration<?> e = ((ASN1Set) set).getObjects(); e.hasMoreElements();) {
        ret.add(getIntegerFromAsn1((ASN1Integer) e.nextElement()));
    }
    return ret;
}
 
Example #16
Source Project: xipki   Author: xipki   File: ExtensionSyntaxChecker.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkSetSyntax(String name, ASN1Set set, List<SubFieldSyntax> subFields)
    throws BadCertTemplateException {
  List<SubFieldSyntax> subFields0 = new ArrayList<SubFieldSyntax>(subFields);

  final int size = set.size();

  for (int i = 0; i < size; i++) {
    ASN1ObjectHolder objHolder = new ASN1ObjectHolder();
    objHolder.object = set.getObjectAt(i);
    // find the matched SubField
    SubFieldSyntax syntax = getSyntax(name, objHolder, subFields0);

    if (syntax == null) {
      throw new BadCertTemplateException("invalid " + name);
    }

    subFields0.remove(syntax);
    checkContentTextOrSubFields(name, syntax, objHolder.object);
  }

  for (SubFieldSyntax m : subFields0) {
    if (m.isRequired()) {
      throw new BadCertTemplateException("invalid " + name);
    }
  }
}
 
Example #17
Source Project: xipki   Author: xipki   File: ExtensionSyntaxChecker.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkContentTextOrSubFields(String name, ExtnSyntax subField,
    ASN1Encodable obj) throws BadCertTemplateException {
  if (obj instanceof ASN1String) {
    if (subField.getStringRegex() != null) {
      assertMatch(name, subField.getStringRegex(), ((ASN1String) obj).getString());
    }
    return;
  }

  FieldType syntaxType = subField.type();
  if (syntaxType == FieldType.SEQUENCE) {
    checkSequenceSyntax(name, (ASN1Sequence) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SET) {
    checkSetSyntax(name, (ASN1Set) obj, subField.getSubFields());
  } else if (syntaxType == FieldType.SEQUENCE_OF) {
    checkSequenceOfOrSetOfSyntax(name, (ASN1Sequence) obj, null, subField.getSubFields());
  } else if (syntaxType == FieldType.SET_OF) {
    checkSequenceOfOrSetOfSyntax(name, null, (ASN1Set) obj, subField.getSubFields());
  }
}
 
Example #18
Source Project: nifi   Author: apache   File: CertificateUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Extract extensions from CSR object
 */
public static Extensions getExtensionsFromCSR(JcaPKCS10CertificationRequest csr) {
    Attribute[] attributess = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    for (Attribute attribute : attributess) {
        ASN1Set attValue = attribute.getAttrValues();
        if (attValue != null) {
            ASN1Encodable extension = attValue.getObjectAt(0);
            if (extension instanceof Extensions) {
                return (Extensions) extension;
            } else if (extension instanceof DERSequence) {
                return Extensions.getInstance(extension);
            }
        }
    }
    return null;
}
 
Example #19
Source Project: hadoop-ozone   Author: apache   File: SecurityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Extensions getPkcs9Extensions(PKCS10CertificationRequest csr)
    throws CertificateException {
  ASN1Set pkcs9ExtReq = getPkcs9ExtRequest(csr);
  Object extReqElement = pkcs9ExtReq.getObjects().nextElement();
  if (extReqElement instanceof Extensions) {
    return (Extensions) extReqElement;
  } else {
    if (extReqElement instanceof ASN1Sequence) {
      return Extensions.getInstance((ASN1Sequence) extReqElement);
    } else {
      throw new CertificateException("Unknown element type :" + extReqElement
          .getClass().getSimpleName());
    }
  }
}
 
Example #20
Source Project: hadoop-ozone   Author: apache   File: SecurityUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static ASN1Set getPkcs9ExtRequest(PKCS10CertificationRequest csr)
    throws CertificateException {
  for (Attribute attr : csr.getAttributes()) {
    ASN1ObjectIdentifier oid = attr.getAttrType();
    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
      return attr.getAttrValues();
    }
  }
  throw new CertificateException("No PKCS#9 extension found in CSR");
}
 
Example #21
Source Project: Auditor   Author: GrapheneOS   File: AttestationApplicationId.java    License: MIT License 5 votes vote down vote up
private List<AttestationPackageInfo> parseAttestationPackageInfos(ASN1Encodable asn1Encodable)
        throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Set)) {
        throw new CertificateParsingException(
                "Expected set for AttestationApplicationsInfos, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Set set = (ASN1Set) asn1Encodable;
    List<AttestationPackageInfo> result = new ArrayList<>();
    for (ASN1Encodable e : set) {
        result.add(new AttestationPackageInfo(e));
    }
    return result;
}
 
Example #22
Source Project: Auditor   Author: GrapheneOS   File: AttestationApplicationId.java    License: MIT License 5 votes vote down vote up
private List<byte[]> parseSignatures(ASN1Encodable asn1Encodable)
        throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Set)) {
        throw new CertificateParsingException("Expected set for Signature digests, found "
                + asn1Encodable.getClass().getName());
    }

    ASN1Set set = (ASN1Set) asn1Encodable;
    List<byte[]> result = new ArrayList<>();

    for (ASN1Encodable e : set) {
        result.add(Asn1Utils.getByteArrayFromAsn1(e));
    }
    return result;
}
 
Example #23
Source Project: Auditor   Author: GrapheneOS   File: Asn1Utils.java    License: MIT License 5 votes vote down vote up
public static Set<Integer> getIntegersFromAsn1Set(ASN1Encodable set)
        throws CertificateParsingException {
    if (!(set instanceof ASN1Set)) {
        throw new CertificateParsingException(
                "Expected set, found " + set.getClass().getName());
    }

    ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
    for (Enumeration<?> e = ((ASN1Set) set).getObjects(); e.hasMoreElements();) {
        builder.add(getIntegerFromAsn1((ASN1Integer) e.nextElement()));
    }
    return builder.build();
}
 
Example #24
Source Project: AttestationServer   Author: GrapheneOS   File: AttestationApplicationId.java    License: MIT License 5 votes vote down vote up
private List<AttestationPackageInfo> parseAttestationPackageInfos(ASN1Encodable asn1Encodable)
        throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Set)) {
        throw new CertificateParsingException(
                "Expected set for AttestationApplicationsInfos, found "
                        + asn1Encodable.getClass().getName());
    }

    ASN1Set set = (ASN1Set) asn1Encodable;
    List<AttestationPackageInfo> result = new ArrayList<>();
    for (ASN1Encodable e : set) {
        result.add(new AttestationPackageInfo(e));
    }
    return result;
}
 
Example #25
Source Project: AttestationServer   Author: GrapheneOS   File: AttestationApplicationId.java    License: MIT License 5 votes vote down vote up
private List<byte[]> parseSignatures(ASN1Encodable asn1Encodable)
        throws CertificateParsingException {
    if (!(asn1Encodable instanceof ASN1Set)) {
        throw new CertificateParsingException("Expected set for Signature digests, found "
                + asn1Encodable.getClass().getName());
    }

    ASN1Set set = (ASN1Set) asn1Encodable;
    List<byte[]> result = new ArrayList<>();

    for (ASN1Encodable e : set) {
        result.add(Asn1Utils.getByteArrayFromAsn1(e));
    }
    return result;
}
 
Example #26
Source Project: AttestationServer   Author: GrapheneOS   File: Asn1Utils.java    License: MIT License 5 votes vote down vote up
public static Set<Integer> getIntegersFromAsn1Set(ASN1Encodable set)
        throws CertificateParsingException {
    if (!(set instanceof ASN1Set)) {
        throw new CertificateParsingException(
                "Expected set, found " + set.getClass().getName());
    }

    ImmutableSet.Builder<Integer> builder = ImmutableSet.builder();
    for (Enumeration<?> e = ((ASN1Set) set).getObjects(); e.hasMoreElements();) {
        builder.add(getIntegerFromAsn1((ASN1Integer) e.nextElement()));
    }
    return builder.build();
}
 
Example #27
Source Project: android-key-attestation   Author: google   File: AuthorizationList.java    License: Apache License 2.0 5 votes vote down vote up
private static Optional<Set<Integer>> findOptionalIntegerSetAuthorizationListEntry(
    Map<Integer, ASN1Primitive> authorizationMap, int tag) {
  ASN1Set asn1Set = (ASN1Set) findAuthorizationListEntry(authorizationMap, tag);
  if (asn1Set == null) {
    return Optional.empty();
  }
  Set<Integer> entrySet = new HashSet<>();
  for (ASN1Encodable value : asn1Set) {
    entrySet.add(ASN1Parsing.getIntegerFromAsn1(value));
  }
  return Optional.of(entrySet);
}
 
Example #28
Source Project: keystore-explorer   Author: kaikramer   File: Asn1Dump.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get dump of the supplied ASN.1 object.
 *
 * @param asn1Object
 *            ASN.1 object
 * @return Dump of object
 * @throws Asn1Exception
 *             A problem was encountered getting the ASN.1 dump
 * @throws IOException
 *             If an I/O problem occurred
 */
public String dump(ASN1Primitive asn1Object) throws Asn1Exception, IOException {
	// Get dump of the supplied ASN.1 object incrementing the indent level of the output
	try {
		indentLevel++;

		if (asn1Object instanceof DERBitString) { // special case of ASN1String
			return dumpBitString((DERBitString) asn1Object);
		} else if (asn1Object instanceof ASN1String) {
			return dumpString((ASN1String) asn1Object);
		} else if (asn1Object instanceof ASN1UTCTime) {
			return dumpUTCTime((ASN1UTCTime) asn1Object);
		} else if (asn1Object instanceof ASN1GeneralizedTime) {
			return dumpGeneralizedTime((ASN1GeneralizedTime) asn1Object);
		} else if (asn1Object instanceof ASN1Sequence ||
				asn1Object instanceof ASN1Set ) {
			return dumpSetOrSequence(asn1Object);
		} else if (asn1Object instanceof ASN1TaggedObject) {
			return dumpTaggedObject((ASN1TaggedObject) asn1Object);
		} else if (asn1Object instanceof ASN1Boolean) {
			return dumpBoolean((ASN1Boolean) asn1Object);
		} else if (asn1Object instanceof ASN1Enumerated) {
			return dumpEnumerated((ASN1Enumerated) asn1Object);
		} else if (asn1Object instanceof ASN1Integer) {
			return dumpInteger((ASN1Integer) asn1Object);
		} else if (asn1Object instanceof ASN1Null) {
			return dumpNull();
		} else if (asn1Object instanceof ASN1ObjectIdentifier) {
			return dumpObjectIdentifier((ASN1ObjectIdentifier) asn1Object);
		} else if (asn1Object instanceof ASN1OctetString) {
			return dumpOctetString((ASN1OctetString) asn1Object);
		} else {
			throw new Asn1Exception("Unknown ASN.1 object: " + asn1Object.toString());
		}
	} finally {
		indentLevel--;
	}
}
 
Example #29
Source Project: keystore-explorer   Author: kaikramer   File: Asn1Dump.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String dumpSetOrSequence(ASN1Encodable asn1ConstructedType) throws Asn1Exception, IOException {
	StringBuilder sb = new StringBuilder();

	sb.append(indentSequence.toString(indentLevel));

	Enumeration<?> components;

	// Sequence or Set?
	if (asn1ConstructedType instanceof ASN1Sequence) {
		sb.append("SEQUENCE");
		ASN1Sequence sequence = (ASN1Sequence) asn1ConstructedType;
		components = sequence.getObjects();
	} else {
		// == SET
		sb.append("SET");
		ASN1Set set = (ASN1Set) asn1ConstructedType;
		components = set.getObjects();
	}

	sb.append(NEWLINE);

	sb.append(indentSequence.toString(indentLevel));
	sb.append("{");
	sb.append(NEWLINE);

	while (components.hasMoreElements()) {
		ASN1Primitive component = (ASN1Primitive) components.nextElement();
		sb.append(dump(component));
	}

	sb.append(indentSequence.toString(indentLevel));

	sb.append("}");
	sb.append(NEWLINE);

	return sb.toString();
}
 
Example #30
Source Project: dss   Author: esig   File: CAdESSignature.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public Date getSigningTime() {
	final Attribute attr = getSignedAttribute(PKCSObjectIdentifiers.pkcs_9_at_signingTime);
	if (attr == null) {
		return null;
	}
	final ASN1Set attrValues = attr.getAttrValues();
	final ASN1Encodable attrValue = attrValues.getObjectAt(0);
	final Date signingDate = DSSASN1Utils.getDate(attrValue);
	if (signingDate != null) {
		/*
		 * RFC 3852 [4] states that "dates between January 1, 1950 and
		 * December 31, 2049 (inclusive) must be encoded as UTCTime. Any
		 * dates with year values before 1950 or after 2049 must be encoded
		 * as GeneralizedTime".
		 */
		if (signingDate.compareTo(JANUARY_1950) >= 0 && signingDate.before(JANUARY_2050)) {
			// must be ASN1UTCTime
			if (!(attrValue instanceof ASN1UTCTime)) {
				LOG.error(
						"RFC 3852 states that dates between January 1, 1950 and December 31, 2049 (inclusive) must be encoded as UTCTime. Any dates with year values before 1950 or after 2049 must be encoded as GeneralizedTime. Date found is {} encoded as {}",
						signingDate, attrValue.getClass());
				return null;
			}
		}
		return signingDate;
	}
	if (LOG.isErrorEnabled()) {
		LOG.error("Error when reading signing time. Unrecognized {}", attrValue.getClass());
	}
	return null;
}