org.bouncycastle.asn1.x509.Certificate Java Examples

The following examples show how to use org.bouncycastle.asn1.x509.Certificate. 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: CrlStreamParserTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCrl2() throws Exception {
  File crlFile = new File("src/test/resources/crls/crl-2/ca1-crl.crl");
  Certificate issuerSigner = parseCert("src/test/resources/crls/crl-2/ca1-cert.crt");

  CrlStreamParser parser = new CrlStreamParser(crlFile);
  Assert.assertEquals("version", 1, parser.getVersion());
  Assert.assertEquals("CRL number", BigInteger.valueOf(5), parser.getCrlNumber());

  Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));

  int numRevokedCerts = 0;

  try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
    while (iterator.hasNext()) {
      iterator.next();
      numRevokedCerts++;
    }
  }

  Assert.assertEquals("#revokedCertificates", 6, numRevokedCerts);
}
 
Example #2
Source File: CertTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Test
public void szcaCertTest() throws Exception {
    String skPath = "/szca/sk-test";
    String certPath = "/szca/signcert.pem";
    String testData = "this is test data";
    String privateKeyPath = CertTest.class.getResource(skPath).getPath();
    String signCertPath = CertTest.class.getResource(certPath).getPath();
    byte[] sk = CryptoUtil.getPrivateKey(privateKeyPath);
    byte[] certBytes = FileUtils.readFileBytes(signCertPath);
    Certificate signCert = Certificate.getInstance(
            new PemReader(new InputStreamReader(new ByteArrayInputStream(certBytes))).readPemObject().getContent());
    byte[] pk = signCert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    byte[] sign = sm2.sign(sk, testData.getBytes());
    boolean result = sm2.verify(pk, sign, testData.getBytes());
    assertEquals(true, result);
}
 
Example #3
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 6 votes vote down vote up
@Test
public void certTest() throws IOException {
    String privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" +
            "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" +
            "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" +
            "C8r6EmyE";
    byte[] sk = org.bouncycastle.util.encoders.Base64.decode(privateKey);

    System.out.println("私钥长度" + sk.length);
    System.out.println(Hex.toHexString(sk));
    String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath();
    byte[] idBytes = FileUtils.readFileBytes(cert_path);
    Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
    byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

    System.out.println(certificate.getSubject());
    System.out.println("公钥:" + Hex.toHexString(publickey));
    System.out.println("公钥长度:" + publickey.length);
}
 
Example #4
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 #5
Source File: CmpCaClient.java    From xipki with Apache License 2.0 6 votes vote down vote up
public void init() throws Exception {
  TlsInit.init();

  if (caCert != null) {
    return;
  }

  Certificate[] certchain = cmpCaCerts();
  this.caCertchain = new ArrayList<>(certchain.length);
  for (Certificate m : certchain) {
    this.caCertchain.add(
        SdkUtil.parseCert((m.getEncoded())));
  }

  this.caCert = this.caCertchain.get(0);
  this.caSubject = certchain[0].getSubject();
  this.caSubjectKeyIdentifier = SdkUtil.extractSki(this.caCert);
}
 
Example #6
Source File: CaHelper.java    From julongchain with Apache License 2.0 6 votes vote down vote up
public static Certificate loadCertificateSM2(String certPath) throws JulongChainException {
    File certDir = new File(certPath);
    File[] files = certDir.listFiles();
    if (!certDir.isDirectory() || files == null) {
        log.error("invalid directory for certPath " + certPath);
        return null;
    }
    for (File file : files) {
        if (!file.getName().endsWith(".pem")) {
            continue;
        }
        try {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file));
            PemReader pemReader = new PemReader(reader);
            PemObject pemObject = pemReader.readPemObject();
            reader.close();
            byte[] certBytes = pemObject.getContent();
            return Certificate.getInstance(certBytes);
        } catch (Exception e) {
            throw new JulongChainException("An error occurred :" + e.getMessage());
        }
    }
    throw new JulongChainException("no pem file found");
}
 
Example #7
Source File: CrlStreamParserTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCrlWithNoExtension() throws Exception {
  File crlFile = new File("src/test/resources/crls/crl-6/no-extensions.crl");
  Certificate issuerSigner = parseCert("src/test/resources/crls/crl-6/ca.crt");

  CrlStreamParser parser = new CrlStreamParser(crlFile);
  Assert.assertEquals("version", 1, parser.getVersion());
  Assert.assertEquals("CRL number", null, parser.getCrlNumber());

  Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));

  int numRevokedCerts = 0;

  try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
    while (iterator.hasNext()) {
      iterator.next();
      numRevokedCerts++;
    }
  }

  Assert.assertEquals("#revokedCertificates", 0, numRevokedCerts);
}
 
Example #8
Source File: CrlStreamParserTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCrlWithNoCrlNumber() throws Exception {
  File crlFile = new File("src/test/resources/crls/crl-5/no-crlnumber.crl");
  Certificate issuerSigner = parseCert("src/test/resources/crls/crl-5/ca.crt");

  CrlStreamParser parser = new CrlStreamParser(crlFile);
  Assert.assertEquals("version", 1, parser.getVersion());
  Assert.assertEquals("CRL number", null, parser.getCrlNumber());

  Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));

  int numRevokedCerts = 0;

  try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
    while (iterator.hasNext()) {
      iterator.next();
      numRevokedCerts++;
    }
  }

  Assert.assertEquals("#revokedCertificates", 0, numRevokedCerts);
}
 
Example #9
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a OCSP Request
 *
 * @param pairIssuerSubject a pair of issuer and subject certificates
 * @return OCSPReq object
 */
private OCSPReq createRequest(
    SFPair<Certificate, Certificate> pairIssuerSubject) throws IOException
{
  Certificate issuer = pairIssuerSubject.left;
  Certificate subject = pairIssuerSubject.right;
  OCSPReqBuilder gen = new OCSPReqBuilder();
  try
  {
    DigestCalculator digest = new SHA1DigestCalculator();
    X509CertificateHolder certHolder = new X509CertificateHolder(issuer.getEncoded());
    CertificateID certId = new CertificateID(
        digest, certHolder, subject.getSerialNumber().getValue());
    gen.addRequest(certId);
    return gen.build();
  }
  catch (OCSPException ex)
  {
    throw new IOException("Failed to build a OCSPReq.", ex);
  }
}
 
Example #10
Source File: CAdESTimestampSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected List<Identifier> getEncapsulatedCertificateIdentifiers(CAdESAttribute unsignedAttribute) {
	List<Identifier> certificateIdentifiers = new ArrayList<>();
	ASN1Sequence seq = (ASN1Sequence) unsignedAttribute.getASN1Object();
	for (int ii = 0; ii < seq.size(); ii++) {
		try {
			final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
			CertificateToken certificateToken = DSSUtils.loadCertificate(cs.getEncoded());
			certificateIdentifiers.add(certificateToken.getDSSId());
		} catch (Exception e) {
			String errorMessage = "Unable to parse an encapsulated certificate : {}";
			if (LOG.isDebugEnabled()) {
				LOG.warn(errorMessage, e.getMessage(), e);
			} else {
				LOG.warn(errorMessage, e.getMessage());
			}
		}
	}
	return certificateIdentifiers;
}
 
Example #11
Source File: CMSCertificateSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void extractCertificateValues() {
	AttributeTable unsignedAttributes = currentSignerInformation.getUnsignedAttributes();
	if (unsignedAttributes != null) {
		Attribute attribute = unsignedAttributes.get(id_aa_ets_certValues);
		if (attribute != null) {
			final ASN1Sequence seq = (ASN1Sequence) attribute.getAttrValues().getObjectAt(0);
			for (int ii = 0; ii < seq.size(); ii++) {
				try {
					final Certificate cs = Certificate.getInstance(seq.getObjectAt(ii));
					addCertificate(DSSUtils.loadCertificate(cs.getEncoded()), CertificateOrigin.CERTIFICATE_VALUES);
				} catch (Exception e) {
					LOG.warn("Unable to parse encapsulated certificate : {}", e.getMessage());
				}
			}
		}
	}
}
 
Example #12
Source File: CrlStreamParserTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCrlWithNoRevokedCerts() throws Exception {
  File crlFile = new File("src/test/resources/crls/crl-4/no-revoked-certs.crl");
  Certificate issuerSigner = parseCert("src/test/resources/crls/crl-4/ca.crt");

  CrlStreamParser parser = new CrlStreamParser(crlFile);
  Assert.assertEquals("version", 1, parser.getVersion());
  Assert.assertEquals("CRL number", BigInteger.valueOf(6), parser.getCrlNumber());

  Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));

  int numRevokedCerts = 0;

  try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
    while (iterator.hasNext()) {
      iterator.next();
      numRevokedCerts++;
    }
  }

  Assert.assertEquals("#revokedCertificates", 0, numRevokedCerts);
}
 
Example #13
Source File: CrlStreamParserTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCrlWithInvalidityDate() throws Exception {
  File crlFile = new File("src/test/resources/crls/crl-3/subcawithcrl1.crl");
  Certificate issuerSigner = parseCert("src/test/resources/crls/crl-3/ca.crt");

  CrlStreamParser parser = new CrlStreamParser(crlFile);
  Assert.assertEquals("version", 1, parser.getVersion());
  Assert.assertEquals("CRL number", BigInteger.valueOf(5), parser.getCrlNumber());

  Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));

  int numRevokedCerts = 0;

  try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
    while (iterator.hasNext()) {
      iterator.next();
      numRevokedCerts++;
    }
  }

  Assert.assertEquals("#revokedCertificates", 2, numRevokedCerts);
}
 
Example #14
Source File: X509Cert.java    From xipki with Apache License 2.0 6 votes vote down vote up
private void checkBcSignature(PublicKey key, Signature signature)
    throws CertificateException, NoSuchAlgorithmException,
        SignatureException, InvalidKeyException {
  Certificate c = bcInstance.toASN1Structure();
  if (!c.getSignatureAlgorithm().equals(c.getTBSCertificate().getSignature())) {
    throw new CertificateException("signature algorithm in TBS cert not same as outer cert");
  }

  signature.initVerify(key);
  try {
    signature.update(c.getTBSCertificate().getEncoded());
  } catch (IOException ex) {
    throw new CertificateException("error encoding TBSCertificate");
  }

  if (!signature.verify(c.getSignature().getBytes())) {
    throw new SignatureException("certificate does not verify with supplied key");
  }
}
 
Example #15
Source File: CtLogTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
private void parseCtLogInCert(String certFile) throws Exception {
  byte[] certBytes = IoUtil.read(getClass().getResourceAsStream(certFile));
  certBytes = X509Util.toDerEncoded(certBytes);
  Certificate cert = Certificate.getInstance(certBytes);
  Extension extn = cert.getTBSCertificate().getExtensions().getExtension(
                      ObjectIdentifiers.Extn.id_SCTs);
  byte[] encodedScts = DEROctetString.getInstance(extn.getParsedValue()).getOctets();
  SignedCertificateTimestampList sctList2 =
      SignedCertificateTimestampList.getInstance(encodedScts);
  SignedCertificateTimestamp sct = sctList2.getSctList().get(0);
  sct.getDigitallySigned().getEncoded();
  sctList2.getSctList().get(0).getDigitallySigned().getSignatureObject();
  byte[] encoded2 = sctList2.getEncoded();
  Assert.assertArrayEquals(encodedScts, encoded2);
}
 
Example #16
Source File: CrlStreamParserTest.java    From xipki with Apache License 2.0 6 votes vote down vote up
@Test
public void parseCrl1() throws Exception {
  File crlFile = new File("src/test/resources/crls/crl-1/subcawithcrl1.crl");
  Certificate issuerSigner = parseCert("src/test/resources/crls/crl-1/ca.crt");

  CrlStreamParser parser = new CrlStreamParser(crlFile);
  Assert.assertEquals("version", 1, parser.getVersion());
  Assert.assertEquals("CRL number", BigInteger.valueOf(3), parser.getCrlNumber());

  Assert.assertTrue("signature", parser.verifySignature(issuerSigner.getSubjectPublicKeyInfo()));

  int numRevokedCerts = 0;

  try (RevokedCertsIterator iterator = parser.revokedCertificates()) {
    while (iterator.hasNext()) {
      iterator.next();
      numRevokedCerts++;
    }
  }

  Assert.assertEquals("#revokedCertificates", 1, numRevokedCerts);
}
 
Example #17
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets OCSP URLs associated with the certificate.
 *
 * @param bcCert Bouncy Castle Certificate
 * @return a set of OCSP URLs
 */
private Set<String> getOcspUrls(Certificate bcCert) throws IOException
{
  TBSCertificate bcTbsCert = bcCert.getTBSCertificate();
  Extensions bcExts = bcTbsCert.getExtensions();
  if (bcExts == null)
  {
    throw new IOException("Failed to get Tbs Certificate.");
  }

  Set<String> ocsp = new HashSet<>();
  for (Enumeration<?> en = bcExts.oids(); en.hasMoreElements(); )
  {
    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) en.nextElement();
    Extension bcExt = bcExts.getExtension(oid);
    if (Extension.authorityInfoAccess.equals(bcExt.getExtnId()))
    {
      // OCSP URLS are included in authorityInfoAccess
      DLSequence seq = (DLSequence) bcExt.getParsedValue();
      for (ASN1Encodable asn : seq)
      {
        ASN1Encodable[] pairOfAsn = ((DLSequence) asn).toArray();
        if (pairOfAsn.length == 2)
        {
          ASN1ObjectIdentifier key = (ASN1ObjectIdentifier) pairOfAsn[0];
          if (OIDocsp.equals(key))
          {
            // ensure OCSP and not CRL
            GeneralName gn = GeneralName.getInstance(pairOfAsn[1]);
            ocsp.add(gn.getName().toString());
          }
        }
      }
    }
  }
  return ocsp;
}
 
Example #18
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a pair of Issuer and Subject certificates
 *
 * @param bcChain a list of bouncy castle Certificate
 * @return a list of paif of Issuer and Subject certificates
 */
private List<SFPair<Certificate, Certificate>> getPairIssuerSubject(
    List<Certificate> bcChain) throws CertificateException
{
  List<SFPair<Certificate, Certificate>> pairIssuerSubject = new ArrayList<>();
  for (int i = 0, len = bcChain.size(); i < len; ++i)
  {
    Certificate bcCert = bcChain.get(i);
    if (bcCert.getIssuer().equals(bcCert.getSubject()))
    {
      continue; // skipping ROOT CA
    }
    if (i < len - 1)
    {
      pairIssuerSubject.add(SFPair.of(bcChain.get(i + 1), bcChain.get(i)));
    }
    else
    {
      // no root CA certificate is attached in the certificate chain, so
      // getting one from the root CA from JVM.
      Certificate issuer = ROOT_CA.get(bcCert.getIssuer().hashCode());
      if (issuer == null)
      {
        throw new CertificateException(
            "Failed to find the root CA.",
            new SFOCSPException(OCSPErrorCode.NO_ROOTCA_FOUND, "Failed to find the root CA."));
      }
      pairIssuerSubject.add(SFPair.of(issuer, bcChain.get(i)));
    }
  }
  return pairIssuerSubject;
}
 
Example #19
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Converts X509Certificate to Bouncy Castle Certificate
 *
 * @param chain an array of X509Certificate
 * @return a list of Bouncy Castle Certificate
 */
private List<Certificate> convertToBouncyCastleCertificate(
    X509Certificate[] chain) throws CertificateEncodingException
{
  final List<Certificate> bcChain = new ArrayList<>();
  for (X509Certificate cert : chain)
  {
    bcChain.add(Certificate.getInstance(cert.getEncoded()));
  }
  return bcChain;
}
 
Example #20
Source File: SFTrustManager.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
/**
 * Executes the revocation status checks for all chained certificates
 *
 * @param pairIssuerSubjectList a list of pair of issuer and subject certificates.
 * @throws CertificateException raises if any error occurs.
 */
private void executeRevocationStatusChecks(
    List<SFPair<Certificate, Certificate>> pairIssuerSubjectList, String peerHost)
throws CertificateException
{
  long currentTimeSecond = new Date().getTime() / 1000L;
  for (SFPair<Certificate, Certificate> pairIssuerSubject : pairIssuerSubjectList)
  {
    executeOneRevocationStatusCheck(pairIssuerSubject, currentTimeSecond, peerHost);
  }
}
 
Example #21
Source File: CrlStreamParserTest.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static Certificate parseCert(String fileName)
    throws IOException, CertificateEncodingException {
  try {
    return Certificate.getInstance(
        X509Util.toDerEncoded(Files.readAllBytes(Paths.get(fileName))));
  } catch (RuntimeException ex) {
    throw new CertificateEncodingException("error decoding certificate: " + ex.getMessage());
  }
}
 
Example #22
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void base64() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, CryptoException, CspException {
    Security.addProvider(new BouncyCastleProvider());
    String sk = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" +
            "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" +
            "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" +
            "C8r6EmyE";
    KeyFactory keyf = keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(sk));
    BCECPrivateKey priKey = (BCECPrivateKey) keyf.generatePrivate(priPKCS8);
    System.out.println("16进制私钥:" + priKey.getD().toString(16));

    String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath();
    byte[] idBytes = FileUtils.readFileBytes(cert_path);
    Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
    byte[] pb = certificate.getTBSCertificate().getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

    System.out.println(certificate.getSubject());
    System.out.println("tbs 公钥" + Hex.toHexString(pb));
    System.out.println("公钥:" + Hex.toHexString(publickey));
    System.out.println("公钥长度:" + publickey.length);


    SM2 sm2 = new SM2();
    byte[] v = sm2.sign(priKey.getD().toByteArray(), "123".getBytes());
    System.out.println(sm2.verify(publickey, v, "123".getBytes()));

}
 
Example #23
Source File: Msp.java    From julongchain with Apache License 2.0 5 votes vote down vote up
public IIdentity deserializeIdentityInternal(byte[] serializedIdentity) throws MspException {
    Certificate cert = Certificate.getInstance(serializedIdentity);
    byte[] pbBytes = cert.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    IKey certPubK = null;
    try {
        certPubK = csp.keyImport(pbBytes, new SM2PublicKeyImportOpts(true));
    } catch (JulongChainException e) {
        throw new MspException(e.getMessage());
    }
    IIdentity identity = new Identity(cert, certPubK, this);
    return identity;
}
 
Example #24
Source File: ExtendCmd.java    From julongchain with Apache License 2.0 5 votes vote down vote up
private CaHelper getCA(String caDir, OrgSpec spec, String name) throws JulongChainException {
    IKey privKey = CspHelper.loadPrivateKey(caDir);
    Certificate cert = CaHelper.loadCertificateSM2(caDir);
    NodeSpec ca = spec.getCa();
    return new CaHelper(
            name,
            ca.getCountry(),
            ca.getProvince(),
            ca.getLocality(),
            ca.getOrganizationalUnit(),
            ca.getStreetAddress(),
            ca.getPostalCode(),
            privKey,
            cert);
}
 
Example #25
Source File: MspHelper.java    From julongchain with Apache License 2.0 5 votes vote down vote up
private static void x509Export(String path, Certificate cert) throws JulongChainException {
    try {
        pemExport(path, "CERTIFICATE", cert.getEncoded());
    } catch (Exception e) {
        throw new JulongChainException("An error occurred on x509Export:" + e.getMessage());
    }
}
 
Example #26
Source File: Msp.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
 * 获取唯一有效的验证证书链
 *
 * @param certificate
 * @param isIntermediateChain
 * @return
 * @throws MspException
 */
public X509Certificate[] getUniqueValidationChain(Certificate certificate, boolean isIntermediateChain) throws MspException {
    X509Certificate[] chains = new X509Certificate[rootCerts.length];
    for (int i = 0; i < rootCerts.length; i++) {
        IIdentity identity = rootCerts[i];
        if (identity instanceof Identity) {
            try {
                X509Certificate x509Certificate = CryptoUtil.getX509Certificate(((Identity) identity).getCertificate().getEncoded());
                chains[i] = x509Certificate;
            } catch (Exception e) {
                throw new MspException(e.getMessage());
            }
        }
    }
    return chains;
}
 
Example #27
Source File: ScepUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static List<X509Cert> getCertsFromSignedData(SignedData signedData)
    throws CertificateException {
  Args.notNull(signedData, "signedData");
  ASN1Set set = signedData.getCertificates();
  if (set == null) {
    return Collections.emptyList();
  }

  final int n = set.size();
  if (n == 0) {
    return Collections.emptyList();
  }

  List<X509Cert> certs = new LinkedList<>();

  X509Cert eeCert = null;
  for (int i = 0; i < n; i++) {
    X509Cert cert;
    try {
      cert = new X509Cert(Certificate.getInstance(set.getObjectAt(i)));
    } catch (IllegalArgumentException ex) {
      throw new CertificateException(ex);
    }

    if (eeCert == null && cert.getBasicConstraints() == -1) {
      eeCert = cert;
    } else {
      certs.add(cert);
    }
  }

  if (eeCert != null) {
    certs.add(0, eeCert);
  }

  return certs;
}
 
Example #28
Source File: CaHelper.java    From julongchain with Apache License 2.0 5 votes vote down vote up
public CaHelper(String name,
                String country,
                String province,
                String locality,
                String organizationalUnit,
                String streetAddress,
                String postalCode,
                IKey signer,
                Certificate signCert) {
    this.mName = name;
    this.mCountry = country;
    this.mProvince = province;
    this.mLocality = locality;
    this.mOrganizationalUnit = organizationalUnit;
    this.mStreetAddress = streetAddress;
    this.mPostalCode = postalCode;
    this.mSigner = signer;
    this.mSignCert = signCert;
}
 
Example #29
Source File: Msp.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
 * 解析x509证书
 *
 * @param idBytes
 * @return
 * @throws IOException
 * @throws MspException
 */
public Certificate getCertFromPem(byte[] idBytes) throws IOException, MspException {
    Certificate certificate = null;
    if (idBytes == null) {
        throw new MspException("GetCertFrom Pem error the idBytes is null");
    }
    certificate = Certificate.getInstance(new PemReader
            (new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
    return certificate;
}
 
Example #30
Source File: XiOCSPReqBuilder.java    From xipki with Apache License 2.0 5 votes vote down vote up
public OCSPRequest build(ContentSigner signer, Certificate[] chain) throws OCSPException {
  if (signer == null) {
    throw new IllegalArgumentException("no signer specified");
  }

  return generateRequest(signer, chain);
}