Java Code Examples for org.bouncycastle.operator.ContentSigner

The following examples show how to use org.bouncycastle.operator.ContentSigner. These examples are extracted from open source projects. 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 Project: hadoop-ozone   Source File: CertificateSignRequest.java    License: 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 2
Source Project: hadoop-ozone   Source File: TestDefaultProfile.java    License: 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 Project: nomulus   Source File: SelfSignedCaCertificate.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns a self-signed Certificate Authority (CA) certificate. */
static X509Certificate createCaCert(KeyPair keyPair, String fqdn, Date from, Date to)
    throws Exception {
  X500Name owner = new X500Name("CN=" + fqdn);
  ContentSigner signer =
      new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());
  X509v3CertificateBuilder builder =
      new JcaX509v3CertificateBuilder(
          owner, new BigInteger(64, RANDOM), from, to, owner, keyPair.getPublic());

  // Mark cert as CA by adding basicConstraint with cA=true to the builder
  BasicConstraints basicConstraints = new BasicConstraints(true);
  builder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

  X509CertificateHolder certHolder = builder.build(signer);
  return new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
}
 
Example 4
Source Project: Hands-On-Cryptography-with-Java   Source File: KeyStoreDemo.java    License: MIT License 6 votes vote down vote up
/**
 * It's annoying to have to wrap KeyPairs with Certificates, but this is
 * "easier" for you to know who the key belongs to.
 *
 * @param keyPair A KeyPair to wrap
 * @return A wrapped certificate with constant name
 * @throws CertificateException
 * @throws OperatorCreationException
 */
public static Certificate generateCertificate(KeyPair keyPair) throws CertificateException, OperatorCreationException {
    X500Name name = new X500Name("cn=Annoying Wrapper");
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final Date start = new Date();
    final Date until = Date.from(LocalDate.now().plus(365, ChronoUnit.DAYS).atStartOfDay().toInstant(ZoneOffset.UTC));
    final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(name,
            new BigInteger(10, new SecureRandom()), //Choose something better for real use
            start,
            until,
            name,
            subPubKeyInfo
    );
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSA").setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate());
    final X509CertificateHolder holder = builder.build(signer);

    Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider()).getCertificate(holder);
    return cert;
}
 
Example 5
/**
 * Copy of <code>org.apache.pdfbox.examples.signature.CreateSignatureBase.sign(InputStream)</code>
 * from the pdfbox examples artifact.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    try
    {
        List<Certificate> certList = new ArrayList<>();
        certList.addAll(Arrays.asList(chain));
        Store<?> certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(chain[0].getEncoded());
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(pk);
        gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        return signedData.getEncoded();
    }
    catch (GeneralSecurityException | CMSException | OperatorCreationException e)
    {
        throw new IOException(e);
    }
}
 
Example 6
public static X509Certificate generateCert(PublicKey rqPubKey, BigInteger serialNr, Credential cred) throws TechnicalConnectorException {
   try {
      X509Certificate cert = cred.getCertificate();
      X500Principal principal = cert.getSubjectX500Principal();
      Date notBefore = cert.getNotBefore();
      Date notAfter = cert.getNotAfter();
      X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, serialNr, notBefore, notAfter, principal, rqPubKey);
      int keyUsageDetails = 16 + 32;
      builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails));
      ContentSigner signer = (new JcaContentSignerBuilder(cert.getSigAlgName())).build(cred.getPrivateKey());
      X509CertificateHolder holder = builder.build(signer);
      return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder);
   } catch (OperatorCreationException | IOException | CertificateException ex) {
      throw new IllegalArgumentException(ex);
   }
}
 
Example 7
Source Project: littleca   Source File: CAImpl.java    License: 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 8
/**
 * Generates a certificate with a specific public key signed by the issuer key.
 *
 * @param dn        the subject DN
 * @param publicKey the subject public key
 * @param issuerDn  the issuer DN
 * @param issuerKey the issuer private key
 * @return the certificate
 * @throws IOException               if an exception occurs
 * @throws NoSuchAlgorithmException  if an exception occurs
 * @throws CertificateException      if an exception occurs
 * @throws NoSuchProviderException   if an exception occurs
 * @throws SignatureException        if an exception occurs
 * @throws InvalidKeyException       if an exception occurs
 * @throws OperatorCreationException if an exception occurs
 */
private static X509Certificate generateIssuedCertificate(String dn, PublicKey publicKey, String issuerDn, PrivateKey issuerKey) throws IOException, NoSuchAlgorithmException,
        CertificateException, NoSuchProviderException, SignatureException, InvalidKeyException, OperatorCreationException {
    ContentSigner sigGen = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(PROVIDER).build(issuerKey);
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    Date startDate = new Date(YESTERDAY);
    Date endDate = new Date(ONE_YEAR_FROM_NOW);

    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(
            new X500Name(issuerDn),
            BigInteger.valueOf(System.currentTimeMillis()),
            startDate, endDate,
            new X500Name(dn),
            subPubKeyInfo);

    X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider(PROVIDER)
            .getCertificate(certificateHolder);
}
 
Example 9
Source Project: Launcher   Source File: CertificateManager.java    License: GNU General Public License v3.0 6 votes vote down vote up
public X509CertificateHolder generateCertificate(String subjectName, PublicKey subjectPublicKey) throws OperatorCreationException {
    SubjectPublicKeyInfo subjectPubKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
    BigInteger serial = BigInteger.valueOf(SecurityHelper.newRandom().nextLong());
    Date startDate = Date.from(Instant.now().minus(minusHours, ChronoUnit.HOURS));
    Date endDate = Date.from(startDate.toInstant().plus(validDays, ChronoUnit.DAYS));

    X500NameBuilder subject = new X500NameBuilder();
    subject.addRDN(BCStyle.CN, subjectName);
    subject.addRDN(BCStyle.O, orgName);
    X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(ca.getSubject(), serial,
            startDate, endDate, subject.build(), subjectPubKeyInfo);

    AlgorithmIdentifier sigAlgId = ca.getSignatureAlgorithm();
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    ContentSigner sigGen = new BcECContentSignerBuilder(sigAlgId, digAlgId).build(caKey);

    return v3CertGen.build(sigGen);
}
 
Example 10
Source Project: haven-platform   Source File: CertificateGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void constructCert() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    ((Logger)LoggerFactory.getLogger(CertificateGenerator.class)).setLevel(Level.DEBUG);
    File file = new File("/tmp/dm-agent.jks");//Files.createTempFile("dm-agent", ".jks");

    KeyPair keypair = createKeypair();
    JcaX509v3CertificateBuilder cb = createRootCert(keypair);
    ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keypair.getPrivate());
    X509CertificateHolder rootCert = cb.build(signer);
    KeystoreConfig cert = CertificateGenerator.constructCert(rootCert,
      keypair.getPrivate(),
      file,
      ImmutableSet.of("test1", "test2"));
    assertNotNull(cert);
}
 
Example 11
Source Project: java-11-examples   Source File: JCEUtils.java    License: 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 12
/**
 * Create a self-signed X.509 Certificate.
 * From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
 *
 * @param dn        the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
 * @param pair      the KeyPair
 * @param days      how many days from now the Certificate is valid for
 * @param algorithm the signing algorithm, eg "SHA1withRSA"
 * @return the self-signed certificate
 * @throws CertificateException thrown if a security error or an IO error occurred.
 */
public static X509Certificate generateCertificate(String dn, KeyPair pair,
                                                  int days, String algorithm)
    throws CertificateException {

  try {
    Security.addProvider(new BouncyCastleProvider());
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(algorithm);
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privateKeyAsymKeyParam = PrivateKeyFactory.createKey(pair.getPrivate().getEncoded());
    SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(pair.getPublic().getEncoded());
    ContentSigner sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privateKeyAsymKeyParam);
    X500Name name = new X500Name(dn);
    Date from = new Date();
    Date to = new Date(from.getTime() + days * 86400000L);
    BigInteger sn = new BigInteger(64, new SecureRandom());

    X509v1CertificateBuilder v1CertGen = new X509v1CertificateBuilder(name, sn, from, to, name, subPubKeyInfo);
    X509CertificateHolder certificateHolder = v1CertGen.build(sigGen);
    return new JcaX509CertificateConverter().setProvider("BC").getCertificate(certificateHolder);
  } catch (CertificateException ce) {
    throw ce;
  } catch (Exception e) {
    throw new CertificateException(e);
  }
}
 
Example 13
Source Project: logback-gelf   Source File: X509Util.java    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
private X509Certificate build() throws NoSuchAlgorithmException,
    CertIOException, OperatorCreationException, CertificateException {

    final X500Principal issuer = new X500Principal("CN=MyCA");
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final Date from = Date.valueOf(LocalDate.now());
    final Date to = Date.valueOf(LocalDate.now().plusYears(1));
    final X509v3CertificateBuilder v3CertGen =
        new JcaX509v3CertificateBuilder(issuer, sn, from, to, issuer, keyPair.getPublic());
    final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
        extUtils.createAuthorityKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.subjectKeyIdentifier, false,
        extUtils.createSubjectKeyIdentifier(keyPair.getPublic()));
    v3CertGen.addExtension(Extension.basicConstraints, true,
        new BasicConstraints(0));
    v3CertGen.addExtension(Extension.keyUsage, true,
        new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    final ContentSigner signer = new JcaContentSignerBuilder(SIG_ALGORITHM)
        .build(keyPair.getPrivate());
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(v3CertGen.build(signer));
}
 
Example 14
Source Project: athenz   Source File: Crypto.java    License: 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 15
Source Project: PowerTunnel   Source File: CertificateHelper.java    License: MIT License 5 votes vote down vote up
private static X509Certificate signCertificate(
        X509v3CertificateBuilder certificateBuilder,
        PrivateKey signedWithPrivateKey) throws OperatorCreationException,
        CertificateException {
    ContentSigner signer = new JcaContentSignerBuilder(SIGNATURE_ALGORITHM)
            .setProvider(PROVIDER_NAME).build(signedWithPrivateKey);
    return new JcaX509CertificateConverter().setProvider(
            PROVIDER_NAME).getCertificate(certificateBuilder.build(signer));
}
 
Example 16
Source Project: besu   Source File: SelfSignedP12Certificate.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("JdkObsolete") // JcaX509v3CertificateBuilder requires java.util.Date.
private static Certificate generateSelfSignedCertificate(final KeyPair keyPair)
    throws CertIOException, GeneralSecurityException, OperatorCreationException {
  final X500Name issuer = new X500Name(distinguishedName);
  final X500Name subject = new X500Name(distinguishedName);
  final BigInteger serialNumber = new BigInteger(String.valueOf(Instant.now().toEpochMilli()));
  final X509v3CertificateBuilder v3CertificateBuilder =
      new JcaX509v3CertificateBuilder(
          issuer,
          serialNumber,
          Date.from(Instant.now()),
          Date.from(Instant.now().plus(Period.ofDays(90))),
          subject,
          keyPair.getPublic());

  // extensions
  v3CertificateBuilder.addExtension(
      Extension.basicConstraints, true, new BasicConstraints(IS_CA));
  v3CertificateBuilder.addExtension(
      Extension.subjectAlternativeName, false, getSubjectAlternativeNames());

  final ContentSigner contentSigner =
      new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(keyPair.getPrivate());

  return new JcaX509CertificateConverter()
      .setProvider(BOUNCY_CASTLE_PROVIDER)
      .getCertificate(v3CertificateBuilder.build(contentSigner));
}
 
Example 17
protected X509Certificate createCertificate(PrivateKey privateKey, X509v3CertificateBuilder x509v3CertificateBuilder)
    throws OperatorCreationException, CertificateException {
  ContentSigner contentSigner =
      new JcaContentSignerBuilder(SIGNATURE_ALGORITHM).setProvider(BouncyCastleProvider.PROVIDER_NAME)
          .build(privateKey);
  X509Certificate x509Certificate = new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME)
      .getCertificate(x509v3CertificateBuilder.build(contentSigner));
  return x509Certificate;
}
 
Example 18
private X509Certificate createCertificate() throws Exception {
    KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair();

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(
            keyPair.getPublic().getEncoded());

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

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

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

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509CertificateHolder certHolder = new X509v3CertificateBuilder(
            issuer,
            new BigInteger("1000"),
            Date.from(Instant.now()),
            Date.from(Instant.now().plusSeconds(100000)),
            subject,
            subjectPublicKeyInfo
            )
            .build(signer);
    return (X509Certificate) certificateFactory.
            generateCertificate(
                    new ByteArrayInputStream(certHolder.getEncoded()));
}
 
Example 19
@NotNull
private ContentSigner createRSAContentSigner(final KeyPair keyPair) throws Exception {
    final AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
    final AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);

    final byte[] encoded = keyPair.getPrivate().getEncoded();
    final AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(encoded);

    return new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(privateKey);
}
 
Example 20
@NotNull
private ContentSigner createECContentSigner(final KeyPair keyPair) throws Exception {
    final AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withECDSA");
    final AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);

    final byte[] encoded = keyPair.getPrivate().getEncoded();
    final AsymmetricKeyParameter privateKey = PrivateKeyFactory.createKey(encoded);

    return new BcECContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(privateKey);
}
 
Example 21
Source Project: CapturePacket   Source File: BouncyCastleSecurityProviderTool.java    License: MIT License 5 votes vote down vote up
/**
 * Creates a ContentSigner that can be used to sign certificates with the given private key and signature algorithm.
 *
 * @param certAuthorityPrivateKey the private key to use to sign certificates
 * @param signatureAlgorithm      the algorithm to use to sign certificates
 * @return a ContentSigner
 */
private static ContentSigner getCertificateSigner(PrivateKey certAuthorityPrivateKey, String signatureAlgorithm) {
    try {
        return new JcaContentSignerBuilder(signatureAlgorithm)
                .build(certAuthorityPrivateKey);
    } catch (OperatorCreationException e) {
        throw new CertificateCreationException("Unable to create ContentSigner using signature algorithm: " + signatureAlgorithm, e);
    }
}
 
Example 22
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example 23
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = ((Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE));
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example 24
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = ((Boolean)SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE)).booleanValue();
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example 25
public static X509Certificate generateCert(KeyPair pair) {
   try {
      X500Principal principal = new X500Principal(RaPropertiesLoader.getProperty("dummycert.subject"));
      Date notBefore = (new DateTime()).minusDays(1).toDate();
      Date notAfter = (new DateTime()).minusDays(1).plusMinutes(1).toDate();
      X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(principal, BigInteger.ZERO, notBefore, notAfter, principal, pair.getPublic());
      int keyUsageDetails = 16 + 32;
      builder.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsageDetails));
      ContentSigner signer = (new JcaContentSignerBuilder(RaPropertiesLoader.getProperty("dummycert.signature.algorithm"))).build(pair.getPrivate());
      X509CertificateHolder holder = builder.build(signer);
      return (new JcaX509CertificateConverter()).setProvider("BC").getCertificate(holder);
   } catch (OperatorCreationException | IOException | CertificateException ex) {
      throw new IllegalArgumentException(ex);
   }
}
 
Example 26
public byte[] sign(Credential signatureCredential, byte[] byteToSign, Map<String, Object> options) throws TechnicalConnectorException {
   byte[] contentToSign = ArrayUtils.clone(byteToSign);
   Map<String, Object> optionMap = new HashMap();
   if (options != null) {
      optionMap.putAll(options);
   }

   this.validateInput(signatureCredential, contentToSign);

   try {
      CMSTypedData content = new CMSProcessableByteArray(contentToSign);
      CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
      String signatureAlgorithm = (String)SignatureUtils.getOption("signatureAlgorithm", optionMap, "Sha1WithRSA");
      JcaSignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new JcaSignerInfoGeneratorBuilder((new JcaDigestCalculatorProviderBuilder()).build());
      ContentSigner contentSigner = (new JcaContentSignerBuilder(signatureAlgorithm)).build(signatureCredential.getPrivateKey());
      CMSAttributeTableGenerator cmsAttributeTableGenerator = (CMSAttributeTableGenerator)SignatureUtils.getOption("signedAttributeGenerator", optionMap, new DefaultSignedAttributeTableGenerator());
      signerInfoGeneratorBuilder.setSignedAttributeGenerator(cmsAttributeTableGenerator);
      generator.addSignerInfoGenerator(signerInfoGeneratorBuilder.build(contentSigner, signatureCredential.getCertificate()));
      Certificate[] certificateChain = signatureCredential.getCertificateChain();
      if (certificateChain != null && certificateChain.length > 0) {
         generator.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
      }

      boolean encapsulate = (Boolean) SignatureUtils.getOption("encapsulate", optionMap, Boolean.FALSE);
      return generator.generate(content, encapsulate).getEncoded();
   } catch (Exception var14) {
      LOG.error(var14.getMessage(), var14);
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.ERROR_SIGNATURE, var14, new Object[]{var14.getClass().getSimpleName() + " : " + var14.getMessage()});
   }
}
 
Example 27
Source Project: gmhelper   Source File: CommonUtil.java    License: 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 28
Source Project: littleca   Source File: CertUtil.java    License: 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 29
private static AttestationCertificatePath generateCertPath(KeyPair pair, String signAlg) {

        try {
            Provider bcProvider = new BouncyCastleProvider();
            //Security.addProvider(bcProvider);

            long now = System.currentTimeMillis();
            Date from = new Date(now);
            Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(1));

            X500Name dnName = new X500Name("C=ORG, O=Dummy Org, OU=Authenticator Attestation, CN=Dummy");
            BigInteger certSerialNumber = BigInteger.ZERO;

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(from);
            calendar.add(Calendar.YEAR, 1);

            ContentSigner contentSigner = new JcaContentSignerBuilder(signAlg).build(pair.getPrivate());
            JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(dnName, certSerialNumber, from, to, dnName, pair.getPublic());

            BasicConstraints basicConstraints = new BasicConstraints(false);
            certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, basicConstraints);

            X509Certificate certificate = new JcaX509CertificateConverter().setProvider(bcProvider).getCertificate(certBuilder.build(contentSigner));
            return new AttestationCertificatePath(Collections.singletonList(certificate));
        } catch (OperatorCreationException | CertificateException | CertIOException e) {
            throw new UnexpectedCheckedException(e);
        }
    }
 
Example 30
Source Project: localization_nifi   Source File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a self-signed {@link X509Certificate} suitable for use as a Certificate Authority.
 *
 * @param keyPair                 the {@link KeyPair} to generate the {@link X509Certificate} for
 * @param dn                      the distinguished name to user for the {@link X509Certificate}
 * @param signingAlgorithm        the signing algorithm to use for the {@link X509Certificate}
 * @param certificateDurationDays the duration in days for which the {@link X509Certificate} should be valid
 * @return a self-signed {@link X509Certificate} suitable for use as a Certificate Authority
 * @throws CertificateException      if there is an generating the new certificate
 */
public static X509Certificate generateSelfSignedX509Certificate(KeyPair keyPair, String dn, String signingAlgorithm, int certificateDurationDays)
        throws CertificateException {
    try {
        ContentSigner sigGen = new JcaContentSignerBuilder(signingAlgorithm).setProvider(BouncyCastleProvider.PROVIDER_NAME).build(keyPair.getPrivate());
        SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
        Date startDate = new Date();
        Date endDate = new Date(startDate.getTime() + TimeUnit.DAYS.toMillis(certificateDurationDays));

        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                reverseX500Name(new X500Name(dn)),
                getUniqueSerialNumber(),
                startDate, endDate,
                reverseX500Name(new X500Name(dn)),
                subPubKeyInfo);

        // Set certificate extensions
        // (1) digitalSignature extension
        certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment
                | KeyUsage.keyAgreement | KeyUsage.nonRepudiation | KeyUsage.cRLSign | KeyUsage.keyCertSign));

        certBuilder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));

        certBuilder.addExtension(Extension.subjectKeyIdentifier, false, new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()));

        certBuilder.addExtension(Extension.authorityKeyIdentifier, false, new JcaX509ExtensionUtils().createAuthorityKeyIdentifier(keyPair.getPublic()));

        // (2) extendedKeyUsage extension
        certBuilder.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth}));

        // Sign the certificate
        X509CertificateHolder certificateHolder = certBuilder.build(sigGen);
        return new JcaX509CertificateConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME).getCertificate(certificateHolder);
    } catch (CertIOException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateException(e);
    }
}