Java Code Examples for org.bouncycastle.asn1.ASN1EncodableVector

The following examples show how to use org.bouncycastle.asn1.ASN1EncodableVector. 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: xipki   Author: xipki   File: XijsonCertprofile.java    License: 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 #2
Source Project: web3sdk   Author: FISCO-BCOS   File: SignTest.java    License: 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 #3
Source Project: itext2   Author: albfernandez   File: PdfPKCS7.java    License: 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 #4
Source Project: xipki   Author: xipki   File: ProxyMessage.java    License: 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 #5
Source Project: xipki   Author: xipki   File: X509Util.java    License: 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 #6
Source Project: xipki   Author: xipki   File: CmpCaClient.java    License: 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 #7
Source Project: keystore-explorer   Author: kaikramer   File: Spkac.java    License: 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 #8
Source Project: keystore-explorer   Author: kaikramer   File: JarSigner.java    License: 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 #9
Source Project: dss   Author: esig   File: SignerAttributeV2.java    License: 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 #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
/**
 * 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 #12
Source Project: dss   Author: esig   File: CAdESLevelBaselineB.java    License: 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 #13
Source Project: dss   Author: esig   File: CAdESLevelBaselineB.java    License: 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 #14
Source Project: dss   Author: esig   File: CAdESLevelBaselineB.java    License: 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 #15
Source Project: xipki   Author: xipki   File: CaClientExample.java    License: 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 #16
Source Project: InflatableDonkey   Author: horrorho   File: SECPrivateKey.java    License: 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 Project: hadoop-ozone   Author: apache   File: CertificateSignRequest.java    License: 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 #18
Source Project: xipki   Author: xipki   File: ProxyMessage.java    License: 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 DERUTF8String(objectLabel));
  return new DERSequence(vector);
}
 
Example #19
Source Project: xipki   Author: xipki   File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vector = new ASN1EncodableVector();
  vector.add(new ASN1Integer(value.getId()));
  vector.add(new ASN1Integer(value.getIndex()));
  return new DERSequence(vector);
}
 
Example #20
Source Project: NetBare   Author: MegatronKing   File: CertificateGenerator.java    License: MIT License 5 votes vote down vote up
/**
 * Generate a root keystore by a given {@link JKS}.
 *
 * @param jks A java keystore object.
 * @return A root {@link KeyStore}.
 */
public KeyStore generateRoot(JKS jks)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, OperatorCreationException {
    KeyPair keyPair = generateKeyPair(ROOT_KEY_SIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, jks.commonName());
    nameBuilder.addRDN(BCStyle.O, jks.organization());
    nameBuilder.addRDN(BCStyle.OU, jks.organizationalUnitName());
    X500Name issuer = nameBuilder.build();

    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, BigInteger.valueOf(randomSerial()), NOT_BEFORE, NOT_AFTER, issuer, 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(KEY_STORE_TYPE);
    result.load(null, null);
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(),
            new Certificate[] { cert });
    return result;
}
 
Example #21
Source Project: gmhelper   Author: ZZMarquis   File: BCECUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将SEC1标准的私钥字节流恢复为PKCS8标准的字节流
 *
 * @param sec1Key
 * @return
 * @throws IOException
 */
public static byte[] convertECPrivateKeySEC1ToPKCS8(byte[] sec1Key) throws IOException {
    /**
     * 参考org.bouncycastle.asn1.pkcs.PrivateKeyInfo和
     * org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey,逆向拼装
     */
    X962Parameters params = getDomainParametersFromName(SM2Util.JDK_EC_SPEC, false);
    ASN1OctetString privKey = new DEROctetString(sec1Key);
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(new ASN1Integer(0)); //版本号
    v.add(new AlgorithmIdentifier(X9ObjectIdentifiers.id_ecPublicKey, params)); //算法标识
    v.add(privKey);
    DERSequence ds = new DERSequence(v);
    return ds.getEncoded(ASN1Encoding.DER);
}
 
Example #22
Source Project: gmhelper   Author: ZZMarquis   File: SM2PreprocessSigner.java    License: 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 #23
Source Project: gmhelper   Author: ZZMarquis   File: SM2Util.java    License: 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 #24
Source Project: InflatableDonkey   Author: horrorho   File: PrivateKey.java    License: MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {

    ASN1EncodableVector vector = DER.vector(
            new DEROctetString(privateKey()),
            publicKeyInfo.orElse(null));

    return new DERSequence(vector);
}
 
Example #25
Source Project: web3sdk   Author: FISCO-BCOS   File: SM2Signer.java    License: Apache License 2.0 5 votes vote down vote up
public 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 #26
Source Project: xipki   Author: xipki   File: ProxyMessage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
  ASN1EncodableVector vecVersions = new ASN1EncodableVector();
  for (Short version : versions) {
    vecVersions.add(new ASN1Integer(BigInteger.valueOf(version)));
  }

  ASN1EncodableVector vec = new ASN1EncodableVector();
  vec.add(ASN1Boolean.getInstance(readOnly));
  vec.add(new DERSequence(vecVersions));
  return new DERSequence(vec);
}
 
Example #27
Source Project: xipki   Author: xipki   File: PkiMessage.java    License: Apache License 2.0 5 votes vote down vote up
private AttributeTable getSignedAttributes() {
  ASN1EncodableVector vec = new ASN1EncodableVector();
  // messageType
  addAttribute(vec, ScepObjectIdentifiers.ID_MESSAGE_TYPE,
      new DERPrintableString(Integer.toString(messageType.getCode())));

  // senderNonce
  addAttribute(vec, ScepObjectIdentifiers.ID_SENDER_NONCE,
      new DEROctetString(senderNonce.getBytes()));

  // transactionID
  addAttribute(vec, ScepObjectIdentifiers.ID_TRANSACTION_ID,
      new DERPrintableString(transactionId.getId()));

  // failInfo
  if (failInfo != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_FAILINFO,
        new DERPrintableString(Integer.toString(failInfo.getCode())));
  }

  // pkiStatus
  if (pkiStatus != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_PKI_STATUS,
        new DERPrintableString(Integer.toString(pkiStatus.getCode())));
  }

  // recipientNonce
  if (recipientNonce != null) {
    addAttribute(vec, ScepObjectIdentifiers.ID_RECIPIENT_NONCE,
        new DEROctetString(recipientNonce.getBytes()));
  }

  for (ASN1ObjectIdentifier type : signedAttributes.keySet()) {
    addAttribute(vec, type, signedAttributes.get(type));
  }
  return new AttributeTable(vec);
}
 
Example #28
Source Project: InflatableDonkey   Author: horrorho   File: ECDSASignature.java    License: MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {
    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(r),
            new ASN1Integer(s));

    return new DERSequence(vector);
}
 
Example #29
Source Project: jcifs   Author: codelibs   File: NegTokenTarg.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] toByteArray () {
    try {
        ByteArrayOutputStream collector = new ByteArrayOutputStream();
        DEROutputStream der = new DEROutputStream(collector);
        ASN1EncodableVector fields = new ASN1EncodableVector();
        int res = getResult();
        if ( res != UNSPECIFIED_RESULT ) {
            fields.add(new DERTaggedObject(true, 0, new ASN1Enumerated(res)));
        }
        ASN1ObjectIdentifier mech = getMechanism();
        if ( mech != null ) {
            fields.add(new DERTaggedObject(true, 1, mech));
        }
        byte[] mechanismToken = getMechanismToken();
        if ( mechanismToken != null ) {
            fields.add(new DERTaggedObject(true, 2, new DEROctetString(mechanismToken)));
        }
        byte[] mechanismListMIC = getMechanismListMIC();
        if ( mechanismListMIC != null ) {
            fields.add(new DERTaggedObject(true, 3, new DEROctetString(mechanismListMIC)));
        }
        der.writeObject(new DERTaggedObject(true, 1, new DERSequence(fields)));
        return collector.toByteArray();
    }
    catch ( IOException ex ) {
        throw new IllegalStateException(ex.getMessage());
    }
}
 
Example #30
Source Project: InflatableDonkey   Author: horrorho   File: NOS.java    License: MIT License 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {

    ASN1EncodableVector vector = DER.vector(
            new ASN1Integer(x),
            y.map(ASN1Integer::new).orElse(null),
            new DEROctetString(key()));

    return new DERSequence(vector);
}