Java Code Examples for org.bouncycastle.cert.X509v3CertificateBuilder#build()

The following examples show how to use org.bouncycastle.cert.X509v3CertificateBuilder#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: KeyStoreDemo.java    From Hands-On-Cryptography-with-Java with MIT License 7 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 2
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 7 votes vote down vote up
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 3
Source File: SelfSignedCaCertificate.java    From nomulus with 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 File: BouncyCastleSelfSignedCertGenerator.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
static String[] generate(String fqdn, KeyPair keypair, SecureRandom random, Date notBefore, Date notAfter)
        throws Exception {
    PrivateKey key = keypair.getPrivate();

    // Prepare the information required for generating an X.509 certificate.
    X500Name owner = new X500Name("CN=" + fqdn);
    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
            owner, new BigInteger(64, random), notBefore, notAfter, owner, keypair.getPublic());

    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(key);
    X509CertificateHolder certHolder = builder.build(signer);
    X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER).getCertificate(certHolder);
    cert.verify(keypair.getPublic());

    return newSelfSignedCertificate(fqdn, key, cert);
}
 
Example 5
Source File: SslInitializerTestUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Signs the given key pair with the given self signed certificate to generate a certificate with
 * the given validity range.
 *
 * @return signed public key (of the key pair) certificate
 */
public static X509Certificate signKeyPair(
    SelfSignedCaCertificate ssc, KeyPair keyPair, String hostname, Date from, Date to)
    throws Exception {
  X500Name subjectDnName = new X500Name("CN=" + hostname);
  BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis());
  X500Name issuerDnName = new X500Name(ssc.cert().getIssuerDN().getName());
  ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(ssc.key());
  X509v3CertificateBuilder v3CertGen =
      new JcaX509v3CertificateBuilder(
          issuerDnName, serialNumber, from, to, subjectDnName, keyPair.getPublic());

  X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
  return new JcaX509CertificateConverter()
      .setProvider(PROVIDER)
      .getCertificate(certificateHolder);
}
 
Example 6
Source File: CertificateGeneratorTest.java    From credhub with Apache License 2.0 5 votes vote down vote up
private X509CertificateHolder makeCert(final KeyPair certKeyPair,
                                       final PrivateKey caPrivateKey,
                                       final X500Name caDn,
                                       final X500Name subjectDn,
                                       final boolean isCa) throws OperatorCreationException, NoSuchAlgorithmException, CertIOException {
  final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(certKeyPair.getPublic()
    .getEncoded());
  final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA")
    .setProvider(BouncyCastleFipsProvider.PROVIDER_NAME)
    .build(caPrivateKey);

  final CurrentTimeProvider currentTimeProvider = new CurrentTimeProvider();

  final Instant now = Instant.from(currentTimeProvider.getInstant());

  final X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(
    caDn,
    BigInteger.TEN,
    Date.from(now),
    Date.from(now.plus(Duration.ofDays(365))),
    subjectDn,
    publicKeyInfo
  );
  x509v3CertificateBuilder
    .addExtension(Extension.basicConstraints, true, new BasicConstraints(isCa));
  return x509v3CertificateBuilder.build(contentSigner);
}
 
Example 7
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 8
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 9
Source File: TLSArtifactsGeneratorTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCertificate() throws  Exception {
    BigInteger serial = new BigInteger(100, SecureRandom.getInstanceStrong());
    X500Name self = new X500Name("cn=localhost");
    X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(
            self,
            serial,
            Date.from(Instant.now()),
            Date.from(Instant.now().plusSeconds(100000)),
            self,
            KEYPAIR.getPublic());
    X509CertificateHolder certHolder = certificateBuilder
            .build(new JcaContentSignerBuilder("SHA256WithRSA").build(KEYPAIR.getPrivate()));
    return new JcaX509CertificateConverter().getCertificate(certHolder);
}
 
Example 10
Source File: SslConfigurer.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
private X509Certificate createCert(KeyPair keyPair, String signatureAlgoritm, String domainName)
  throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, OperatorCreationException, CertificateException, IOException {
  
  RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
  RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
  
  AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find(signatureAlgoritm);
  AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
  BcContentSignerBuilder sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
  
  ASN1InputStream publicKeyStream = new ASN1InputStream(rsaPublicKey.getEncoded());
  SubjectPublicKeyInfo pubKey = SubjectPublicKeyInfo.getInstance(publicKeyStream.readObject());
  publicKeyStream.close();
  
  X509v3CertificateBuilder v3CertBuilder = new X509v3CertificateBuilder(
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      BigInteger.valueOf(Math.abs(new SecureRandom().nextInt())),
      new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30),
      new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)),
      new X500Name("CN=" + domainName + ", OU=None, O=None L=None, C=None"),
      pubKey);
  
  RSAKeyParameters keyParams = new RSAKeyParameters(true, rsaPrivateKey.getPrivateExponent(), rsaPrivateKey.getModulus());
  ContentSigner contentSigner = sigGen.build(keyParams);
  
  X509CertificateHolder certificateHolder = v3CertBuilder.build(contentSigner);
  
  JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC");
  return certConverter.getCertificate(certificateHolder);
}
 
Example 11
Source File: CertificateUtils.java    From nifi-registry with 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);
    }
}
 
Example 12
Source File: TLSCertificateBuilder.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
private X509Certificate createSelfSignedCertificate(CertType certType, KeyPair keyPair, String san) throws Exception {
    X509v3CertificateBuilder certBuilder = createCertBuilder(keyPair);

    // Basic constraints
    BasicConstraints constraints = new BasicConstraints(false);
    certBuilder.addExtension(
            Extension.basicConstraints,
            true,
            constraints.getEncoded());
    // Key usage
    KeyUsage usage = new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature);
    certBuilder.addExtension(Extension.keyUsage, false, usage.getEncoded());
    // Extended key usage
    certBuilder.addExtension(
            Extension.extendedKeyUsage,
            false,
            certType.keyUsage().getEncoded());

    if (san != null) {
        addSAN(certBuilder, san);
    }

    ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm)
            .build(keyPair.getPrivate());
    X509CertificateHolder holder = certBuilder.build(signer);

    JcaX509CertificateConverter converter = new JcaX509CertificateConverter();
    converter.setProvider(new BouncyCastleProvider());
    return converter.getCertificate(holder);
}
 
Example 13
Source File: ElasticsearchCluster.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private static Certificate genSelfSignedCert(KeyPair keyPair, String signAlgo) throws CertificateException {
  X500Name issuer = new X500Name("CN=localhost, OU=test, O=Dremio, L=Mountain View, ST=CA, C=US");
  X500Name subject = issuer; // self signed
  BigInteger serial = BigInteger.valueOf(new Random().nextInt());
  Date notBefore = new Date(System.currentTimeMillis() - (24 * 3600 * 1000));
  Date notAfter = new Date(System.currentTimeMillis() + (24 * 3600 * 1000));
  SubjectPublicKeyInfo pubkeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
  X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, pubkeyInfo);
  ContentSigner signer = newSigner(keyPair.getPrivate(), signAlgo);
  X509CertificateHolder certHolder = certBuilder.build(signer);

  Certificate cert = new JcaX509CertificateConverter().getCertificate(certHolder);
  return cert;
}
 
Example 14
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 15
Source File: Certificates.java    From icure-backend with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Creates a certificate for a healthcare party.
 */
public static X509Certificate createCertificateV3(PublicKey hcpartyPublicKey, HealthcareParty hcparty, String hcPartyEmail, PublicKey icurePublicKey, PrivateKey icurePrivateKey) throws Exception {
	//
	// Signers
	//
	Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> sAttrs = new Hashtable<>();
	Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> sOrder = new Vector<>();

	sAttrs.put(X509Principal.C, "BE");
	sAttrs.put(X509Principal.O, "Taktik");
	sAttrs.put(X509Principal.OU, "ICureCloud");
	sAttrs.put(X509Principal.EmailAddress, "[email protected]");
	sOrder.addElement(X509Principal.C);
	sOrder.addElement(X509Principal.O);
	sOrder.addElement(X509Principal.OU);
	sOrder.addElement(X509Principal.EmailAddress);

	X509Principal issuerX509Principal = new X509Principal(sOrder, sAttrs);
	X500Name issuer = new X500Name(issuerX509Principal.getName());

	//
	// Subjects
	//
	Hashtable<org.bouncycastle.asn1.ASN1ObjectIdentifier, String> attrs = new Hashtable<>();
	Vector<org.bouncycastle.asn1.ASN1ObjectIdentifier> order = new Vector<>();

	attrs.put(X509Principal.C, "BE");
	attrs.put(X509Principal.O, "organization-" + hcparty.getCompanyName());
	attrs.put(X509Principal.L, "location-" + hcparty.getId());
	attrs.put(X509Principal.CN, "cn-" + hcparty.getId());
	attrs.put(X509Principal.EmailAddress, hcPartyEmail);
	order.addElement(X509Principal.C);
	order.addElement(X509Principal.O);
	order.addElement(X509Principal.L);
	order.addElement(X509Principal.CN);
	order.addElement(X509Principal.EmailAddress);

	X509Principal subjectX509Principal = new X509Principal(order, attrs);
	X500Name subject = new X500Name(subjectX509Principal.getName());

	//
	// Other attrs
	//
	BigInteger 	serial = BigInteger.valueOf(RSAKeysUtils.random.nextLong());
	Date 		notBefore = new Date(System.currentTimeMillis() - 10000);
	Date		notAfter = new Date(System.currentTimeMillis() + 24L * 3600 * 1000);
	SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(hcpartyPublicKey.getEncoded());
	

	X509v3CertificateBuilder x509v3CertBuilder = new X509v3CertificateBuilder(issuer, serial, notBefore, notAfter, subject, spki);
	x509v3CertBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); // hcparty is not CA
	x509v3CertBuilder.addExtension(Extension.subjectKeyIdentifier, true, new SubjectKeyIdentifier(hcpartyPublicKey.getEncoded()));
	x509v3CertBuilder.addExtension(Extension.authorityKeyIdentifier, true, new AuthorityKeyIdentifierStructure(icurePublicKey));

	//
	// Create a content signer
	//
	AlgorithmIdentifier signatureAlgorithmId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
	AlgorithmIdentifier digestAlgorithmId = new DefaultDigestAlgorithmIdentifierFinder().find(signatureAlgorithmId);
	AsymmetricKeyParameter akp = PrivateKeyFactory.createKey(icurePrivateKey.getEncoded());
	ContentSigner contentSigner =  new BcRSAContentSignerBuilder(signatureAlgorithmId, digestAlgorithmId).build(akp);

	//
	// Build the certificate
	//
	X509CertificateHolder holder = x509v3CertBuilder.build(contentSigner);
	Certificate certificateStructure = holder.toASN1Structure();
	X509Certificate certificate = convertToJavaCertificate(certificateStructure);
	
	certificate.verify(icurePublicKey);

	return certificate;
}
 
Example 16
Source File: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 4 votes vote down vote up
private java.security.cert.Certificate createCertificate(X509v3CertificateBuilder certificateBuilder, ContentSigner signer) throws CertificateException, IOException {
    X509CertificateHolder certificateHolder = certificateBuilder.build(signer);

    return CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(certificateHolder.getEncoded()));
}
 
Example 17
Source File: X509V3CertGen.java    From MaxKey with Apache License 2.0 4 votes vote down vote up
public static X509Certificate genV3Certificate(String issuerName,String subjectName,Date notBefore,Date notAfter,KeyPair keyPair) throws Exception {


//issuer same as  subject is CA
BigInteger  serial=BigInteger.valueOf(System.currentTimeMillis());
 
X500Name x500Name =new X500Name(issuerName);
 
X500Name subject =new X500Name(subjectName);
 
PublicKey publicKey =keyPair.getPublic();
PrivateKey privateKey=keyPair.getPrivate();
 
SubjectPublicKeyInfo subjectPublicKeyInfo = null;  
try {
  		Object aiStream=new ASN1InputStream(publicKey.getEncoded()).readObject();
  		subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance(aiStream);  
} catch (IOException e1) {  
	e1.printStackTrace();  
}  
       
       
X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(x500Name,
		 serial,
		 notBefore,
		 notAfter,
		 subject,
		 subjectPublicKeyInfo);
 
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(privateKey); 
//certBuilder.addExtension(X509Extensions.BasicConstraints,  true, new BasicConstraints(false));
//certBuilder.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature| KeyUsage.keyEncipherment));
//certBuilder.addExtension(X509Extensions.ExtendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
//certBuilder.addExtension(X509Extensions.SubjectAlternativeName, false, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "[email protected]")));


X509CertificateHolder x509CertificateHolder = certBuilder.build(sigGen);  
   CertificateFactory certificateFactory = CertificateFactory.class.newInstance();
   InputStream inputStream = new ByteArrayInputStream(x509CertificateHolder.toASN1Structure().getEncoded());  
   X509Certificate x509Certificate = (X509Certificate) certificateFactory.engineGenerateCertificate(inputStream);  
   inputStream.close();
 
return x509Certificate;
}
 
Example 18
Source File: X509Util.java    From logback-gelf with GNU Lesser General Public License v2.1 4 votes vote down vote up
X509Certificate build(final String commonName, final String... subjectAltName)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {

    final AlgorithmIdentifier sigAlgId =
        new DefaultSignatureAlgorithmIdentifierFinder().find(SIG_ALGORITHM);
    final AlgorithmIdentifier digAlgId =
        new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    final AsymmetricKeyParameter privateKeyAsymKeyParam =
        PrivateKeyFactory.createKey(keyPair.getPrivate().getEncoded());
    final SubjectPublicKeyInfo subPubKeyInfo =
        SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
    final ContentSigner sigGen;

    final X500Name issuer = new X500Name(CA_NAME);
    final X500NameBuilder x500NameBuilder = new X500NameBuilder();
    if (commonName != null) {
        x500NameBuilder.addRDN(BCStyle.CN, commonName);
    }
    x500NameBuilder.addRDN(BCStyle.O, "snakeoil");
    final X500Name name = x500NameBuilder.build();

    final Date from = Date.valueOf(validFrom);
    final Date to = Date.valueOf(validTo);
    final BigInteger sn = new BigInteger(64, new SecureRandom());
    final X509v3CertificateBuilder v3CertGen =
        new X509v3CertificateBuilder(issuer, sn, from, to, name, subPubKeyInfo);

    if (caCertificate != null) {
        sigGen = new JcaContentSignerBuilder(SIG_ALGORITHM).build(caPrivateKey);

        final JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
        v3CertGen.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCertificate));
    } else {
        sigGen = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(privateKeyAsymKeyParam);
    }

    if (subjectAltName != null) {
        final GeneralName[] generalNames = Arrays.stream(subjectAltName)
            .map(s -> new GeneralName(GeneralName.dNSName, s))
            .toArray(GeneralName[]::new);

        v3CertGen.addExtension(Extension.subjectAlternativeName, false,
            new GeneralNames(generalNames).getEncoded());
    }

    final X509CertificateHolder certificateHolder = v3CertGen.build(sigGen);
    return new JcaX509CertificateConverter()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME)
        .getCertificate(certificateHolder);
}
 
Example 19
Source File: PacketProxyCAPerUser.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
private void generateKeyStore(String ksPath) throws Exception {
	KeyStore ks;
	KeyPair CAKeyPair = super.genRSAKeyPair();
	
	// 各ユーザ用のキーストアを作るためのテンプレートを取得
	try (InputStream input = this.getClass().getResourceAsStream("/certificates/user.ks")) {
		ks = KeyStore.getInstance("JKS");
		ks.load(input, password);
	}
	
	int serialNumber = 0;
	do {
		serialNumber = SecureRandom.getInstance("SHA1PRNG").nextInt();
	} while (serialNumber <= 0);

	String x500Name = String.format("C=PacketProxy, ST=PacketProxy, L=PacketProxy, O=PacketProxy, OU=PacketProxy CA, CN=PacketProxy per-user CA (%x)", serialNumber);
	Date from = new Date();
	Calendar cal = Calendar.getInstance();
	cal.setTime(from);
	cal.add(Calendar.YEAR, 30);
	Date to = cal.getTime();

	X509v3CertificateBuilder caRootBuilder = new X509v3CertificateBuilder(
			new X500Name(x500Name),
			BigInteger.valueOf(serialNumber),
			from,
			to,
			new X500Name(x500Name),
			SubjectPublicKeyInfo.getInstance(CAKeyPair.getPublic().getEncoded()));
       
	/* CA: X509 Extensionsの設定(CA:true, pathlen:0) */
	caRootBuilder.addExtension(Extension.basicConstraints, true, new BasicConstraints(0)); 
	
       AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
       AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
       ContentSigner signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(PrivateKeyFactory.createKey(CAKeyPair.getPrivate().getEncoded()));
       X509CertificateHolder signedRoot = caRootBuilder.build(signer);
	
	// 新しいKeyStoreの生成
	KeyStore newks = KeyStore.getInstance("JKS");
	newks.load(null, password);
	
	// 証明書と秘密鍵の登録
	CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
	newks.setKeyEntry(
			"root",
			CAKeyPair.getPrivate(),
			password,
			new Certificate[]{ certFactory.generateCertificate(new ByteArrayInputStream(signedRoot.getEncoded())) });
	
	File newksfile = new File(ksPath);
	newksfile.getParentFile().mkdirs();
	newksfile.createNewFile();
	newksfile.setWritable(false, false);
	newksfile.setWritable(true);
	newksfile.setReadable(false, false);
	newksfile.setReadable(true);
	try (FileOutputStream fos = new FileOutputStream(ksPath)) {
	    newks.store(fos, password);
	}
}
 
Example 20
Source File: CA.java    From PacketProxy with Apache License 2.0 4 votes vote down vote up
public KeyStore createKeyStore(String commonName, String[] domainNames) throws Exception {
	/* シリアルナンバーの設定 */
	MessageDigest digest = MessageDigest.getInstance("MD5");
	byte[] hash = digest.digest(commonName.getBytes());
	BigInteger templateSerial = new BigInteger(hash);

	/* Subjectの設定 */
	X500Name templateSubject =  new X500Name(createSubject(commonName));

	/* Builderの生成 */
	X509v3CertificateBuilder serverBuilder = new X509v3CertificateBuilder(
			templateIssuer,
			templateSerial,
			templateFrom,
			templateTo,
			templateSubject,
			templatePubKey);

	/* SANの設定 */
	ArrayList<ASN1Encodable> sans = new ArrayList<>();
	sans.add(new GeneralName(GeneralName.dNSName, createCNforSAN(commonName)));
	for (String domainName : domainNames) {
		//System.out.println(domainName);
		sans.add(new GeneralName(GeneralName.dNSName, domainName));
	}
	DERSequence subjectAlternativeNames = new DERSequence(sans.toArray(new ASN1Encodable[sans.size()]));
	serverBuilder.addExtension(Extension.subjectAlternativeName, false, subjectAlternativeNames);

	// 署名
	X509CertificateHolder serverHolder = serverBuilder.build(createSigner());

	/* 新しいKeyStoreを作成 */
	CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
	KeyStore ks = KeyStore.getInstance("JKS");
	ks.load(null, password);
	ks.setKeyEntry(
			aliasServer,
			keyPair.getPrivate(),
			password,
			new java.security.cert.Certificate[] {
					certFactory.generateCertificate(new ByteArrayInputStream(serverHolder.getEncoded())),
					certFactory.generateCertificate(new ByteArrayInputStream(caRootHolder.getEncoded()))
			});

	return ks;
}