org.bouncycastle.asn1.DERSequence Java Examples

The following examples show how to use org.bouncycastle.asn1.DERSequence. 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: CAdESTimestampDataBuilder.java    From dss with 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 #3
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 #4
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 #5
Source File: CertificateUtils.java    From localization_nifi with 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 #6
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 #7
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 #8
Source File: DAuthorityInformationAccess.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
private void okPressed() {
	List<AccessDescription> accessDescriptions = jadAccessDescriptions.getAccessDescriptions();

	if (accessDescriptions.isEmpty()) {
		JOptionPane.showMessageDialog(this, res.getString("DAuthorityInformationAccess.ValueReq.message"),
				getTitle(), JOptionPane.WARNING_MESSAGE);
		return;
	}

	ASN1EncodableVector vec = new ASN1EncodableVector();
	for (AccessDescription accessDescription : accessDescriptions) {
		vec.add(accessDescription);
	}
	AuthorityInformationAccess authorityInformationAccess =
			AuthorityInformationAccess.getInstance(new DERSequence(vec));

	try {
		value = authorityInformationAccess.getEncoded(ASN1Encoding.DER);
	} catch (IOException e) {
		DError.displayError(this, e);
		return;
	}

	closeDialog();
}
 
Example #9
Source File: EndPointKeyStoreManager.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * 証明書署名要求のオブジェクトを作成する.
 *
 * @param keyPair キーペア
 * @param commonName コモンネーム
 * @param generalNames SANs
 * @return 証明書署名要求のオブジェクト
 * @throws GeneralSecurityException 作成に失敗した場合
 */
private static PKCS10CertificationRequest createCSR(final KeyPair keyPair,
                                                    final String commonName,
                                                    final GeneralNames generalNames) throws GeneralSecurityException {
    final String signatureAlgorithm = "SHA256WithRSAEncryption";
    final X500Principal principal = new X500Principal("CN=" + commonName + ", O=Device Connect Project, L=N/A, ST=N/A, C=JP");
    DERSequence sanExtension= new DERSequence(new ASN1Encodable[] {
            X509Extensions.SubjectAlternativeName,
            new DEROctetString(generalNames)
    });
    DERSet extensions = new DERSet(new DERSequence(sanExtension));
    DERSequence extensionRequest = new DERSequence(new ASN1Encodable[] {
            PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            extensions
    });
    DERSet attributes = new DERSet(extensionRequest);
    return new PKCS10CertificationRequest(
            signatureAlgorithm,
            principal,
            keyPair.getPublic(),
            attributes,
            keyPair.getPrivate(),
            SecurityUtil.getSecurityProvider());
}
 
Example #10
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 #11
Source File: CertValues.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
  public Attribute getValue() throws SignerException {

  	List<org.bouncycastle.asn1.x509.Certificate> certificateValues = new ArrayList<org.bouncycastle.asn1.x509.Certificate>();
  	try {
  		
  		int chainSize = certificates.length -1;
   		  for (int i = 0; i < chainSize; i++ ){
  		  	    X509Certificate cert = (X509Certificate) certificates[i];
  		  	  byte data[] = cert.getEncoded();
  		  	  certificateValues.add(org.bouncycastle.asn1.x509.Certificate.getInstance(data));    		  	  
  		 }	 
  		  org.bouncycastle.asn1.x509.Certificate[] certValuesArray = new org.bouncycastle.asn1.x509.Certificate[certificateValues.size()];
	return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(certificateValues.toArray(certValuesArray))));
  	} catch (CertificateEncodingException e) {
  		throw new SignerException(e.getMessage());
}
  }
 
Example #12
Source File: SigningCertificate.java    From signer with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Attribute getValue() {
    try {
        X509Certificate cert = (X509Certificate) certificates[0];
        Digest digest = DigestFactory.getInstance().factoryDefault();
        digest.setAlgorithm(DigestAlgorithmEnum.SHA_1);
        byte[] hash = digest.digest(cert.getEncoded());
        X500Name dirName = new X500Name(cert.getSubjectDN().getName());
        GeneralName name = new GeneralName(dirName);
        GeneralNames issuer = new GeneralNames(name);
        ASN1Integer serial = new ASN1Integer(cert.getSerialNumber());
        IssuerSerial issuerSerial = new IssuerSerial(issuer, serial);
        ESSCertID essCertId = new ESSCertID(hash, issuerSerial);
        return new Attribute(new ASN1ObjectIdentifier(identifier), new DERSet(new DERSequence(new ASN1Encodable[]{new DERSequence(essCertId), new DERSequence(DERNull.INSTANCE)})));

    } catch (CertificateEncodingException ex) {
        throw new SignerException(ex.getMessage());
    }
}
 
Example #13
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 #14
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 #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: 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 #17
Source File: CertificateUtils.java    From nifi with 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 #18
Source File: SignedAssertions.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();
    for (SignedAssertion sa : assertions) {
        v.add(sa);
    }

    return new DERSequence(v);
}
 
Example #19
Source File: BaseSyncopeWASAML2ClientTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
protected 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 #20
Source File: SubjectAlternativeNameHolder.java    From LittleProxy-mitm with Apache License 2.0 5 votes vote down vote up
public void fillInto(X509v3CertificateBuilder certGen)
        throws CertIOException {
    if (!sans.isEmpty()) {
        ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans
                .size()]);
        certGen.addExtension(Extension.subjectAlternativeName, false,
                new DERSequence(encodables));
    }
}
 
Example #21
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 #22
Source File: PolicyMapping.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
@Override
public ASN1Primitive toASN1Primitive() {

	ASN1EncodableVector dv = new ASN1EncodableVector();
	dv.add(issuerDomainPolicy);
	dv.add(subjectDomainPolicy);
	return new DERSequence(dv);
}
 
Example #23
Source File: BCECUtil.java    From jiguang-java-client-common with MIT License 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 #24
Source File: ExtensionsChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private void checkExtnPolicyMappings(StringBuilder failureMsg, byte[] extensionValue,
    Extensions requestedExtns, ExtensionControl extControl) {
  PolicyMappings conf = policyMappings;
  if (conf == null) {
    checkConstantExtnValue(Extension.policyMappings, failureMsg, extensionValue,
        requestedExtns, extControl);
    return;
  }

  ASN1Sequence isPolicyMappings = DERSequence.getInstance(extensionValue);
  Map<String, String> isMap = new HashMap<>();
  int size = isPolicyMappings.size();
  for (int i = 0; i < size; i++) {
    ASN1Sequence seq = ASN1Sequence.getInstance(isPolicyMappings.getObjectAt(i));
    CertPolicyId issuerDomainPolicy = CertPolicyId.getInstance(seq.getObjectAt(0));
    CertPolicyId subjectDomainPolicy = CertPolicyId.getInstance(seq.getObjectAt(1));
    isMap.put(issuerDomainPolicy.getId(), subjectDomainPolicy.getId());
  }

  for (PolicyIdMappingType m : conf.getMappings()) {
    String expIssuerDomainPolicy = m.getIssuerDomainPolicy().getOid();
    String expSubjectDomainPolicy = m.getSubjectDomainPolicy().getOid();

    String isSubjectDomainPolicy = isMap.remove(expIssuerDomainPolicy);
    if (isSubjectDomainPolicy == null) {
      failureMsg.append("issuerDomainPolicy '").append(expIssuerDomainPolicy)
        .append("' is absent but is required; ");
    } else if (!isSubjectDomainPolicy.equals(expSubjectDomainPolicy)) {
      addViolation(failureMsg, "subjectDomainPolicy for issuerDomainPolicy",
          isSubjectDomainPolicy, expSubjectDomainPolicy);
    }
  }

  if (CollectionUtil.isNotEmpty(isMap)) {
    failureMsg.append("issuerDomainPolicies '").append(isMap.keySet())
      .append("' are present but not expected; ");
  }
}
 
Example #25
Source File: IdentityCertificateService.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Fill subject alternate names in to signedCertificatebuilder to build new certificate
 * @param sans  a list of subject alternate name.
 *
 * */
private void fillSans(List<ASN1Encodable> sans, X509v3CertificateBuilder x509v3CertificateBuilder)
    throws CertIOException {
  if (!sans.isEmpty()) {
    ASN1Encodable[] encodables = sans.toArray(new ASN1Encodable[sans.size()]);
    x509v3CertificateBuilder.addExtension(Extension.subjectAlternativeName, false, new DERSequence(encodables));
  }
}
 
Example #26
Source File: NegTokenTarg.java    From jcifs-ng with 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 #27
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();
  for (ObjectIdentifier objectId : objectIds) {
    vec.add(objectId);
  }
  return new DERSequence(vec);
}
 
Example #28
Source File: SpnegoContext.java    From jcifs-ng with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @param mechs
 * @return
 * @throws CIFSException
 */
private static byte[] encodeMechs ( ASN1ObjectIdentifier[] mechs ) throws CIFSException {
    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DEROutputStream dos = new DEROutputStream(bos);
        dos.writeObject(new DERSequence(mechs));
        dos.close();
        return bos.toByteArray();
    }
    catch ( IOException e ) {
        throw new CIFSException("Failed to encode mechList", e);
    }
}
 
Example #29
Source File: RevocationInfoArchival.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
public RevocationInfoArchival(CertificateList[] crlVals, OCSPResponse[] ocspVals, OtherRevVals otherRevVals)
{
    if (null != crlVals)
    {
        this.crlVals = new DERSequence(crlVals);
    }
    if (null != ocspVals)
    {
        this.ocspVals = new DERSequence(ocspVals);
    }
    this.otherRevVals = otherRevVals;
}
 
Example #30
Source File: SelectedCommitmentTypes.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void parse(ASN1Primitive derObject) {
    ASN1Sequence derSequence = ASN1Object.getDERSequence(derObject);
    ASN1Primitive object = derSequence.getObjectAt(0).toASN1Primitive();
    if (object instanceof DERNull) {
        this.recognizedCommitmentType = null;
    } else if (object instanceof DERSequence) {
        this.recognizedCommitmentType = new CommitmentType();
        this.recognizedCommitmentType.parse(object);
    }
}