Java Code Examples for org.bouncycastle.asn1.ASN1EncodableVector#add()

The following examples show how to use org.bouncycastle.asn1.ASN1EncodableVector#add() . 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: 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 2
Source File: CadesLevelBaselineLTATimestampExtractor.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * The field certificatesHashIndex is a sequence of octet strings. Each one
 * contains the hash value of one instance of CertificateChoices within
 * certificates field of the root SignedData. A hash value for every instance of
 * CertificateChoices, as present at the time when the corresponding archive
 * time-stamp is requested, shall be included in certificatesHashIndex. No other
 * hash value shall be included in this field.
 *
 * @return
 * @throws eu.europa.esig.dss.model.DSSException
 */
private ASN1Sequence getCertificatesHashIndex() {

	final ASN1EncodableVector certificatesHashIndexVector = new ASN1EncodableVector();

	final Collection<CertificateToken> certificateTokens = certificates;
	for (final CertificateToken certificateToken : certificateTokens) {
		final byte[] digest = certificateToken.getDigest(hashIndexDigestAlgorithm);
		if (LOG.isDebugEnabled()) {
			LOG.debug("Adding to CertificatesHashIndex DSS-Identifier: {} with hash {}", certificateToken.getDSSId(), Utils.toHex(digest));
		}
		final DEROctetString derOctetStringDigest = new DEROctetString(digest);
		certificatesHashIndexVector.add(derOctetStringDigest);
	}
	return new DERSequence(certificatesHashIndexVector);
}
 
Example 3
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 4
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * addOtherNameAsn1Object requires special handling since
 * Bouncy Castle does not support othername as string.
 * @param name
 * @return
 */
private ASN1Object addOtherNameAsn1Object(String name) {
  // Below oid is copied from this URL:
  // https://docs.microsoft.com/en-us/windows/win32/adschema/a-middlename
  final String otherNameOID = "2.16.840.1.113730.3.1.34";
  ASN1EncodableVector otherName = new ASN1EncodableVector();
  otherName.add(new ASN1ObjectIdentifier(otherNameOID));
  otherName.add(new DERTaggedObject(
      true, GeneralName.otherName, new DERUTF8String(name)));
  return new DERTaggedObject(
      false, 0, new DERSequence(otherName));
}
 
Example 5
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new DEROctetString(value.getId()));
  vec.add(new DERUTF8String(value.getLabel()));
  return new DERSequence(vec);
}
 
Example 6
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority, String keyStoreType)
		throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException,
		OperatorCreationException, CertificateException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	nameBuilder.addRDN(BCStyle.CN, authority.commonName());
	nameBuilder.addRDN(BCStyle.O, authority.organization());
	nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

	X500Name issuer = nameBuilder.build();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());
	X500Name subject = issuer;
	PublicKey pubKey = keyPair.getPublic();

	X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, pubKey);

	generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey));
	generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

	KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
			| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
	generator.addExtension(Extension.keyUsage, false, usage);

	ASN1EncodableVector purposes = new ASN1EncodableVector();
	purposes.add(KeyPurposeId.id_kp_serverAuth);
	purposes.add(KeyPurposeId.id_kp_clientAuth);
	purposes.add(KeyPurposeId.anyExtendedKeyUsage);
	generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

	X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

	KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */);
	result.load(null, null);
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert });
	return result;
}
 
Example 7
Source File: SignedAssertion.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(oid);
    v.add(assertion);

    return new DERSequence(v);
}
 
Example 8
Source File: IdentifiedCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static ASN1Sequence createSubjectInfoAccess(
    Map<ASN1ObjectIdentifier, Extension> requestedExtensions,
    Map<ASN1ObjectIdentifier, Set<GeneralNameMode>> modes) throws BadCertTemplateException {
  if (modes == null) {
    return null;
  }

  Extension extn = requestedExtensions.get(Extension.subjectInfoAccess);
  if (extn == null) {
    return null;
  }

  ASN1Encodable extValue = extn.getParsedValue();
  if (extValue == null) {
    return null;
  }

  ASN1Sequence reqSeq = ASN1Sequence.getInstance(extValue);
  int size = reqSeq.size();

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    AccessDescription ad = AccessDescription.getInstance(reqSeq.getObjectAt(i));
    ASN1ObjectIdentifier accessMethod = ad.getAccessMethod();
    Set<GeneralNameMode> generalNameModes = modes.get(accessMethod);

    if (generalNameModes == null) {
      throw new BadCertTemplateException("subjectInfoAccess.accessMethod "
          + accessMethod.getId() + " is not allowed");
    }

    GeneralName accessLocation = BaseCertprofile.createGeneralName(
        ad.getAccessLocation(), generalNameModes);
    vec.add(new AccessDescription(accessMethod, accessLocation));
  } // end for

  return vec.size() > 0 ? new DERSequence(vec) : null;
}
 
Example 9
Source File: ProxyMessage.java    From xipki with Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new SlotIdentifier(slotId));
  vector.add(new ASN1Integer(keyType));
  vector.add(new DEROctetString(keyValue));
  return new DERSequence(vector);
}
 
Example 10
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 11
Source File: CmpAgent.java    From xipki with Apache License 2.0 5 votes vote down vote up
private PKIMessage buildMessageWithXipkiAction(int action, ASN1Encodable value) {
  PKIHeader header = buildPkiHeader(null);

  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(new ASN1Integer(action));
  if (value != null) {
    vec.add(value);
  }

  InfoTypeAndValue itv = new InfoTypeAndValue(ObjectIdentifiers.Xipki.id_xipki_cmp_cmpGenmsg,
      new DERSequence(vec));
  GenMsgContent genMsgContent = new GenMsgContent(itv);
  PKIBody body = new PKIBody(PKIBody.TYPE_GEN_MSG, genMsgContent);
  return new PKIMessage(header, body);
}
 
Example 12
Source File: SM2Util.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
/**
 * 把64字节的纯R+S字节数组编码成DER编码
 *
 * @param rawSign 64字节数组形式的SM2签名值,前32字节为R,后32字节为S
 * @return DER编码后的SM2签名值
 * @throws IOException
 */
public static byte[] encodeSM2SignToDER(byte[] rawSign) throws IOException {
    //要保证大数是正数
    BigInteger r = new BigInteger(1, extractBytes(rawSign, 0, 32));
    BigInteger s = new BigInteger(1, extractBytes(rawSign, 32, 32));
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(r));
    v.add(new ASN1Integer(s));
    return new DERSequence(v).getEncoded(ASN1Encoding.DER);
}
 
Example 13
Source File: SM2PreprocessSigner.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
protected byte[] derEncode(BigInteger r, BigInteger s)
        throws IOException {

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(r));
    v.add(new ASN1Integer(s));
    return new DERSequence(v).getEncoded(ASN1Encoding.DER);
}
 
Example 14
Source File: Spkac.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private byte[] encodeRsaPublicKeyAsBitString(RSAPublicKey rsaPublicKey) throws SpkacException {
	try {
		ASN1EncodableVector vec = new ASN1EncodableVector ();
		vec.add(new ASN1Integer(rsaPublicKey.getModulus()));
		vec.add(new ASN1Integer(rsaPublicKey.getPublicExponent()));
		DERSequence derSequence = new DERSequence(vec);
		return derSequence.getEncoded(ASN1Encoding.DER);
	} catch (Exception ex) {
		throw new SpkacException(res.getString("NoEncodeRsaPublicKey.exception.message"), ex);
	}
}
 
Example 15
Source File: KeyIdentifierGenerator.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private byte[] encodeRsaPublicKeyAsBitString(RSAPublicKey rsaPublicKey) throws IOException {
	ASN1EncodableVector vec = new ASN1EncodableVector();
	vec.add(new ASN1Integer(rsaPublicKey.getModulus()));
	vec.add(new ASN1Integer(rsaPublicKey.getPublicExponent()));

	DERSequence derSequence = new DERSequence(vec);
	return derSequence.getEncoded();
}
 
Example 16
Source File: GeneralSubtrees.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
	ASN1EncodableVector vec = new ASN1EncodableVector();
	for (int i = 0; i < subtrees.size(); i++) {
		vec.add(subtrees.get(i));
	}
	return new DERSequence(vec);
}
 
Example 17
Source File: CertificateHelper.java    From CapturePacket with MIT License 4 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority,
        String keyStoreType) throws NoSuchAlgorithmException,
        NoSuchProviderException, IOException,
        OperatorCreationException, CertificateException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, authority.commonName());
    nameBuilder.addRDN(BCStyle.O, authority.organization());
    nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
            | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore
            .getInstance(keyStoreType/* , PROVIDER_NAME */);
    result.load(null, null);
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), new Certificate[] { cert });
    return result;
}
 
Example 18
Source File: CertificateHelper.java    From LittleProxy-mitm with Apache License 2.0 4 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority,
        String keyStoreType) throws NoSuchAlgorithmException,
        NoSuchProviderException, IOException,
        OperatorCreationException, CertificateException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, authority.commonName());
    nameBuilder.addRDN(BCStyle.O, authority.organization());
    nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
            | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore
            .getInstance(keyStoreType/* , PROVIDER_NAME */);
    result.load(null, null);
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), new Certificate[] { cert });
    return result;
}
 
Example 19
Source File: CertificateHelper.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority,
        String keyStoreType) throws NoSuchAlgorithmException,
        NoSuchProviderException, IOException,
        OperatorCreationException, CertificateException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, authority.commonName());
    nameBuilder.addRDN(BCStyle.O, authority.organization());
    nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
            | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore
            .getInstance(keyStoreType/* , PROVIDER_NAME */);
    result.load(null, null);
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), new Certificate[] { cert });
    return result;
}
 
Example 20
Source File: CAdESLevelBaselineB.java    From dss with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * A content time-stamp allows a time-stamp token of the data to be signed to be incorporated into the signed
 * information.
 * It provides proof of the existence of the data before the signature was created.
 *
 * A content time-stamp attribute is the time-stamp token of the signed data content before it is signed.
 * This attribute is a signed attribute.
 * Its object identifier is :
 * id-aa-ets-contentTimestamp OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs-9(9)
 * smime(16) id-aa(2) 20}
 *
 * Content time-stamp attribute values have ASN.1 type ContentTimestamp:
 * ContentTimestamp ::= TimeStampToken
 *
 * The value of messageImprint of TimeStampToken (as described in RFC 3161) is the hash of the message digest as
 * defined in
 * ETSI standard 101733 v.2.2.1, clause 5.6.1.
 *
 * NOTE: content-time-stamp indicates that the signed information was formed before the date included in the
 * content-time-stamp.
 * NOTE (bis): There is a small difference in treatment between the content-time-stamp and the archive-timestamp
 * (ATSv2) when the signature
 * is attached. In that case, the content-time-stamp is computed on the raw data (without ASN.1 tag and length)
 * whereas the archive-timestamp
 * is computed on data as read.
 *
 * @param parameters
 * @param signedAttributes
 * @return
 */
private void addContentTimestamps(final CAdESSignatureParameters parameters, final ASN1EncodableVector signedAttributes) {

	if (Utils.isCollectionNotEmpty(parameters.getContentTimestamps())) {

		final List<TimestampToken> contentTimestamps = parameters.getContentTimestamps();
		for (final TimestampToken contentTimestamp : contentTimestamps) {

			final ASN1Object asn1Object = DSSASN1Utils.toASN1Primitive(contentTimestamp.getEncoded());
			final DERSet attrValues = new DERSet(asn1Object);
			final Attribute attribute = new Attribute(id_aa_ets_contentTimestamp, attrValues);
			signedAttributes.add(attribute);
		}
	}
}