Java Code Examples for org.bouncycastle.pkcs.PKCS10CertificationRequest#getSubject()

The following examples show how to use org.bouncycastle.pkcs.PKCS10CertificationRequest#getSubject() . 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: ZTSClientTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateInstanceRefreshRequestSubDomain() {

    File privkey = new File("./src/test/resources/unit_test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);

    InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system",
            "test", privateKey, "aws", 3600);
    assertNotNull(req);

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq));

    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue()));
    assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0));
}
 
Example 2
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static String extractX509CSRSubjectField(PKCS10CertificationRequest certReq, ASN1ObjectIdentifier id) {

        X500Name x500name = certReq.getSubject();
        if (x500name == null) {
            return null;
        }
        RDN[] rdns = x500name.getRDNs(id);

        // we're only supporting a single field in Athenz certificates so
        // any other multiple value will be considered invalid

        if (rdns == null || rdns.length == 0) {
            return null;
        }

        if (rdns.length != 1) {
            throw new CryptoException("CSR Subject contains multiple values for the same field.");
        }

        return IETFUtils.valueToString(rdns[0].getFirst().getValue());
    }
 
Example 3
Source File: CertUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * 创建一个自签名的证书
 *
 * @param publicKey
 * @param privateKey
 * @param userDN
 * @param notBefore
 * @param notAfter
 * @param serialNumber
 * @param signAlg
 * @return
 * @throws CertException
 */
public static X509Certificate makeUserSelfSignCert(PublicKey publicKey, PrivateKey privateKey, String userDN,
                                                   Date notBefore, Date notAfter, BigInteger serialNumber, String signAlg) throws CertException {
    try {
        if (null == signAlg) {
            throw new CertException(signAlg + " can't be null");
        }
        X500Name issuer = new X500Name(userDN);
        //1. 创建签名
        ContentSigner signer = new JcaContentSignerBuilder(signAlg)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(privateKey);
        //2. 创建证书请求
        PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(issuer, publicKey);
        PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);

        //3. 创建证书
        //SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber,
                notBefore, notAfter, pkcs10CertificationRequest.getSubject(), pkcs10CertificationRequest.getSubjectPublicKeyInfo());

        //添加扩展信息 见 X509CertExtensions
        X509CertExtensions.buildAllExtensions(certBuilder, publicKey, publicKey);
        X509CertificateHolder holder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(holder);

    } catch (Exception e) {
        throw new CertException("makeUserSelfSignCert failed", e);
    }
}
 
Example 4
Source File: CertUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * 创建ca私钥签名证书
 *
 * @param publicKey
 * @param privateKey
 * @param issuerDN
 * @param userDN
 * @param notBefore
 * @param notAfter
 * @param serialNumber
 * @param signAlg
 * @return
 * @throws CertException
 */
public static X509Certificate makeUserCert(PublicKey publicKey, PublicKey caPublicKey, PrivateKey caPrivateKey, String issuerDN,
                                           String userDN, Date notBefore, Date notAfter, BigInteger serialNumber, String signAlg)
        throws CertException {
    try {
        if (null == signAlg) {
            throw new CertException(signAlg + " can't be null");
        }

        X500Name issuer = new X500Name(issuerDN);
        //1. 创建签名
        ContentSigner signer = new JcaContentSignerBuilder(signAlg)
                .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(caPrivateKey);
        //2. 创建证书请求
        PKCS10CertificationRequestBuilder pkcs10CertificationRequestBuilder = new JcaPKCS10CertificationRequestBuilder(new X500Name(userDN), publicKey);
        PKCS10CertificationRequest pkcs10CertificationRequest = pkcs10CertificationRequestBuilder.build(signer);
        //3. 创建证书
        //SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

        SubjectPublicKeyInfo subPubKeyInfo = pkcs10CertificationRequest.getSubjectPublicKeyInfo();
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serialNumber,
                notBefore, notAfter, pkcs10CertificationRequest.getSubject(), subPubKeyInfo);
        //添加扩展信息 见 X509CertExtensions
        X509CertExtensions.buildAllExtensions(certBuilder, publicKey, caPublicKey);
        X509CertificateHolder holder = certBuilder.build(signer);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .getCertificate(holder);
    } catch (Exception e) {
        throw new CertException("makeUserCert failed", e);
    }
}
 
Example 5
Source File: CsrImpl.java    From java-certificate-authority with Apache License 2.0 5 votes vote down vote up
public CsrImpl(final PKCS10CertificationRequest request) {
  dn = new BcX500NameDnImpl(request.getSubject());
  try {
    publicKey = new JcaPEMKeyConverter().getPublicKey(request.getSubjectPublicKeyInfo());
  } catch (final PEMException e) {
    throw new CaException(e);
  }
}
 
Example 6
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static X509Certificate selfsign(PKCS10CertificationRequest inputCSR, String publicAddress, KeyPair signKey)
        throws Exception {

    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder()
            .find("SHA256withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
            .find(sigAlgId);

    AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(signKey.getPrivate()
            .getEncoded());

    Calendar cal = Calendar.getInstance();
    Date currentTime = cal.getTime();
    cal.add(Calendar.YEAR, CERT_VALIDITY_YEAR);
    Date expiryTime = cal.getTime();

    X509v3CertificateBuilder myCertificateGenerator = new X509v3CertificateBuilder(
            new X500Name(String.format("cn=%s", publicAddress)), new BigInteger("1"), currentTime, expiryTime, inputCSR.getSubject(),
            inputCSR.getSubjectPublicKeyInfo());

    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(akp);

    X509CertificateHolder holder = myCertificateGenerator.build(sigGen);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    return (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(holder.toASN1Structure().getEncoded()));
}
 
Example 7
Source File: DefaultApprover.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
/**
 * Sign function signs a Certificate.
 * @param config - Security Config.
 * @param caPrivate - CAs private Key.
 * @param caCertificate - CA Certificate.
 * @param validFrom - Begin Da te
 * @param validTill - End Date
 * @param certificationRequest - Certification Request.
 * @param scmId - SCM id.
 * @param clusterId - Cluster id.
 * @return Signed Certificate.
 * @throws IOException - On Error
 * @throws OperatorCreationException - on Error.
 */
@SuppressWarnings("ParameterNumber")
public  X509CertificateHolder sign(
    SecurityConfig config,
    PrivateKey caPrivate,
    X509CertificateHolder caCertificate,
    Date validFrom,
    Date validTill,
    PKCS10CertificationRequest certificationRequest,
    String scmId,
    String clusterId) throws IOException, OperatorCreationException {

  AlgorithmIdentifier sigAlgId = new
      DefaultSignatureAlgorithmIdentifierFinder().find(
      config.getSignatureAlgo());
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder()
      .find(sigAlgId);

  AsymmetricKeyParameter asymmetricKP = PrivateKeyFactory.createKey(caPrivate
      .getEncoded());
  SubjectPublicKeyInfo keyInfo =
      certificationRequest.getSubjectPublicKeyInfo();

  // Get scmId and cluster Id from subject name.
  X500Name x500Name = certificationRequest.getSubject();
  String csrScmId = x500Name.getRDNs(BCStyle.OU)[0].getFirst().getValue().
      toASN1Primitive().toString();
  String csrClusterId = x500Name.getRDNs(BCStyle.O)[0].getFirst().getValue().
      toASN1Primitive().toString();

  if (!scmId.equals(csrScmId) || !clusterId.equals(csrClusterId)) {
    if (csrScmId.equalsIgnoreCase("null") &&
        csrClusterId.equalsIgnoreCase("null")) {
      // Special case to handle DN certificate generation as DN might not know
      // scmId and clusterId before registration. In secure mode registration
      // will succeed only after datanode has a valid certificate.
      String cn = x500Name.getRDNs(BCStyle.CN)[0].getFirst().getValue()
          .toASN1Primitive().toString();
      x500Name = SecurityUtil.getDistinguishedName(cn, scmId, clusterId);
    } else {
      // Throw exception if scmId and clusterId doesn't match.
      throw new SCMSecurityException("ScmId and ClusterId in CSR subject" +
          " are incorrect.");
    }
  }

  RSAKeyParameters rsa =
      (RSAKeyParameters) PublicKeyFactory.createKey(keyInfo);
  if (rsa.getModulus().bitLength() < config.getSize()) {
    throw new SCMSecurityException("Key size is too small in certificate " +
        "signing request");
  }
  X509v3CertificateBuilder certificateGenerator =
      new X509v3CertificateBuilder(
          caCertificate.getSubject(),
          // Serial is not sequential but it is monotonically increasing.
          BigInteger.valueOf(Time.monotonicNowNanos()),
          validFrom,
          validTill,
          x500Name, keyInfo);

  ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
      .build(asymmetricKP);

  return certificateGenerator.build(sigGen);

}