Java Code Examples for org.bouncycastle.asn1.x500.X500NameBuilder#build()

The following examples show how to use org.bouncycastle.asn1.x500.X500NameBuilder#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: KeyGenerator.java    From chvote-1-0 with GNU Affero General Public License v3.0 6 votes vote down vote up
private X509v3CertificateBuilder createCertificateBuilder(KeyPair keyPair) throws PropertyConfigurationException, CertIOException {
    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, propertyConfigurationService.getConfigValue(CERT_COMMON_NAME_PROPERTY));
    nameBuilder.addRDN(BCStyle.O, propertyConfigurationService.getConfigValue(CERT_ORGANISATION_PROPERTY));
    nameBuilder.addRDN(BCStyle.OU, propertyConfigurationService.getConfigValue(CERT_ORGANISATIONAL_UNIT_PROPERTY));
    nameBuilder.addRDN(BCStyle.C, propertyConfigurationService.getConfigValue(CERT_COUNTRY_PROPERTY));
    X500Name x500Name = nameBuilder.build();

    BigInteger serial = new BigInteger(CERT_SERIAL_NUMBER_BIT_SIZE, SecureRandomFactory.createPRNG());

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

    Date startDate = new Date();
    Date endDate = Date.from(startDate.toInstant().plus(propertyConfigurationService.getConfigValueAsInt(CERT_VALIDITY_DAYS_PROPERTY), ChronoUnit.DAYS));

    X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(x500Name, serial, startDate, endDate, x500Name, publicKeyInfo);

    String certFriendlyName = propertyConfigurationService.getConfigValue(CERT_PRIVATE_FRIENDLY_NAME_PROPERTY);
    certificateBuilder.addExtension(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, false, new DERBMPString(certFriendlyName));
    return certificateBuilder;
}
 
Example 2
Source File: CertificateManager.java    From Launcher with 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 3
Source File: CertificateGenerator.java    From NetBare with MIT License 5 votes vote down vote up
public KeyStore generateServer(String commonName, JKS jks,
                                      Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(SERVER_KEY_SIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded()).getSubject();
    BigInteger serial = BigInteger.valueOf(randomSerial());
    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, jks.certOrganisation());
    name.addRDN(BCStyle.OU, jks.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());
    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));
    builder.addExtension(Extension.subjectAlternativeName, false,
            new DERSequence(new GeneralName(GeneralName.dNSName, commonName)));

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType());
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(jks.alias(), keyPair.getPrivate(), jks.password(), chain);
    return result;
}
 
Example 4
Source File: CertificateHelper.java    From signer with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority, String keyStoreType)
		throws NoSuchAlgorithmException, NoSuchProviderException, CertIOException, IOException,
		OperatorCreationException, CertificateException, KeyStoreException {

	KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	nameBuilder.addRDN(BCStyle.CN, authority.commonName());
	nameBuilder.addRDN(BCStyle.O, authority.organization());
	nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

	X500Name issuer = nameBuilder.build();
	BigInteger serial = BigInteger.valueOf(initRandomSerial());
	X500Name subject = issuer;
	PublicKey pubKey = keyPair.getPublic();

	X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE, NOT_AFTER,
			subject, pubKey);

	generator.addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyIdentifier(pubKey));
	generator.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

	KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
			| KeyUsage.dataEncipherment | KeyUsage.cRLSign);
	generator.addExtension(Extension.keyUsage, false, usage);

	ASN1EncodableVector purposes = new ASN1EncodableVector();
	purposes.add(KeyPurposeId.id_kp_serverAuth);
	purposes.add(KeyPurposeId.id_kp_clientAuth);
	purposes.add(KeyPurposeId.anyExtendedKeyUsage);
	generator.addExtension(Extension.extendedKeyUsage, false, new DERSequence(purposes));

	X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

	KeyStore result = KeyStore.getInstance(keyStoreType/* , PROVIDER_NAME */);
	result.load(null, null);
	result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), new Certificate[] { cert });
	return result;
}
 
Example 5
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 6
Source File: BouncyCastleSecurityProviderTool.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
/**
 * Creates an X500Name based on the specified certificateInfo.
 *
 * @param certificateInfo information to populate the X500Name with
 * @return a new X500Name object for use as a subject or issuer
 */
private static X500Name createX500NameForCertificate(CertificateInfo certificateInfo) {
    X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);

    if (certificateInfo.getCommonName() != null) {
        x500NameBuilder.addRDN(BCStyle.CN, certificateInfo.getCommonName());
    }

    if (certificateInfo.getOrganization() != null) {
        x500NameBuilder.addRDN(BCStyle.O, certificateInfo.getOrganization());
    }

    if (certificateInfo.getOrganizationalUnit() != null) {
        x500NameBuilder.addRDN(BCStyle.OU, certificateInfo.getOrganizationalUnit());
    }

    if (certificateInfo.getEmail() != null) {
        x500NameBuilder.addRDN(BCStyle.E, certificateInfo.getEmail());
    }

    if (certificateInfo.getLocality() != null) {
        x500NameBuilder.addRDN(BCStyle.L, certificateInfo.getLocality());
    }

    if (certificateInfo.getState() != null) {
        x500NameBuilder.addRDN(BCStyle.ST, certificateInfo.getState());
    }

    if (certificateInfo.getCountryCode() != null) {
        x500NameBuilder.addRDN(BCStyle.C, certificateInfo.getCountryCode());
    }

    // TODO: Add more X.509 certificate fields as needed

    return x500NameBuilder.build();
}
 
Example 7
Source File: SM2X509CertMakerTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static X500Name buildRootCADN() {
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, "CN");
    builder.addRDN(BCStyle.O, "org.zz");
    builder.addRDN(BCStyle.OU, "org.zz");
    builder.addRDN(BCStyle.CN, "ZZ Root CA");
    return builder.build();
}
 
Example 8
Source File: SM2X509CertMakerTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
public static X500Name buildSubjectDN() {
    X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.C, "CN");
    builder.addRDN(BCStyle.O, "org.zz");
    builder.addRDN(BCStyle.OU, "org.zz");
    builder.addRDN(BCStyle.CN, "example.org");
    builder.addRDN(BCStyle.EmailAddress, "[email protected]");
    return builder.build();
}
 
Example 9
Source File: AbstractX509CertificateService.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
protected X500Name getSubject(String commonName) {
  X500NameBuilder x500NameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
  x500NameBuilder.addRDN(BCStyle.CN, commonName);
  x500NameBuilder.addRDN(BCStyle.O, _certificateAuthority.getOrganization());
  x500NameBuilder.addRDN(BCStyle.OU, _certificateAuthority.getOrganizationalUnit());
  return x500NameBuilder.build();
}
 
Example 10
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 11
Source File: X500NameUtils.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates an X500Name object from the given components.
 *
 * @param commonName
 * @param organisationUnit
 * @param organisationName
 * @param localityName
 * @param stateName
 * @param countryCode
 * @param emailAddress
 * @return X500Name object from the given components
 */
public static X500Name buildX500Name(String commonName, String organisationUnit, String organisationName,
		String localityName, String stateName, String countryCode, String emailAddress) {

	X500NameBuilder x500NameBuilder = new X500NameBuilder(KseX500NameStyle.INSTANCE);

	if (emailAddress != null) {
		x500NameBuilder.addRDN(BCStyle.E, emailAddress);
	}
	if (countryCode != null) {
		x500NameBuilder.addRDN(BCStyle.C, countryCode);
	}
	if (stateName != null) {
		x500NameBuilder.addRDN(BCStyle.ST, stateName);
	}
	if (localityName != null) {
		x500NameBuilder.addRDN(BCStyle.L, localityName);
	}
	if (organisationName != null) {
		x500NameBuilder.addRDN(BCStyle.O, organisationName);
	}
	if (organisationUnit != null) {
		x500NameBuilder.addRDN(BCStyle.OU, organisationUnit);
	}
	if (commonName != null) {
		x500NameBuilder.addRDN(BCStyle.CN, commonName);
	}

	return x500NameBuilder.build();
}
 
Example 12
Source File: CertificateHelper.java    From LittleProxy-mitm with Apache License 2.0 4 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority,
        String keyStoreType) throws NoSuchAlgorithmException,
        NoSuchProviderException, IOException,
        OperatorCreationException, CertificateException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, authority.commonName());
    nameBuilder.addRDN(BCStyle.O, authority.organization());
    nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
            | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore
            .getInstance(keyStoreType/* , PROVIDER_NAME */);
    result.load(null, null);
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), new Certificate[] { cert });
    return result;
}
 
Example 13
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 14
Source File: CertificateTool.java    From peer-os with Apache License 2.0 4 votes vote down vote up
/**
 * *********************************************************************************** Generate x509 Certificate
 *
 * @param keyPair KeyPair
 * @param certificateData CertificateData
 *
 * @return X509Certificate
 */
public X509Certificate generateSelfSignedCertificate( KeyPair keyPair, CertificateData certificateData )
{
    try
    {
        Security.addProvider( new org.bouncycastle.jce.provider.BouncyCastleProvider() );

        setDateParamaters();

        //******************************************************************************
        // Generate self-signed certificate

        X500NameBuilder builder = new X500NameBuilder( BCStyle.INSTANCE );
        builder.addRDN( BCStyle.CN, certificateData.getCommonName() );
        builder.addRDN( BCStyle.OU, certificateData.getOrganizationUnit() );
        builder.addRDN( BCStyle.O, certificateData.getOrganizationName() );
        builder.addRDN( BCStyle.C, certificateData.getCountry() );
        builder.addRDN( BCStyle.L, certificateData.getLocalityName() );
        builder.addRDN( BCStyle.ST, certificateData.getState() );
        builder.addRDN( BCStyle.EmailAddress, certificateData.getEmail() );

        BigInteger serial = BigInteger.valueOf( System.currentTimeMillis() );

        X509v3CertificateBuilder certGen =
                new JcaX509v3CertificateBuilder( builder.build(), serial, notBefore, notAfter, builder.build(),
                        keyPair.getPublic() );
        ContentSigner sigGen = new JcaContentSignerBuilder( "SHA256WithRSAEncryption" ).
                                                                                               build( keyPair
                                                                                                       .getPrivate() );
        X509Certificate x509cert = new JcaX509CertificateConverter().
                                                                            getCertificate(
                                                                                    certGen.build( sigGen ) );
        x509cert.checkValidity( new Date() );
        x509cert.verify( x509cert.getPublicKey() );
        return x509cert;
    }
    catch ( Exception t )
    {
        throw new ActionFailedException( "Failed to generate self-signed certificate!", t );
    }
}
 
Example 15
Source File: CertificateHelper.java    From AndroidHttpCapture with MIT License 4 votes vote down vote up
public static KeyStore createServerCertificate(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames,
        Authority authority, Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
            .getSubject();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());

    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, authority.certOrganisation());
    name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());

    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));

    subjectAlternativeNames.fillInto(builder);

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
    /* , PROVIDER_NAME */);
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), chain);

    return result;
}
 
Example 16
Source File: CertificateHelper.java    From CapturePacket with MIT License 4 votes vote down vote up
public static KeyStore createRootCertificate(Authority authority,
        String keyStoreType) throws NoSuchAlgorithmException,
        NoSuchProviderException, IOException,
        OperatorCreationException, CertificateException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(ROOT_KEYSIZE);

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    nameBuilder.addRDN(BCStyle.CN, authority.commonName());
    nameBuilder.addRDN(BCStyle.O, authority.organization());
    nameBuilder.addRDN(BCStyle.OU, authority.organizationalUnitName());

    X500Name issuer = nameBuilder.build();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());
    X500Name subject = issuer;
    PublicKey pubKey = keyPair.getPublic();

    X509v3CertificateBuilder generator = new JcaX509v3CertificateBuilder(
            issuer, serial, NOT_BEFORE, NOT_AFTER, subject, pubKey);

    generator.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(pubKey));
    generator.addExtension(Extension.basicConstraints, true,
            new BasicConstraints(true));

    KeyUsage usage = new KeyUsage(KeyUsage.keyCertSign
            | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
            | KeyUsage.dataEncipherment | KeyUsage.cRLSign);
    generator.addExtension(Extension.keyUsage, false, usage);

    ASN1EncodableVector purposes = new ASN1EncodableVector();
    purposes.add(KeyPurposeId.id_kp_serverAuth);
    purposes.add(KeyPurposeId.id_kp_clientAuth);
    purposes.add(KeyPurposeId.anyExtendedKeyUsage);
    generator.addExtension(Extension.extendedKeyUsage, false,
            new DERSequence(purposes));

    X509Certificate cert = signCertificate(generator, keyPair.getPrivate());

    KeyStore result = KeyStore
            .getInstance(keyStoreType/* , PROVIDER_NAME */);
    result.load(null, null);
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), new Certificate[] { cert });
    return result;
}
 
Example 17
Source File: SignerSpecificTest.java    From xades4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void signWithNationalCertificate() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", BouncyCastleProvider.PROVIDER_NAME);
    keyGen.initialize(1024, new SecureRandom());
    Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
    long add = (1L * 365L * 24L * 60L * 60L * 1000L);  //1 year
    Date validityEndDate = new Date(System.currentTimeMillis() + add);
    KeyPair keyPair = keyGen.generateKeyPair();


    X509Certificate certWithNationalSymbols;
    {
        //generate certificate with national symbols in DN
        X500NameBuilder x500NameBuilder = new X500NameBuilder();
        AttributeTypeAndValue attr = new AttributeTypeAndValue(RFC4519Style.cn, commonName);
        x500NameBuilder.addRDN(attr);
        X500Name dn = x500NameBuilder.build();
        X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(
                dn, // issuer authority
                BigInteger.valueOf(new Random().nextInt()), //serial number of certificate
                validityBeginDate, // start of validity
                validityEndDate, //end of certificate validity
                dn, // subject name of certificate
                keyPair.getPublic()); // public key of certificate
        // key usage restrictions
        builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign
                | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                | KeyUsage.dataEncipherment | KeyUsage.cRLSign));
        builder.addExtension(Extension.basicConstraints, false, new BasicConstraints(true));
        certWithNationalSymbols = new JcaX509CertificateConverter().getCertificate(builder
                .build(new JcaContentSignerBuilder("SHA256withRSA").setProvider(BouncyCastleProvider.PROVIDER_NAME).
                        build(keyPair.getPrivate())));
    }


    XadesSigner signer = new XadesBesSigningProfile(new DirectKeyingDataProvider(certWithNationalSymbols, keyPair.getPrivate())).newSigner();
    Document doc1 = getTestDocument();
    Element elemToSign = doc1.getDocumentElement();
    DataObjectDesc obj1 = new DataObjectReference('#' + elemToSign.getAttribute("Id")).withTransform(new EnvelopedSignatureTransform());
    SignedDataObjects signDataObject = new SignedDataObjects(obj1);
    signer.sign(signDataObject, doc1.getDocumentElement());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    outputDOM(doc1, baos);
    String str = new String(baos.toByteArray());
    //expected without parsing exception
    Document doc = parseDocument(new ByteArrayInputStream(baos.toByteArray()));

}
 
Example 18
Source File: CertificateHelper.java    From LittleProxy-mitm with Apache License 2.0 4 votes vote down vote up
public static KeyStore createServerCertificate(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames,
        Authority authority, Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
            .getSubject();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());

    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, authority.certOrganisation());
    name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());

    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));

    subjectAlternativeNames.fillInto(builder);

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
    /* , PROVIDER_NAME */);
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), chain);

    return result;
}
 
Example 19
Source File: CertificateHelper.java    From PowerTunnel with MIT License 4 votes vote down vote up
public static KeyStore createServerCertificate(String commonName,
        SubjectAlternativeNameHolder subjectAlternativeNames,
        Authority authority, Certificate caCert, PrivateKey caPrivKey)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        IOException, OperatorCreationException, CertificateException,
        InvalidKeyException, SignatureException, KeyStoreException {

    KeyPair keyPair = generateKeyPair(FAKE_KEYSIZE);

    X500Name issuer = new X509CertificateHolder(caCert.getEncoded())
            .getSubject();
    BigInteger serial = BigInteger.valueOf(initRandomSerial());

    X500NameBuilder name = new X500NameBuilder(BCStyle.INSTANCE);
    name.addRDN(BCStyle.CN, commonName);
    name.addRDN(BCStyle.O, authority.certOrganisation());
    name.addRDN(BCStyle.OU, authority.certOrganizationalUnitName());
    X500Name subject = name.build();

    X509v3CertificateBuilder builder = new JcaX509v3CertificateBuilder(issuer, serial, NOT_BEFORE,
            new Date(System.currentTimeMillis() + ONE_DAY), subject, keyPair.getPublic());

    builder.addExtension(Extension.subjectKeyIdentifier, false,
            createSubjectKeyIdentifier(keyPair.getPublic()));
    builder.addExtension(Extension.basicConstraints, false,
            new BasicConstraints(false));

    subjectAlternativeNames.fillInto(builder);

    X509Certificate cert = signCertificate(builder, caPrivKey);

    cert.checkValidity(new Date());
    cert.verify(caCert.getPublicKey());

    KeyStore result = KeyStore.getInstance(KeyStore.getDefaultType()
    /* , PROVIDER_NAME */);
    result.load(null, null);
    Certificate[] chain = { cert, caCert };
    result.setKeyEntry(authority.alias(), keyPair.getPrivate(),
            authority.password(), chain);

    return result;
}
 
Example 20
Source File: X509CertUtil.java    From portecle with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Generate a self-signed X509 certificate for the supplied key pair and signature algorithm.
 *
 * @return The generated certificate
 * @param sCommonName Common name certificate attribute
 * @param sOrganisationUnit Organization Unit certificate attribute
 * @param sOrganisation Organization certificate attribute
 * @param sLocality Locality certificate
 * @param sState State certificate attribute
 * @param sEmailAddress Email Address certificate attribute
 * @param sCountryCode Country Code certificate attribute
 * @param iValidity Validity period of certificate in days
 * @param sans Subject alternative names certificate extension value
 * @param publicKey Public part of key pair
 * @param privateKey Private part of key pair
 * @param signatureType Signature Type
 * @throws CryptoException If there was a problem generating the certificate
 */
public static X509Certificate generateCert(String sCommonName, String sOrganisationUnit, String sOrganisation,
    String sLocality, String sState, String sCountryCode, String sEmailAddress, int iValidity,
    Collection<GeneralName> sans, PublicKey publicKey, PrivateKey privateKey, SignatureType signatureType)
    throws CryptoException
{
	X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
	if (sEmailAddress != null)
	{
		nameBuilder.addRDN(BCStyle.E, sEmailAddress);
	}
	if (sCountryCode != null)
	{
		nameBuilder.addRDN(BCStyle.C, sCountryCode);
	}
	if (sState != null)
	{
		nameBuilder.addRDN(BCStyle.ST, sState);
	}
	if (sLocality != null)
	{
		nameBuilder.addRDN(BCStyle.L, sLocality);
	}
	if (sOrganisation != null)
	{
		nameBuilder.addRDN(BCStyle.O, sOrganisation);
	}
	if (sOrganisationUnit != null)
	{
		nameBuilder.addRDN(BCStyle.OU, sOrganisationUnit);
	}
	if (sCommonName != null)
	{
		nameBuilder.addRDN(BCStyle.CN, sCommonName);
	}

	BigInteger serial = generateX509SerialNumber();

	Date notBefore = new Date(System.currentTimeMillis());
	Date notAfter = new Date(notBefore.getTime() + ((long) iValidity * 24 * 60 * 60 * 1000));

	JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), serial,
	    notBefore, notAfter, nameBuilder.build(), publicKey);

	try
	{
		if (sans != null && !sans.isEmpty())
		{
			certBuilder.addExtension(Extension.subjectAlternativeName, false,
			    new GeneralNames(sans.toArray(new GeneralName[sans.size()])));
		}

		ContentSigner signer = new JcaContentSignerBuilder(signatureType.name()).build(privateKey);
		X509CertificateHolder certHolder = certBuilder.build(signer);

		return new JcaX509CertificateConverter().getCertificate(certHolder);
	}
	catch (CertificateException | IOException | OperatorCreationException ex)
	{
		throw new CryptoException(RB.getString("CertificateGenFailed.exception.message"), ex);
	}
}