org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder Java Examples

The following examples show how to use org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder. 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: CsrBuilderImpl.java    From java-certificate-authority with Apache License 2.0 7 votes vote down vote up
@Override
public CsrWithPrivateKey generateRequest(final DistinguishedName dn) {
  final KeyPair pair = KeysUtil.generateKeyPair();
  try {
    final PrivateKey privateKey = pair.getPrivate();
    final PublicKey publicKey = pair.getPublic();
    final X500Name x500Name = dn.getX500Name();
    final ContentSigner signGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
        .build(privateKey);
    final PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
        x500Name, publicKey);
    final PKCS10CertificationRequest csr = builder.build(signGen);
    return new CsrWithPrivateKeyImpl(csr, privateKey);
  } catch (final OperatorCreationException e) {
    throw new CaException(e);
  }
}
 
Example #2
Source File: TestDefaultProfile.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an CSR with the extension specified.
 * This function is used to get an Invalid CSR and test that PKI profile
 * rejects these invalid extensions, Hence the function name, by itself it
 * is a well formed CSR, but our PKI profile will treat it as invalid CSR.
 *
 * @param kPair - Key Pair.
 * @return CSR  - PKCS10CertificationRequest
 * @throws OperatorCreationException - on Error.
 */
private PKCS10CertificationRequest getInvalidCSR(KeyPair kPair,
    Extensions extensions) throws OperatorCreationException {
  X500NameBuilder namebuilder =
      new X500NameBuilder(X500Name.getDefaultStyle());
  namebuilder.addRDN(BCStyle.CN, "invalidCert");
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(namebuilder.build(),
          keyPair.getPublic());
  p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
      extensions);
  JcaContentSignerBuilder csBuilder =
      new JcaContentSignerBuilder(this.securityConfig.getSignatureAlgo());
  ContentSigner signer = csBuilder.build(keyPair.getPrivate());
  return p10Builder.build(signer);
}
 
Example #3
Source File: CertificateSignRequest.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
private PKCS10CertificationRequest generateCSR() throws
    OperatorCreationException {
  X500Name dnName = SecurityUtil.getDistinguishedName(subject, scmID,
      clusterID);
  PKCS10CertificationRequestBuilder p10Builder =
      new JcaPKCS10CertificationRequestBuilder(dnName, keyPair.getPublic());

  ContentSigner contentSigner =
      new JcaContentSignerBuilder(config.getSignatureAlgo())
          .setProvider(config.getProvider())
          .build(keyPair.getPrivate());

  if (extensions != null) {
    p10Builder.addAttribute(
        PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensions);
  }
  return p10Builder.build(contentSigner);
}
 
Example #4
Source File: CAImpl.java    From littleca with Apache License 2.0 6 votes vote down vote up
@Override
public PKCS10CertificationRequest makeUserCertReq(PublicKey publicKey, String userDN, String signAlg) throws CertException {
    try {
        PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(new X500Name(userDN)
                ,SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()));
        if(null==signAlg) {
        	signAlg=DEFAULT_SIGN_ALG;
        }
        JcaContentSignerBuilder jcaBuilder = new JcaContentSignerBuilder(signAlg);
        jcaBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
        ContentSigner contentSigner = jcaBuilder.build(privateKey);
        PKCS10CertificationRequest certificationRequest = builder.build(contentSigner);
        return certificationRequest;
    } catch (Exception e) {
    	throw new CertException("makeUserCertReq failed",e);
    } 
}
 
Example #5
Source File: IdentityController.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Creates Certificate Signing Request.
 * 
 * @throws IOException
 * @throws OperatorCreationException
 */
public PKCS10CertificationRequest createCSR(KeyPair keyPair) throws IOException, OperatorCreationException {

    X500Principal principal = new X500Principal(createX500NameString());
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(principal, keyPair.getPublic());
   
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
    PKCS10CertificationRequest csr = p10Builder.build(signer);
   
        return csr;
}
 
Example #6
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static PKCS10CertificationRequestBuilder addSubjectAlternativeNames(PKCS10CertificationRequestBuilder p10Builder, List<String> sanList)
        throws IOException {
    GeneralName[] generalNames = sanList
            .stream()
            .map(address -> new GeneralName(GeneralName.dNSName, address))
            .toArray(GeneralName[]::new);

    GeneralNames subjectAltNames = new GeneralNames(generalNames);
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
}
 
Example #7
Source File: PkiUtil.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static PKCS10CertificationRequest generateCsrWithName(KeyPair identity, String name, List<String> sanList) throws Exception {
    X500Principal principal = new X500Principal(name);
    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(principal, identity.getPublic());

    if (!CollectionUtils.isEmpty(sanList)) {
        p10Builder = addSubjectAlternativeNames(p10Builder, sanList);
    }

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
    ContentSigner signer = csBuilder.build(identity.getPrivate());
    return p10Builder.build(signer);
}
 
Example #8
Source File: Actions.java    From xipki with Apache License 2.0 5 votes vote down vote up
private PKCS10CertificationRequest generateRequest(ConcurrentContentSigner signer,
    SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn,
    Map<ASN1ObjectIdentifier, ASN1Encodable> attributes) throws XiSecurityException {
  Args.notNull(signer, "signer");
  Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo");
  Args.notNull(subjectDn, "subjectDn");
  PKCS10CertificationRequestBuilder csrBuilder =
      new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo);
  if (CollectionUtil.isNotEmpty(attributes)) {
    for (ASN1ObjectIdentifier attrType : attributes.keySet()) {
      csrBuilder.addAttribute(attrType, attributes.get(attrType));
    }
  }

  ConcurrentBagEntrySigner signer0;
  try {
    signer0 = signer.borrowSigner();
  } catch (NoIdleSignerException ex) {
    throw new XiSecurityException(ex.getMessage(), ex);
  }

  try {
    return csrBuilder.build(signer0.value());
  } finally {
    signer.requiteSigner(signer0);
  }
}
 
Example #9
Source File: MyUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateRequest(PrivateKey privatekey,
    SubjectPublicKeyInfo subjectPublicKeyInfo, X500Name subjectDn,
    String challengePassword, List<Extension> extensions)
    throws OperatorCreationException {
  Args.notNull(privatekey, "privatekey");
  Args.notNull(subjectPublicKeyInfo, "subjectPublicKeyInfo");
  Args.notNull(subjectDn, "subjectDn");

  Map<ASN1ObjectIdentifier, ASN1Encodable> attributes =
      new HashMap<ASN1ObjectIdentifier, ASN1Encodable>();

  if (StringUtil.isNotBlank(challengePassword)) {
    DERPrintableString asn1Pwd = new DERPrintableString(challengePassword);
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, asn1Pwd);
  }

  if (CollectionUtil.isNotEmpty(extensions)) {
    Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
    attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, asn1Extensions);
  }

  PKCS10CertificationRequestBuilder csrBuilder =
      new PKCS10CertificationRequestBuilder(subjectDn, subjectPublicKeyInfo);

  if (attributes != null) {
    for (ASN1ObjectIdentifier attrType : attributes.keySet()) {
      csrBuilder.addAttribute(attrType, attributes.get(attrType));
    }
  }

  ContentSigner contentSigner = new JcaContentSignerBuilder(
      ScepUtil.getSignatureAlgorithm(privatekey, HashAlgo.SHA1)).build(privatekey);
  return csrBuilder.build(contentSigner);
}
 
Example #10
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static CertificationRequest genCsr(MyKeypair keypair, String subject,
    String challengePassword) throws GeneralSecurityException, OperatorCreationException {
  X500Name subjectDn = new X500Name(subject);

  PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(
      subjectDn, keypair.publicKeyInfo);

  if (challengePassword != null && !challengePassword.isEmpty()) {
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
        new DERPrintableString(challengePassword));
  }

  ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
  return csrBuilder.build(signer).toASN1Structure();
}
 
Example #11
Source File: CaClientExample.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected static CertificationRequest genCsr(MyKeypair keypair, String subject,
    String challengePassword) throws GeneralSecurityException, OperatorCreationException {
  X500Name subjectDn = new X500Name(subject);

  PKCS10CertificationRequestBuilder csrBuilder = new PKCS10CertificationRequestBuilder(
      subjectDn, keypair.publicKeyInfo);

  if (challengePassword != null && !challengePassword.isEmpty()) {
    csrBuilder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
        new DERPrintableString(challengePassword));
  }

  ContentSigner signer = buildSigner(keypair.privateKey, "SHA256");
  return csrBuilder.build(signer).toASN1Structure();
}
 
Example #12
Source File: X509Utils.java    From acme-client with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest generateCSR(String[] commonNames, KeyPair pair) throws OperatorCreationException, IOException {
	X500NameBuilder namebuilder = new X500NameBuilder(X500Name.getDefaultStyle());
	namebuilder.addRDN(BCStyle.CN, commonNames[0]);
	
	List<GeneralName> subjectAltNames = new ArrayList<>(commonNames.length);
	for (String cn:commonNames)
		subjectAltNames.add(new GeneralName(GeneralName.dNSName, cn));
	GeneralNames subjectAltName = new GeneralNames(subjectAltNames.toArray(new GeneralName[0]));         
	
	ExtensionsGenerator extGen = new ExtensionsGenerator();
	extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltName.toASN1Primitive());
	
	PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(namebuilder.build(), pair.getPublic());
	p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
	JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
	ContentSigner signer = csBuilder.build(pair.getPrivate());
	PKCS10CertificationRequest request = p10Builder.build(signer);
	return request;
}
 
Example #13
Source File: Crypto.java    From athenz with Apache License 2.0 5 votes vote down vote up
public static String generateX509CSR(PrivateKey privateKey, PublicKey publicKey,
                                     String x500Principal, GeneralName[] sanArray) throws OperatorCreationException, IOException {

    // Create Distinguished Name

    X500Principal subject = new X500Principal(x500Principal);

    // Create ContentSigner

    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder(Crypto.RSA_SHA256);
    ContentSigner signer = csBuilder.build(privateKey);

    // Create the CSR

    PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
            subject, publicKey);

    // Add SubjectAlternativeNames (SAN) if specified
    ///CLOVER:OFF
    if (sanArray != null) {
        ///CLOVER:ON
        ExtensionsGenerator extGen = new ExtensionsGenerator();
        GeneralNames subjectAltNames = new GeneralNames(sanArray);
        extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
        p10Builder.addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extGen.generate());
    }

    PKCS10CertificationRequest csr = p10Builder.build(signer);

    // write to openssl PEM format

    PemObject pemObject = new PemObject("CERTIFICATE REQUEST", csr.getEncoded());
    StringWriter strWriter;
    try (JcaPEMWriter pemWriter = new JcaPEMWriter(strWriter = new StringWriter())) {
        pemWriter.writeObject(pemObject);
    }
    return strWriter.toString();
}
 
Example #14
Source File: CertificateAuthorityClientTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
private byte[] createCSR() throws IOException, OperatorCreationException {
    KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair();

    X500Name name = new X500NameBuilder()
            .addRDN(BCStyle.CN, "issuer")
            .build();

    ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator();

    extensionsGenerator.addExtension(
            Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));


    extensionsGenerator.addExtension(
            Extension.extendedKeyUsage,
            true,
            new ExtendedKeyUsage(
                    new KeyPurposeId[] {
                            KeyPurposeId.id_kp_clientAuth,
                            KeyPurposeId.id_kp_serverAuth }
            ));

    GeneralNames subAtlNames = new GeneralNames(
            new GeneralName[]{
                    new GeneralName(GeneralName.dNSName, "test.com"),
                    new GeneralName(GeneralName.iPAddress, TEST_IP_ADDR),
            }
    );
    extensionsGenerator.addExtension(
            Extension.subjectAlternativeName, true, subAtlNames);

    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate());

    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(name, keyPair.getPublic())
            .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate());

    return PEMUtils.toPEM(csrBuilder.build(signer));
}
 
Example #15
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 #16
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 #17
Source File: CommonUtil.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static PKCS10CertificationRequest createCSR(X500Name subject, SM2PublicKey pubKey, PrivateKey priKey,
    String signAlgo) throws OperatorCreationException {
    PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(subject, pubKey);
    ContentSigner signerBuilder = new JcaContentSignerBuilder(signAlgo)
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(priKey);
    return csrBuilder.build(signerBuilder);
}
 
Example #18
Source File: PKCGenerate.java    From ofdrw with Apache License 2.0 5 votes vote down vote up
/**
 * 生成SM2密钥对的证书请求(pkcs10格式)
 *
 * @param kp      SM2密钥对
 * @param subject 证书使用者
 * @return 证书请求
 * @throws OperatorCreationException
 */
public static PKCS10CertificationRequest CertRequest(KeyPair kp, X500Name subject) throws OperatorCreationException {
    // 构造请求信息,主要是由“实体”的DN和公钥构成
    PKCS10CertificationRequestBuilder requestBuilder =
            new JcaPKCS10CertificationRequestBuilder(subject, kp.getPublic());
    // 使用“实体”私钥对请求的信息进行签名,然后组装成ASN.1对象
    return requestBuilder.build(
            new JcaContentSignerBuilder("SM3withSM2")
                    .setProvider("BC")
                    .build(kp.getPrivate()));

}
 
Example #19
Source File: CryptoPrimitives.java    From fabric-sdk-java with Apache License 2.0 4 votes vote down vote up
/**
 * generateCertificationRequest
 *
 * @param subject The subject to be added to the certificate
 * @param pair    Public private key pair
 * @return PKCS10CertificationRequest Certificate Signing Request.
 * @throws OperatorCreationException
 */

public String generateCertificationRequest(String subject, KeyPair pair)
        throws InvalidArgumentException {

    try {
        PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder(
                new X500Principal("CN=" + subject), pair.getPublic());

        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withECDSA");

        if (null != SECURITY_PROVIDER) {
            csBuilder.setProvider(SECURITY_PROVIDER);
        }
        ContentSigner signer = csBuilder.build(pair.getPrivate());

        return certificationRequestToPEM(p10Builder.build(signer));
    } catch (Exception e) {

        logger.error(e);
        throw new InvalidArgumentException(e);

    }

}