org.bouncycastle.asn1.ASN1EncodableVector Java Examples

The following examples show how to use org.bouncycastle.asn1.ASN1EncodableVector. 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 File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 7 votes vote down vote up
/**
 * 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 #2
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 *
 * 5.10.2 content-identifier Attribute
 * The content-identifier attribute provides an identifier for the signed content, for use when a reference may be
 * later required to that content; for example, in the content-reference attribute in other signed data sent later.
 * The
 * content-identifier shall be a signed attribute. content-identifier attribute type values for the ES have an ASN.1
 * type ContentIdentifier, as defined in
 * ESS (RFC 2634 [5]).
 *
 * The minimal content-identifier attribute should contain a concatenation of user-specific identification
 * information (such as a user name or public keying material identification information), a GeneralizedTime string,
 * and a random number.
 *
 * @param parameters
 * @param signedAttributes
 */
private void addContentIdentifier(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/* this attribute is prohibited in PAdES B */
	if (padesUsage) {
		return;
	}

	final String contentIdentifierPrefix = parameters.getContentIdentifierPrefix();
	if (Utils.isStringNotBlank(contentIdentifierPrefix)) {
		if (Utils.isStringBlank(parameters.getContentIdentifierSuffix())) {
			StringBuilder suffixBuilder = new StringBuilder();
			suffixBuilder.append(new ASN1GeneralizedTime(new Date()).getTimeString());
			suffixBuilder.append(new SecureRandom().nextLong());
			parameters.setContentIdentifierSuffix(suffixBuilder.toString());
		}
		final String contentIdentifierString = contentIdentifierPrefix + parameters.getContentIdentifierSuffix();
		final ContentIdentifier contentIdentifier = new ContentIdentifier(contentIdentifierString.getBytes());
		final DERSet attrValues = new DERSet(contentIdentifier);
		final Attribute attribute = new Attribute(id_aa_contentIdentifier, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #3
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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 List<CommitmentType> commitmentTypeIndications = parameters.bLevel().getCommitmentTypeIndications();
	if (Utils.isCollectionNotEmpty(commitmentTypeIndications)) {

		final int size = commitmentTypeIndications.size();
		ASN1Encodable[] asn1Encodables = new ASN1Encodable[size];
		for (int ii = 0; ii < size; ii++) {
			
			final CommitmentType commitmentType = commitmentTypeIndications.get(ii);
			if (commitmentType.getOid() == null) {
				throw new DSSException("The commitmentTypeIndication OID must be defined for CAdES creation!");
			}

			final ASN1ObjectIdentifier objectIdentifier = new ASN1ObjectIdentifier(commitmentType.getOid());
			final CommitmentTypeIndication commitmentTypeIndication = new CommitmentTypeIndication(objectIdentifier);
			asn1Encodables[ii] = commitmentTypeIndication.toASN1Primitive(); // DER encoded
		}
		final DERSet attrValues = new DERSet(asn1Encodables);
		final Attribute attribute = new Attribute(id_aa_ets_commitmentType, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #4
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
public AttributeTable getSignedAttributes(final CAdESSignatureParameters parameters) {
	if (Utils.isArrayNotEmpty(parameters.getSignedData())) {
		LOG.debug("Using explict SignedAttributes from parameter");
		return CMSUtils.getAttributesFromByteArray(parameters.getSignedData());
	}

	ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
	addSigningCertificateAttribute(parameters, signedAttributes);
	addSigningTimeAttribute(parameters, signedAttributes);
	addSignerAttribute(parameters, signedAttributes);
	addSignaturePolicyId(parameters, signedAttributes);
	addContentHints(parameters, signedAttributes);
	addContentIdentifier(parameters, signedAttributes);
	addCommitmentType(parameters, signedAttributes);
	addSignerLocation(parameters, signedAttributes);
	addContentTimestamps(parameters, signedAttributes);

	// mime-type attribute breaks parallel signatures by adding PKCS7 as a mime-type for subsequent signers.
	// This attribute is not mandatory, so it has been disabled.

	return new AttributeTable(signedAttributes);
}
 
Example #5
Source File: ProxyMessage.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new DERUTF8String(control.getLabel()));

  byte[] id = control.getId();
  if (id != null) {
    vector.add(new DERTaggedObject(0, new DEROctetString(id)));
  }

  Set<P11KeyUsage> usages = control.getUsages();
  if (CollectionUtil.isNotEmpty(usages)) {
    ASN1EncodableVector asn1Usages = new ASN1EncodableVector();
    for (P11KeyUsage usage : usages) {
      int value = usageToValueMap.get(usage);
      asn1Usages.add(new ASN1Enumerated(value));
    }
    vector.add(new DERTaggedObject(1, new DERSequence(asn1Usages)));
  }

  if (control.getExtractable() != null) {
    vector.add(new DERTaggedObject(2, ASN1Boolean.getInstance(control.getExtractable())));
  }

  return new DERSequence(vector);
}
 
Example #6
Source File: PdfPKCS7.java    From itext2 with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Added by Aiken Sam, 2006-11-15, modifed by Martin Brunecky 07/12/2007
 * to start with the timeStampToken (signedData 1.2.840.113549.1.7.2).
 * Token is the TSA response without response status, which is usually
 * handled by the (vendor supplied) TSA request/response interface).
 * @param timeStampToken byte[] - time stamp token, DER encoded signedData
 * @return ASN1EncodableVector
 * @throws IOException
 */
private ASN1EncodableVector buildUnauthenticatedAttributes(byte[] timeStampToken)  throws IOException {
    if (timeStampToken == null)
        return null;

    // @todo: move this together with the rest of the defintions
    String ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14"; // RFC 3161 id-aa-timeStampToken

    ASN1InputStream tempstream = new ASN1InputStream(new ByteArrayInputStream(timeStampToken));
    ASN1EncodableVector unauthAttributes = new ASN1EncodableVector();

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1ObjectIdentifier(ID_TIME_STAMP_TOKEN)); // id-aa-timeStampToken
    ASN1Sequence seq = (ASN1Sequence) tempstream.readObject();
    v.add(new DERSet(seq));

    unauthAttributes.add(new DERSequence(v));
    return unauthAttributes;
 }
 
Example #7
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * 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.
 *
 * @param signerInformation {@link SignerInformation}
 * @param atsHashIndexVersionIdentifier {@link ASN1ObjectIdentifier} of the ats-hash-index table version to create
 * @return
 */
private ASN1Sequence getUnsignedAttributesHashIndex(SignerInformation signerInformation, ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {

	final ASN1EncodableVector unsignedAttributesHashIndex = new ASN1EncodableVector();
	AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
	final ASN1EncodableVector asn1EncodableVector = unsignedAttributes.toASN1EncodableVector();
	for (int i = 0; i < asn1EncodableVector.size(); i++) {
		final Attribute attribute = (Attribute) asn1EncodableVector.get(i);
		if (!excludedAttributesFromAtsHashIndex.contains(attribute.getAttrType())) {
			List<DEROctetString> attributeDerOctetStringHashes = getAttributeDerOctetStringHashes(attribute, atsHashIndexVersionIdentifier);
			for (DEROctetString derOctetStringDigest : attributeDerOctetStringHashes) {
				unsignedAttributesHashIndex.add(derOctetStringDigest);
			}
		}
	}
	return new DERSequence(unsignedAttributesHashIndex);
}
 
Example #8
Source File: X509Util.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static Extension createExtnSubjectInfoAccess(List<String> accessMethodAndLocations,
    boolean critical) throws BadInputException {
  if (CollectionUtil.isEmpty(accessMethodAndLocations)) {
    return null;
  }

  ASN1EncodableVector vector = new ASN1EncodableVector();
  for (String accessMethodAndLocation : accessMethodAndLocations) {
    vector.add(createAccessDescription(accessMethodAndLocation));
  }
  ASN1Sequence seq = new DERSequence(vector);
  try {
    return new Extension(Extension.subjectInfoAccess, critical, seq.getEncoded());
  } catch (IOException ex) {
    throw new IllegalStateException(ex.getMessage(), ex);
  }
}
 
Example #9
Source File: SignTest.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testGmSignVerify() throws IOException {
    byte[] sourceData =
            Hex.decode("434477813974bf58f94bcf760833c2b40f77a5fc360485b0b9ed1bd9682edb45");
    String publicKey =
            "e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    String sign =
            "09628650676000c8d18bf43db68e7f66dfaed230d87e6391c29eb594b7b9cc3c8d370dbd29ce62bbcf3506adb57f041d8646ae4f70a26ea5179418e738fd4372e8c670380cb220095268f40221fc748fa6ac39d6e930e63c30da68bad97f885da6e8c9ad722c3683ab859393220d1431eb1818ed44a942efb07b261a0fc769e7";
    byte[] signatureBytes = Numeric.hexStringToByteArray("0x" + sign);

    ASN1Integer d_r =
            new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 0, 32)));
    ASN1Integer d_s =
            new ASN1Integer(new BigInteger(1, Arrays.copyOfRange(signatureBytes, 32, 64)));
    ASN1EncodableVector v2 = new ASN1EncodableVector();
    v2.add(d_r);
    v2.add(d_s);
    DERSequence der = new DERSequence(v2);
    boolean b =
            SM2Algorithm.verify(
                    sourceData,
                    der.getEncoded(),
                    publicKey.substring(0, 64),
                    publicKey.substring(64, 128));
    assertTrue("Test sm2 verify", b);
}
 
Example #10
Source File: CmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
private Certificate[] cmpCaCerts() throws Exception {
  ProtectedPKIMessageBuilder builder = new ProtectedPKIMessageBuilder(
      PKIHeader.CMP_2000, requestorSubject, responderSubject);
  builder.setMessageTime(new Date());
  builder.setTransactionID(randomTransactionId());
  builder.setSenderNonce(randomSenderNonce());

  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(CMP_ACTION_CACERTCHAIN));

  InfoTypeAndValue itv = new InfoTypeAndValue(id_xipki_cmp_cacertchain, new DERSequence(vec));
  PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, new GenMsgContent(itv));
  builder.setBody(body);

  ProtectedPKIMessage request = build(builder);
  PKIMessage response = transmit(request, null);
  ASN1Encodable asn1Value = extractGeneralRepContent(response, id_xipki_cmp_cacertchain.getId());
  ASN1Sequence seq = ASN1Sequence.getInstance(asn1Value);

  final int size = seq.size();
  Certificate[] caCerts = new Certificate[size];
  for (int i = 0; i < size; i++) {
    caCerts[i] = CMPCertificate.getInstance(seq.getObjectAt(i)).getX509v3PKCert();
  }
  return caCerts;
}
 
Example #11
Source File: CaClientExample.java    From xipki with Apache License 2.0 6 votes vote down vote up
protected static MyKeypair generateDsaKeypair() throws Exception {
  // plen: 2048, qlen: 256
  DSAParameterSpec spec = new DSAParameterSpec(P2048_Q256_P, P2048_Q256_Q, P2048_Q256_G);
  KeyPairGenerator kpGen = KeyPairGenerator.getInstance("DSA");
  kpGen.initialize(spec);
  KeyPair kp = kpGen.generateKeyPair();

  DSAPublicKey dsaPubKey = (DSAPublicKey) kp.getPublic();
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(dsaPubKey.getParams().getP()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getQ()));
  vec.add(new ASN1Integer(dsaPubKey.getParams().getG()));
  ASN1Sequence dssParams = new DERSequence(vec);

  SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(
      new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams),
      new ASN1Integer(dsaPubKey.getY()));

  return new MyKeypair(kp.getPrivate(), subjectPublicKeyInfo);
}
 
Example #12
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private ASN1Sequence createPublicKeyAndChallenge() throws SpkacException {
	ASN1EncodableVector publicKeyAlgorithm = new ASN1EncodableVector();
	publicKeyAlgorithm.add(new ASN1ObjectIdentifier(getPublicKeyAlg().oid()));

	if (getPublicKey() instanceof RSAPublicKey) {
		publicKeyAlgorithm.add(DERNull.INSTANCE);
	} else {
		DSAParams dsaParams = ((DSAPublicKey) getPublicKey()).getParams();

		ASN1EncodableVector dssParams = new ASN1EncodableVector();
		dssParams.add(new ASN1Integer(dsaParams.getP()));
		dssParams.add(new ASN1Integer(dsaParams.getQ()));
		dssParams.add(new ASN1Integer(dsaParams.getG()));

		publicKeyAlgorithm.add(new DERSequence(dssParams));
	}

	ASN1EncodableVector spki = new ASN1EncodableVector();
	spki.add(new DERSequence(publicKeyAlgorithm));
	spki.add(encodePublicKeyAsBitString(getPublicKey()));

	ASN1EncodableVector publicKeyAndChallenge = new ASN1EncodableVector();
	publicKeyAndChallenge.add(new DERSequence(spki));
	publicKeyAndChallenge.add(new DERIA5String(getChallenge()));
	return new DERSequence(publicKeyAndChallenge);
}
 
Example #13
Source File: JarSigner.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
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;
	}
 
Example #14
Source File: SignerAttributeV2.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * <pre>
 *  SignerAttributeV2 ::= SEQUENCE {
 *	 	claimedAttributes [0] ClaimedAttributes OPTIONAL,
 * 		certifiedAttributesV2 [1] CertifiedAttributesV2 OPTIONAL,
 * 		signedAssertions [2] SignedAssertions OPTIONAL
 *	}
 * </pre>
 */
@Override
public ASN1Primitive toASN1Primitive() {
	ASN1EncodableVector v = new ASN1EncodableVector();

	for (int i = 0; i != values.length; i++) {
		if (values[i] instanceof Attribute[]) {
			v.add(new DERTaggedObject(0, new DERSequence((Attribute[]) values[i])));
		} else if (values[i] instanceof CertifiedAttributesV2) {
			v.add(new DERTaggedObject(1, (CertifiedAttributesV2) values[i]));
		} else if (values[i] instanceof SignedAssertions) {
			v.add(new DERTaggedObject(2, (SignedAssertions) values[i]));
		} else {
			LOG.warn("Unsupported type {}", values[i]);
		}
	}

	return new DERSequence(v);
}
 
Example #15
Source File: XijsonCertprofile.java    From xipki with Apache License 2.0 6 votes vote down vote up
private void initAuthorizationTemplate(Set<ASN1ObjectIdentifier> extnIds,
    Map<String, ExtensionType> extensions) throws CertprofileException {
  ASN1ObjectIdentifier type = ObjectIdentifiers.Xipki.id_xipki_ext_authorizationTemplate;
  if (extensionControls.containsKey(type)) {
    extnIds.remove(type);
    AuthorizationTemplate extConf = getExtension(type, extensions).getAuthorizationTemplate();
    if (extConf != null) {
      ASN1EncodableVector vec = new ASN1EncodableVector();
      vec.add(new ASN1ObjectIdentifier(extConf.getType().getOid()));
      vec.add(new DEROctetString(extConf.getAccessRights().getValue()));
      ASN1Encodable extValue = new DERSequence(vec);
      authorizationTemplate =
          new ExtensionValue(extensionControls.get(type).isCritical(), extValue);
    }
  }
}
 
Example #16
Source File: SECPrivateKey.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    DERTaggedObject parametersEncodable = parameters()
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(PARAMETERS, e))
            .orElseGet(null);

    DERTaggedObject publicKeyEncodable = publicKey()
            .map(DERBitString::new)
            .map(e -> new DERTaggedObject(PUBLIC_KEY, e))
            .orElseGet(null);

    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(version),
            new DEROctetString(privateKey),
            parametersEncodable,
            publicKeyEncodable);

    return new DERSequence(vector);
}
 
Example #17
Source File: Signature.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = DER.vector(
            new DEROctetString(signerKeyID()),
            new ASN1Integer(type),
            new DEROctetString(data()));

    return new DERSequence(vector);
}
 
Example #18
Source File: ProtectionInfo.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {

    DERTaggedObject dataEncodable = data
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(DATA, e))
            .orElseGet(null);

    DERTaggedObject signatureEncodable = signature
            .map(e -> new DERTaggedObject(SIGNATURE, e))
            .orElseGet(null);

    DERTaggedObject tagEncodable = tag
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(TAG, e))
            .orElseGet(null);

    DERTaggedObject cont3Encodable = cont3
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(CONT3, e))
            .orElseGet(null);

    DERTaggedObject cont4Encodable = cont4
            .map(DEROctetString::new)
            .map(e -> new DERTaggedObject(CONT4, e))
            .orElseGet(null);

    ASN1EncodableVector vector = DER.vector(
            encryptedKeys,
            dataEncodable,
            signatureEncodable,
            new DEROctetString(hmac()),
            tagEncodable,
            cont3Encodable,
            cont4Encodable);

    DERSequence sequence = new DERSequence(vector);
    return DER.toApplicationSpecific(APPLICATION_TAG, sequence);
}
 
Example #19
Source File: CaEnrollBenchKeyEntry.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void init(BigInteger p, BigInteger q, BigInteger g, BigInteger y) throws IOException {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(p));
  vec.add(new ASN1Integer(q));
  vec.add(new ASN1Integer(g));
  ASN1Sequence dssParams = new DERSequence(vec);
  AlgorithmIdentifier algId = new AlgorithmIdentifier(X9ObjectIdentifiers.id_dsa, dssParams);
  this.spki = new SubjectPublicKeyInfo(algId, new ASN1Integer(y));
}
 
Example #20
Source File: EncryptedKey.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1Integer asn1IntegerFlags = flags.map(ASN1Integer::new)
            .orElse(null);

    ASN1EncodableVector vector = DER.vector(
            masterKey,
            new DEROctetString(wrappedKey()),
            asn1IntegerFlags);

    return new DERSequence(vector);
}
 
Example #21
Source File: Item.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(version),
            new DEROctetString(octets()));

    return new DERSequence(vector);
}
 
Example #22
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void addSignaturePolicyId(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {

		Policy policy = parameters.bLevel().getSignaturePolicy();
		if (policy != null) {

			final String policyId = policy.getId();
			SignaturePolicyIdentifier sigPolicy = null;

			if (Utils.isStringEmpty(policyId)) {// implicit
				sigPolicy = new SignaturePolicyIdentifier();
			} else { // explicit
				final ASN1ObjectIdentifier derOIPolicyId = new ASN1ObjectIdentifier(policyId);
				final ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(policy.getDigestAlgorithm().getOid());
				final AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(oid);
				OtherHashAlgAndValue otherHashAlgAndValue = new OtherHashAlgAndValue(algorithmIdentifier, new DEROctetString(policy.getDigestValue()));

				if (Utils.isStringNotEmpty(policy.getSpuri())) {
					SigPolicyQualifierInfo policyQualifierInfo = new SigPolicyQualifierInfo(PKCSObjectIdentifiers.id_spq_ets_uri,
							new DERIA5String(policy.getSpuri()));
					SigPolicyQualifierInfo[] qualifierInfos = new SigPolicyQualifierInfo[] { policyQualifierInfo };
					SigPolicyQualifiers qualifiers = new SigPolicyQualifiers(qualifierInfos);

					sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue, qualifiers));
				} else {
					sigPolicy = new SignaturePolicyIdentifier(new SignaturePolicyId(derOIPolicyId, otherHashAlgAndValue));
				}
			}

			final DERSet attrValues = new DERSet(sigPolicy);
			final Attribute attribute = new Attribute(id_aa_ets_sigPolicyId, attrValues);
			signedAttributes.add(attribute);
		}
	}
 
Example #23
Source File: BackupEscrow.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = DER.vector(
            new DEROctetString(wrappedKey()),
            new DEROctetString(data()),
            new DEROctetString(x()),
            new ASN1Integer(y),
            new DEROctetString(masterKeyPublic()));

    DERSequence sequence = new DERSequence(vector);
    return DER.toApplicationSpecific(APPLICATION_TAG, sequence);
}
 
Example #24
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * ETSI TS 101 733 V2.2.1 (2013-04)
 * 5.11.2 signer-location Attribute
 * The signer-location attribute specifies a mnemonic for an address associated with the signer at a particular
 * geographical (e.g. city) location. The mnemonic is registered in the country in which the signer is located and
 * is used in
 * the provision of the Public Telegram Service (according to Recommendation ITU-T F.1 [11]).
 * The signer-location attribute shall be a signed attribute.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addSignerLocation(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {
	/*
	 * In PAdES, the role is in the signature dictionary
	 */
	if (padesUsage) {
		return;
	}

	final eu.europa.esig.dss.model.SignerLocation signerLocationParameter = parameters.bLevel().getSignerLocation();
	if (signerLocationParameter != null && !signerLocationParameter.isEmpty()) {

		final DERUTF8String country = signerLocationParameter.getCountry() == null ? null : new DERUTF8String(signerLocationParameter.getCountry());
		final DERUTF8String locality = signerLocationParameter.getLocality() == null ? null : new DERUTF8String(signerLocationParameter.getLocality());
		final ASN1EncodableVector postalAddress = new ASN1EncodableVector();
		final List<String> postalAddressParameter = signerLocationParameter.getPostalAddress();
		if (postalAddressParameter != null) {
			for (final String addressLine : postalAddressParameter) {
				postalAddress.add(new DERUTF8String(addressLine));
			}
		}
		final DERSequence derSequencePostalAddress = new DERSequence(postalAddress);
		final SignerLocation signerLocation = new SignerLocation(country, locality, derSequencePostalAddress);
		final DERSet attrValues = new DERSet(signerLocation);
		final Attribute attribute = new Attribute(id_aa_ets_signerLocation, attrValues);
		signedAttributes.add(attribute);
	}
}
 
Example #25
Source File: BaseCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static RDN createPostalAddressRdn(ASN1ObjectIdentifier type, ASN1Encodable rdnValue,
    RdnControl control, int index) throws BadCertTemplateException {
  Args.notNull(type, "type");

  if (!(rdnValue instanceof ASN1Sequence)) {
    throw new BadCertTemplateException("rdnValue of RDN postalAddress has incorrect syntax");
  }

  ASN1Sequence seq = (ASN1Sequence) rdnValue;
  final int size = seq.size();
  if (size < 1 || size > 6) {
    throw new BadCertTemplateException(
        "Sequence size of RDN postalAddress is not within [1, 6]: " + size);
  }

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    ASN1Encodable line = seq.getObjectAt(i);
    String text;
    if (line instanceof ASN1String && !(line instanceof DERUniversalString)) {
      text = ((ASN1String) line).getString();
    } else {
      throw new BadCertTemplateException(
        String.format("postalAddress[%d] has incorrect syntax", i));
    }

    ASN1Encodable asn1Line = createRdnValue(text, type, control, index);
    vec.add(asn1Line);
  }

  return new RDN(type, new DERSequence(vec));
}
 
Example #26
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * 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.
 * 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 timestampHashIndex
 * @return
 */
@SuppressWarnings("unchecked")
private ASN1Sequence getVerifiedUnsignedAttributesHashIndex(SignerInformation signerInformation, final ASN1Sequence timestampHashIndex, 
		ASN1ObjectIdentifier atsHashIndexVersionIdentifier) {
	
	final ASN1Sequence unsignedAttributesHashes = DSSASN1Utils.getUnsignedAttributesHashIndex(timestampHashIndex);
	
	final List<DEROctetString> timestampUnsignedAttributesHashesList = new ArrayList<>();
	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);
		List<DEROctetString> attributeDerOctetStringHashes = getAttributeDerOctetStringHashes(attribute, atsHashIndexVersionIdentifier);
		for (DEROctetString derOctetStringDigest : attributeDerOctetStringHashes) {
			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(s) hash in Timestamp has 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;
}
 
Example #27
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void digestAndAddToList(ASN1EncodableVector crlsHashIndex, byte[] encoded) {
	final byte[] digest = DSSUtils.digest(hashIndexDigestAlgorithm, encoded);
	if (LOG.isDebugEnabled()) {
		LOG.debug("Adding to crlsHashIndex with hash {}", Utils.toHex(digest));
	}
	final DEROctetString derOctetStringDigest = new DEROctetString(digest);
	crlsHashIndex.add(derOctetStringDigest);
}
 
Example #28
Source File: ExtensionType.java    From xipki with Apache License 2.0 5 votes vote down vote up
public ASN1Sequence toXiPolicyConstrains() throws CertprofileException {
  if (requireExplicitPolicy != null && requireExplicitPolicy < 0) {
    throw new CertprofileException(
        "negative requireExplicitPolicy is not allowed: " + requireExplicitPolicy);
  }

  if (inhibitPolicyMapping != null && inhibitPolicyMapping < 0) {
    throw new CertprofileException(
        "negative inhibitPolicyMapping is not allowed: " + inhibitPolicyMapping);
  }

  if (requireExplicitPolicy == null && inhibitPolicyMapping == null) {
    return null;
  }

  final boolean explicit = false;
  ASN1EncodableVector vec = new ASN1EncodableVector();
  if (requireExplicitPolicy != null) {
    vec.add(new DERTaggedObject(explicit, 0,
        new ASN1Integer(BigInteger.valueOf(requireExplicitPolicy))));
  }

  if (inhibitPolicyMapping != null) {
    vec.add(new DERTaggedObject(explicit, 1,
        new ASN1Integer(BigInteger.valueOf(inhibitPolicyMapping))));
  }

  return new DERSequence(vec);
}
 
Example #29
Source File: SAML2SPKeystoreTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Certificate createSelfSignedCert(final KeyPair keyPair) throws Exception {
    final X500Name dn = new X500Name("cn=Unknown");
    final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator();

    certGen.setSerialNumber(new ASN1Integer(BigInteger.valueOf(1)));
    certGen.setIssuer(dn);
    certGen.setSubject(dn);
    certGen.setStartDate(new Time(new Date(System.currentTimeMillis() - 1000L)));

    final Date expiration = new Date(System.currentTimeMillis() + 100000);
    certGen.setEndDate(new Time(expiration));

    final AlgorithmIdentifier sigAlgID = new AlgorithmIdentifier(PKCSObjectIdentifiers.sha1WithRSAEncryption, DERNull.INSTANCE);
    certGen.setSignature(sigAlgID);
    certGen.setSubjectPublicKeyInfo(SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    final Signature sig = Signature.getInstance("SHA1WithRSA");
    sig.initSign(keyPair.getPrivate());
    sig.update(certGen.generateTBSCertificate().getEncoded(ASN1Encoding.DER));

    final TBSCertificate tbsCert = certGen.generateTBSCertificate();
    final ASN1EncodableVector v = new ASN1EncodableVector();

    v.add(tbsCert);
    v.add(sigAlgID);
    v.add(new DERBitString(sig.sign()));

    final Certificate cert = CertificateFactory.getInstance("X.509")
        .generateCertificate(new ByteArrayInputStream(new DERSequence(v).getEncoded(ASN1Encoding.DER)));
    cert.verify(keyPair.getPublic());
    return cert;
}
 
Example #30
Source File: OxAuthCryptoProvider.java    From oxAuth with MIT License 5 votes vote down vote up
public X509Certificate generateV3Certificate(KeyPair keyPair, String issuer, String signatureAlgorithm, Long expirationTime) throws CertIOException, OperatorCreationException, CertificateException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Signers name
    X500Name issuerName = new X500Name(issuer);

    // Subjects name - the same as we are self signed.
    X500Name subjectName = new X500Name(issuer);

    // Serial
    BigInteger serial = new BigInteger(256, new SecureRandom());

    // Not before
    Date notBefore = new Date(System.currentTimeMillis() - 10000);
    Date notAfter = new Date(expirationTime);

    // Create the certificate - version 3
    JcaX509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuerName, serial, notBefore, notAfter, subjectName, publicKey);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);

    ASN1ObjectIdentifier extendedKeyUsage = new ASN1ObjectIdentifier("2.5.29.37").intern();
    builder.addExtension(extendedKeyUsage, false, new DERSequence(purposes));

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).setProvider("BC").build(privateKey);
    X509CertificateHolder holder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);

    return cert;
}