Java Code Examples for org.bouncycastle.operator.jcajce.JcaContentSignerBuilder#build()

The following examples show how to use org.bouncycastle.operator.jcajce.JcaContentSignerBuilder#build() . 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: 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 2
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 3
Source File: CertificateManager.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public void generateCA() throws NoSuchAlgorithmException, IOException, OperatorCreationException, InvalidAlgorithmParameterException {
    ECGenParameterSpec ecGenSpec = new ECGenParameterSpec("secp384k1");
    KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(ecGenSpec, SecurityHelper.newRandom());
    KeyPair pair = generator.generateKeyPair();
    LocalDateTime startDate = LocalDate.now().atStartOfDay();

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, orgName.concat(" CA"));
    subject.addRDN(BCStyle.O, orgName);

    X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
            subject.build(),
            new BigInteger("0"),
            Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
            Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
            new X500Name("CN=ca"),
            SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded()));
    JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
    ContentSigner signer = csBuilder.build(pair.getPrivate());
    ca = builder.build(signer);
    caKey = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
}
 
Example 4
Source File: JCEUtils.java    From java-11-examples with Apache License 2.0 6 votes vote down vote up
public static X509Certificate createSignedCertificate(String issuerName, String subjectName, Date notBefore, Long duration, TimeUnit timeUnit, PublicKey publicKey, PrivateKey privateKey) throws PKIException {
    try {
        X500Name issuer = new X500Name(CN_NAME + issuerName);
        BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
        Date notAfter = new Date(notBefore.getTime() + timeUnit.toMillis(duration));
        X500Name subject = new X500Name(CN_NAME + subjectName);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, publicKeyInfo);
        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(SHA256_RSA);
        ContentSigner signer = jcaContentSignerBuilder.build(privateKey);
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509, BC_PROVIDER);
        byte[] certBytes = certBuilder.build(signer).getEncoded();
        return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certBytes));
    } catch (Exception e) {
        throw new PKIException(e);
    }
}
 
Example 5
Source File: IdentityController.java    From Spark with Apache License 2.0 6 votes vote down vote up
public X509Certificate createSelfSignedCertificate(KeyPair keyPair) throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, OperatorCreationException, CertificateException {

        long serial = System.currentTimeMillis();
        SubjectPublicKeyInfo keyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        X500Name name = new X500Name(createX500NameString());
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(name, 
                                                                            BigInteger.valueOf(serial), 
                                                                            new Date(System.currentTimeMillis() - 1000000000), 
                                                                            new Date(System.currentTimeMillis() + 1000000000),
                                                                            name, 
                                                                            keyInfo
                                                                            );
        certBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); 
        certBuilder.addExtension(Extension.keyUsage,         true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certBuilder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
    
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256withRSA");
        ContentSigner signer = csBuilder.build(keyPair.getPrivate());
        X509CertificateHolder certHolder = certBuilder.build(signer);
        X509Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
        
        return cert;
    }
 
Example 6
Source File: CertificateAutogenTask.java    From Launcher with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Path process(Path inputFile) throws IOException {
    if (signedDataGenerator != null) return inputFile;
    try {
        LogHelper.warning("You are using an auto-generated certificate (sign.enabled false). It is not good");
        LogHelper.warning("It is highly recommended that you use the correct certificate (sign.enabled true)");
        LogHelper.warning("You can use GenerateCertificateModule or your own certificate.");
        X500NameBuilder subject = new X500NameBuilder();
        subject.addRDN(BCStyle.CN, server.config.projectName.concat(" Autogenerated"));
        subject.addRDN(BCStyle.O, server.config.projectName);
        LocalDateTime startDate = LocalDate.now().atStartOfDay();
        X509v3CertificateBuilder builder = new X509v3CertificateBuilder(
                subject.build(),
                new BigInteger("0"),
                Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),
                Date.from(startDate.plusDays(3650).atZone(ZoneId.systemDefault()).toInstant()),
                new X500Name("CN=ca"),
                SubjectPublicKeyInfo.getInstance(server.publicKey.getEncoded()));
        builder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(KeyPurposeId.id_kp_codeSigning));
        //builder.addExtension(Extension.keyUsage, false, new KeyUsage(1));
        JcaContentSignerBuilder csBuilder = new JcaContentSignerBuilder("SHA256WITHECDSA");
        ContentSigner signer = csBuilder.build(server.privateKey);
        bcCertificate = builder.build(signer);
        certificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(bcCertificate);
        ArrayList<Certificate> chain = new ArrayList<>();
        chain.add(certificate);
        signedDataGenerator = SignHelper.createSignedDataGenerator(server.privateKey, certificate, chain, "SHA256WITHECDSA");
    } catch (OperatorCreationException | CMSException | CertificateException e) {
        LogHelper.error(e);
    }
    return inputFile;
}
 
Example 7
Source File: TestUtil.java    From fabric-chaincode-java with Apache License 2.0 5 votes vote down vote up
/**
 * Function to create a certificate with dummy attributes
 *
 * @param attributeValue {String} value to be written to the identity attributes
 *                       section of the certificate
 * @return encodedCert {String} encoded certificate with re-written attributes
 */
public static String createCertWithIdentityAttributes(final String attributeValue) throws Exception {

    // Use existing certificate with attributes
    final byte[] decodedCert = Base64.getDecoder().decode(CERT_MULTIPLE_ATTRIBUTES);
    // Create a certificate holder and builder
    final X509CertificateHolder certHolder = new X509CertificateHolder(decodedCert);
    final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(certHolder);

    // special OID used by Fabric to save attributes in x.509 certificates
    final String fabricCertOid = "1.2.3.4.5.6.7.8.1";
    // Write the new attribute value
    final byte[] extDataToWrite = attributeValue.getBytes();
    certBuilder.replaceExtension(new ASN1ObjectIdentifier(fabricCertOid), true, extDataToWrite);

    // Create a privateKey
    final KeyPairGenerator generator = KeyPairGenerator.getInstance("EC");
    generator.initialize(384);
    final KeyPair keyPair = generator.generateKeyPair();

    // Create and build the Content Signer
    final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256withECDSA");
    final ContentSigner contentSigner = contentSignerBuilder.build(keyPair.getPrivate());
    // Build the Certificate from the certificate builder
    final X509CertificateHolder builtCert = certBuilder.build(contentSigner);
    final X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X509")
            .generateCertificate(new ByteArrayInputStream(builtCert.getEncoded()));
    final String encodedCert = Base64.getEncoder().encodeToString(certificate.getEncoded());
    return encodedCert;
}
 
Example 8
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 9
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 10
Source File: SignatureBlockGenerator.java    From fdroidclient with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sign the given content using the private and public keys from the keySet, and return the encoded CMS (PKCS#7) data.
 * Use of direct signature and DER encoding produces a block that is verifiable by Android recovery programs.
 */
public static byte[] generate(KeySet keySet, byte[] content) {
    try {
        List certList = new ArrayList();
        CMSTypedData msg = new CMSProcessableByteArray(content);

        certList.add(keySet.getPublicKey());

        Store certs = new JcaCertStore(certList);

        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(keySet.getSignatureAlgorithm()).setProvider("BC");
        ContentSigner sha1Signer = jcaContentSignerBuilder.build(keySet.getPrivateKey());

        JcaDigestCalculatorProviderBuilder jcaDigestCalculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder().setProvider("BC");
        DigestCalculatorProvider digestCalculatorProvider = jcaDigestCalculatorProviderBuilder.build();

        JcaSignerInfoGeneratorBuilder jcaSignerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder(digestCalculatorProvider);
        jcaSignerInfoGeneratorBuilder.setDirectSignature(true);
        SignerInfoGenerator signerInfoGenerator = jcaSignerInfoGeneratorBuilder.build(sha1Signer, keySet.getPublicKey());

        gen.addSignerInfoGenerator(signerInfoGenerator);

        gen.addCertificates(certs);

        CMSSignedData sigData = gen.generate(msg, false);
        return sigData.toASN1Structure().getEncoded("DER");

    } catch (Exception x) {
        throw new RuntimeException(x.getMessage(), x);
    }
}
 
Example 11
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 12
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 13
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);

    }

}
 
Example 14
Source File: SslClientCertificateImplTest.java    From hivemq-community-edition with Apache License 2.0 3 votes vote down vote up
private Certificate getCertificate(final KeyPair keyPair, final JcaX509v3CertificateBuilder certificateBuilder) throws OperatorCreationException, CertificateException {

        Security.addProvider(new BouncyCastleProvider());

        JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder("SHA256WithRSAEncryption");
        signerBuilder = signerBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);

        final ContentSigner contentSigner = signerBuilder.build(keyPair.getPrivate());

        JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
        converter = converter.setProvider(BouncyCastleProvider.PROVIDER_NAME);

        return converter.getCertificate(certificateBuilder.build(contentSigner));
    }