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

The following examples show how to use org.bouncycastle.asn1.x500.X500NameBuilder#addRDN() . 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: 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 2
Source File: CommonUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
/**
 * 如果不知道怎么填充names,可以查看org.bouncycastle.asn1.x500.style.BCStyle这个类,
 * names的key值必须是BCStyle.DefaultLookUp中存在的(可以不关心大小写)
 *
 * @param names
 * @return
 * @throws InvalidX500NameException
 */
public static X500Name buildX500Name(Map<String, String> names) throws InvalidX500NameException {
    if (names == null || names.size() == 0) {
        throw new InvalidX500NameException("names can not be empty");
    }
    try {
        X500NameBuilder builder = new X500NameBuilder();
        Iterator itr = names.entrySet().iterator();
        BCStyle x500NameStyle = (BCStyle) BCStyle.INSTANCE;
        Map.Entry entry;
        while (itr.hasNext()) {
            entry = (Map.Entry) itr.next();
            ASN1ObjectIdentifier oid = x500NameStyle.attrNameToOID((String) entry.getKey());
            builder.addRDN(oid, (String) entry.getValue());
        }
        return builder.build();
    } catch (Exception ex) {
        throw new InvalidX500NameException(ex.getMessage(), ex);
    }
}
 
Example 3
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 4
Source File: SpkacSubject.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get subject as an X.509 name.
 *
 * @return Name
 */
public X500Name getName() {
	X500NameBuilder x500NameBuilder = new X500NameBuilder(KseX500NameStyle.INSTANCE);

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

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

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

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

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

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

	return x500NameBuilder.build();
}
 
Example 5
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 6
Source File: CertificateManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName,
                                                                    String subjectCommonName, String domain,
                                                                    String signAlgoritm, Set<String> sanDnsNames)
        throws GeneralSecurityException, IOException {

    // subjectDN
    X500NameBuilder subjectBuilder = new X500NameBuilder();
    subjectBuilder.addRDN(BCStyle.CN, subjectCommonName);

    // issuerDN
    X500NameBuilder issuerBuilder = new X500NameBuilder();
    issuerBuilder.addRDN(BCStyle.CN, issuerCommonName);

    return createX509V3Certificate(kp, days, issuerBuilder, subjectBuilder, domain, signAlgoritm, sanDnsNames);
}
 
Example 7
Source File: CertificateGeneratorTest.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private static JcaX509v3CertificateBuilder createRootCert(KeyPair keypair) throws Exception {
    X500NameBuilder ib = new X500NameBuilder(RFC4519Style.INSTANCE);
    ib.addRDN(RFC4519Style.c, "AQ");
    ib.addRDN(RFC4519Style.o, "Test");
    ib.addRDN(RFC4519Style.l, "Vostok Station");
    ib.addRDN(PKCSObjectIdentifiers.pkcs_9_at_emailAddress, "[email protected]");
    X500Name issuer = ib.build();
    return createCert(keypair, issuer, issuer);
}
 
Example 8
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 9
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 10
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 11
Source File: BouncyCastleSecurityProviderTool.java    From CapturePacket 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 12
Source File: BouncyCastleSecurityProviderTool.java    From Dream-Catcher 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 13
Source File: BouncyCastleSecurityProviderTool.java    From browserup-proxy with Apache License 2.0 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 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: DeviceCertificateManager.java    From enmasse with Apache License 2.0 4 votes vote down vote up
public Device createDevice(final String deviceName, final Instant notBefore, final Instant notAfter, final Consumer<X509v3CertificateBuilder> customizer) throws Exception {

        // create the fill device name

        final X500NameBuilder builder = new X500NameBuilder(RFC4519Style.INSTANCE);
        Arrays
                .asList(new X500Name(this.baseName.getName()).getRDNs())
                .forEach(e -> builder.addMultiValuedRDN(e.getTypesAndValues()));
        builder.addRDN(RFC4519Style.cn, deviceName);
        final X500Principal name = new X500Principal(builder.build().toString());

        // create a new key pair for the device

        final KeyPair deviceKey = this.keyPairGenerator.generateKeyPair();

        // sign certificate with CA key

        final ContentSigner contentSigner = new JcaContentSignerBuilder(mode.getSignatureAlgorithm())
                .build(this.keyPair.getPrivate());

        // create certificate

        final X509v3CertificateBuilder deviceCertificateBuilder = new JcaX509v3CertificateBuilder(
                this.baseName,
                BigInteger.valueOf(this.serialNumber.getAndIncrement()),
                Date.from(notBefore),
                Date.from(notAfter),
                name,
                deviceKey.getPublic())
                        .addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(deviceKey.getPublic()))
                        .addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(this.keyPair.getPublic()));

        // customize

        if (customizer != null) {
            customizer.accept(deviceCertificateBuilder);
        }

        // convert to JCA certificate

        final X509Certificate deviceCertificate = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider())
                .getCertificate(deviceCertificateBuilder.build(contentSigner));

        // return result

        return new Device(deviceKey, deviceCertificate);

    }
 
Example 16
Source File: CertificateHelper.java    From AndroidHttpCapture 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: 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 18
Source File: CertificateHelper.java    From PowerTunnel 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 19
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 20
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()));

}