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

The following examples show how to use org.bouncycastle.pkcs.PKCS10CertificationRequest#getSubjectPublicKeyInfo() . 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: 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 2
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 3
Source File: CaEmulator.java    From xipki with Apache License 2.0 5 votes vote down vote up
private boolean verifyPopo(CertificationRequest csr) {
  Args.notNull(csr, "csr");
  try {
    PKCS10CertificationRequest p10Req = new PKCS10CertificationRequest(csr);
    SubjectPublicKeyInfo pkInfo = p10Req.getSubjectPublicKeyInfo();
    PublicKey pk = generatePublicKey(pkInfo);

    ContentVerifierProvider cvp = getContentVerifierProvider(pk);
    return p10Req.isSignatureValid(cvp);
  } catch (InvalidKeyException | PKCSException | InvalidKeySpecException ex) {
    LOG.error("could not validate POPO of CSR", ex);
    return false;
  }
}
 
Example 4
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 5
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);

}
 
Example 6
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateCSR() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException,
    OperatorCreationException, PKCSException {
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "DN001";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  CertificateSignRequest.Builder builder =
      new CertificateSignRequest.Builder()
          .setSubject(subject)
          .setScmID(scmID)
          .setClusterID(clusterID)
          .setKey(keyPair)
          .setConfiguration(conf);
  PKCS10CertificationRequest csr = builder.build();

  // Check the Subject Name is in the expected format.
  String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(),
      subject, scmID, clusterID);
  Assert.assertEquals(csr.getSubject().toString(), dnName);

  // Verify the public key info match
  byte[] encoded = keyPair.getPublic().getEncoded();
  SubjectPublicKeyInfo subjectPublicKeyInfo =
      SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded));
  SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo();
  Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo);

  // Verify CSR with attribute for extensions
  Assert.assertEquals(1, csr.getAttributes().length);
  Extensions extensions = SecurityUtil.getPkcs9Extensions(csr);

  // Verify key usage extension
  Extension keyUsageExt = extensions.getExtension(Extension.keyUsage);
  Assert.assertEquals(true, keyUsageExt.isCritical());


  // Verify San extension not set
  Assert.assertEquals(null,
      extensions.getExtension(Extension.subjectAlternativeName));

  // Verify signature in CSR
  ContentVerifierProvider verifierProvider =
      new JcaContentVerifierProviderBuilder().setProvider(securityConfig
          .getProvider()).build(csr.getSubjectPublicKeyInfo());
  Assert.assertEquals(true, csr.isSignatureValid(verifierProvider));
}
 
Example 7
Source File: TestCertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 4 votes vote down vote up
@Test
public void testGenerateCSRwithSan() throws NoSuchProviderException,
    NoSuchAlgorithmException, SCMSecurityException,
    OperatorCreationException, PKCSException {
  String clusterID = UUID.randomUUID().toString();
  String scmID = UUID.randomUUID().toString();
  String subject = "DN001";
  HDDSKeyGenerator keyGen =
      new HDDSKeyGenerator(securityConfig.getConfiguration());
  KeyPair keyPair = keyGen.generateKey();

  CertificateSignRequest.Builder builder =
      new CertificateSignRequest.Builder()
          .setSubject(subject)
          .setScmID(scmID)
          .setClusterID(clusterID)
          .setKey(keyPair)
          .setConfiguration(conf);

  // Multi-home
  builder.addIpAddress("192.168.1.1");
  builder.addIpAddress("192.168.2.1");
  builder.addServiceName("OzoneMarketingCluster003");

  builder.addDnsName("dn1.abc.com");

  PKCS10CertificationRequest csr = builder.build();

  // Check the Subject Name is in the expected format.
  String dnName = String.format(SecurityUtil.getDistinguishedNameFormat(),
      subject, scmID, clusterID);
  Assert.assertEquals(csr.getSubject().toString(), dnName);

  // Verify the public key info match
  byte[] encoded = keyPair.getPublic().getEncoded();
  SubjectPublicKeyInfo subjectPublicKeyInfo =
      SubjectPublicKeyInfo.getInstance(ASN1Sequence.getInstance(encoded));
  SubjectPublicKeyInfo csrPublicKeyInfo = csr.getSubjectPublicKeyInfo();
  Assert.assertEquals(csrPublicKeyInfo, subjectPublicKeyInfo);

  // Verify CSR with attribute for extensions
  Assert.assertEquals(1, csr.getAttributes().length);
  Extensions extensions = SecurityUtil.getPkcs9Extensions(csr);

  // Verify key usage extension
  Extension sanExt = extensions.getExtension(Extension.keyUsage);
  Assert.assertEquals(true, sanExt.isCritical());

  verifyServiceId(extensions);

  // Verify signature in CSR
  ContentVerifierProvider verifierProvider =
      new JcaContentVerifierProviderBuilder().setProvider(securityConfig
          .getProvider()).build(csr.getSubjectPublicKeyInfo());
  Assert.assertEquals(true, csr.isSignatureValid(verifierProvider));
}