static X500Name buildName(String commonName, String organization, String organizationUnit, String locality, String state, String country) { X500NameBuilder nameBuilder = new X500NameBuilder(); if (!commonName.isEmpty()) { nameBuilder.addRDN(BCStyle.CN, commonName); } if (!organizationUnit.isEmpty()) { nameBuilder.addRDN(BCStyle.OU, organizationUnit); } if (!organization.isEmpty()) { nameBuilder.addRDN(BCStyle.O, organization); } if (!locality.isEmpty()) { nameBuilder.addRDN(BCStyle.L, locality); } if (!state.isEmpty()) { nameBuilder.addRDN(BCStyle.ST, state); } if (!country.isEmpty()) { nameBuilder.addRDN(BCStyle.C, country); } return nameBuilder.build(); }
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; }
public X500Name x500Name() throws IOException { if(name==null) { X500NameBuilder xnb = new X500NameBuilder(); xnb.addRDN(BCStyle.CN,cn); xnb.addRDN(BCStyle.E,email); if(environment==null) { xnb.addRDN(BCStyle.OU,mechID); } else { xnb.addRDN(BCStyle.OU,mechID+':'+environment); } xnb.addRDN(BCStyle.O,o); xnb.addRDN(BCStyle.L,l); xnb.addRDN(BCStyle.ST,st); xnb.addRDN(BCStyle.C,c); name = xnb.build(); } return name; }
/** * Returns a Subject for service certificate. */ public X500Name getSubject() { // Create subject CN as pod-name-0-task-name.service-name String cn = String.format("%s.%s", EndpointUtils.removeSlashes(EndpointUtils.replaceDotsWithDashes(taskInstanceName)), EndpointUtils.removeSlashes(EndpointUtils.replaceDotsWithDashes(serviceName))); if (cn.length() > CN_MAX_LENGTH) { cn = cn.substring(cn.length() - CN_MAX_LENGTH); } return new X500NameBuilder() .addRDN(BCStyle.CN, cn) .addRDN(BCStyle.O, "Mesosphere, Inc") .addRDN(BCStyle.L, "San Francisco") .addRDN(BCStyle.ST, "CA") .addRDN(BCStyle.C, "US") .build(); }
public PKCS10CertificationRequest generateCSR(User user, KeyPair key) throws OperatorCreationException { X500Name x500User = new X500NameBuilder() .addRDN(BCStyle.C, user.getCountryName()) .addRDN(BCStyle.ST, user.getProvinceName()) .addRDN(BCStyle.L, user.getLocalityName()) .addRDN(BCStyle.O, user.getOrganizationName()) .addRDN(BCStyle.OU, user.getOrganizationUnitName()) .addRDN(BCStyle.CN, user.getCommonName()) .addRDN(BCStyle.EmailAddress, user.getEmailAddress()) .build(); PKCS10CertificationRequestBuilder p10Builder = new JcaPKCS10CertificationRequestBuilder( x500User, key.getPublic()); user.setPrivateKey(key.getPrivate().getEncoded()); JcaContentSignerBuilder csBuilder= new JcaContentSignerBuilder("SHA512WithRSAEncryption"); ContentSigner signer = csBuilder.build(key.getPrivate()); return p10Builder.build(signer); }
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; }
private static void setOID(X500NameBuilder dnBuilder, X509Metadata metadata, String oid, String defaultValue) { String value = null; if (metadata.oids != null && metadata.oids.containsKey(oid)) { value = metadata.oids.get(oid); } if (Strings.isNullOrEmpty(value)) { value = defaultValue; } if (!Strings.isNullOrEmpty(value)) { try { Field field = BCStyle.class.getField(oid); ASN1ObjectIdentifier objectId = (ASN1ObjectIdentifier) field.get(null); dnBuilder.addRDN(objectId, value); } catch (Exception e) { logger.error(MessageFormat.format("Failed to set OID \"{0}\"!", oid), e); } } }
/** * This method creates the PKCS10 Certificate Sign Request which is to be sent to the SCEP Server using the * generated PublicKey of the client. The certificate parameters used here are the ones from the AgentManager * which are the values read from the configurations file. * * @return the PKCS10CertificationRequest object created using the client specific configs and the generated * PublicKey * @throws AgentCoreOperationException if an error occurs when creating a content signer to sign the CSR. */ private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException { // Build the CN for the cert we are requesting. X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE); nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getDeviceName()); nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner()); nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner()); nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId()); X500Name principal = nameBld.build(); JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(SIGNATURE_ALG).setProvider(PROVIDER); ContentSigner contentSigner; try { contentSigner = contentSignerBuilder.build(this.privateKey); } catch (OperatorCreationException e) { String errorMsg = "Could not create content signer with private key."; log.error(errorMsg); throw new AgentCoreOperationException(errorMsg, e); } // Generate the certificate signing request (csr = PKCS10) PKCS10CertificationRequestBuilder reqBuilder = new JcaPKCS10CertificationRequestBuilder(principal, this.publicKey); return reqBuilder.build(contentSigner); }
/** * Creates an X509 version3 certificate. * * @param kp KeyPair that keeps the public and private keys for the new certificate. * @param days time to live * @param issuerCommonName Issuer CN string * @param subjectCommonName Subject CN string * @param domain Domain of the server. * @param signAlgoritm Signature algorithm. This can be either a name or an OID. * @return X509 V3 Certificate * @throws GeneralSecurityException * @throws IOException */ public static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int days, String issuerCommonName, String subjectCommonName, String domain, String signAlgoritm) 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); }
private Pair<Key, X509Certificate> generateKey(String name) throws GeneralSecurityException, OperatorCreationException { logger.debug("generating self-signed cert for {}", name); BouncyCastleProvider provider = new BouncyCastleProvider(); Security.addProvider(provider); KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", provider); kpGen.initialize(1024, new SecureRandom()); KeyPair pair = kpGen.generateKeyPair(); X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.OU, "None"); builder.addRDN(BCStyle.O, "None"); builder.addRDN(BCStyle.CN, name); Instant now = Instant.now(); Date notBefore = Date.from(now); Date notAfter = Date.from(now.plus(365, ChronoUnit.DAYS)); BigInteger serial = BigInteger.valueOf(now.getEpochSecond()); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(), serial, notBefore, notAfter, builder.build(), pair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .setProvider(provider) .build(pair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter() .setProvider(provider) .getCertificate(certGen.build(sigGen)); return Pair.of(pair.getPrivate(), cert); }
private static void setOID(X500NameBuilder dnBuilder, X509Metadata metadata, String oid, String defaultValue) { String value = null; if (metadata.oids != null && metadata.oids.containsKey(oid)) { value = metadata.oids.get(oid); } if (StringUtils.isEmpty(value)) { value = defaultValue; } if (!StringUtils.isEmpty(value)) { try { Field field = BCStyle.class.getField(oid); ASN1ObjectIdentifier objectId = (ASN1ObjectIdentifier) field.get(null); dnBuilder.addRDN(objectId, value); } catch (Exception e) { logger.error(MessageFormat.format("Failed to set OID \"{0}\"!", oid) ,e); } } }
public static X509Certificate generateTestCertificate(KeyPair pair) throws CertificateException, OperatorCreationException { final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); final X500Name cn = nameBuilder.addRDN(BCStyle.CN, "Test Certificate").build(); final byte[] encoded = pair.getPublic().getEncoded(); final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(encoded)); final X509v1CertificateBuilder certBuilder = new X509v1CertificateBuilder( cn, BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis() - 10000), new Date(System.currentTimeMillis() + 10000), cn, subjectPublicKeyInfo ); final JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder("SHA256WithRSAEncryption"); final ContentSigner contentSigner = contentSignerBuilder.build(pair.getPrivate()); final X509CertificateHolder certificateHolder = certBuilder.build(contentSigner); return new JcaX509CertificateConverter().setProvider( "BC" ).getCertificate(certificateHolder); }
private ASN1Encodable createEntryValue(ASN1ObjectIdentifier oid, String value) { X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(oid, value); X500Name name = builder.build(); ASN1Sequence seq = (ASN1Sequence)name.toASN1Primitive(); ASN1Set set = ASN1Set.getInstance(seq.getObjectAt(0).toASN1Primitive()); seq = (ASN1Sequence)set.getObjectAt(0); return seq.getObjectAt(1); }
private ASN1Encodable createEntryValueFromString(ASN1ObjectIdentifier oid, String value) { X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(oid, value); X500Name name = new X500Name(builder.build().toString()); ASN1Sequence seq = (ASN1Sequence)name.toASN1Primitive(); ASN1Set set = ASN1Set.getInstance(seq.getObjectAt(0).toASN1Primitive()); seq = (ASN1Sequence)set.getObjectAt(0); return seq.getObjectAt(1); }
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; }
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, NOT_AFTER, 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("PKCS12" /* , PROVIDER_NAME */); result.load(null, null); Certificate[] chain = { cert, caCert }; result.setKeyEntry(authority.alias(), keyPair.getPrivate(), authority.password(), chain); return result; }
public void initializeKeyStore() throws GeneralSecurityException, IOException { KeyPair keyPair = generateKeyPair(1024); X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, commonName); nameBuilder.addRDN(BCStyle.O, organization); nameBuilder.addRDN(BCStyle.OU, 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 keystore = KeyStore.getInstance(KEY_STORE_TYPE); keystore.load(null, null); keystore.setKeyEntry(alias, keyPair.getPrivate(), password, new Certificate[] { cert }); try (OutputStream os = new FileOutputStream(aliasFile(KEY_STORE_FILE_EXTENSION))) { keystore.store(os, password); } exportPem(aliasFile(".pem"), cert); }
/** * 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(); }
private byte[] createCSR() throws IOException, OperatorCreationException { KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair(); X500Name name = new X500NameBuilder() .addRDN(BCStyle.CN, "issuer") .build(); ExtensionsGenerator extensionsGenerator = new ExtensionsGenerator(); extensionsGenerator.addExtension( Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); extensionsGenerator.addExtension( Extension.extendedKeyUsage, true, new ExtendedKeyUsage( new KeyPurposeId[] { KeyPurposeId.id_kp_clientAuth, KeyPurposeId.id_kp_serverAuth } )); GeneralNames subAtlNames = new GeneralNames( new GeneralName[]{ new GeneralName(GeneralName.dNSName, "test.com"), new GeneralName(GeneralName.iPAddress, TEST_IP_ADDR), } ); extensionsGenerator.addExtension( Extension.subjectAlternativeName, true, subAtlNames); ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()); PKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(name, keyPair.getPublic()) .addAttribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, extensionsGenerator.generate()); return PEMUtils.toPEM(csrBuilder.build(signer)); }
private X509Certificate createCertificate() throws Exception { KeyPair keyPair = KEY_PAIR_GENERATOR.generateKeyPair(); SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo.getInstance( keyPair.getPublic().getEncoded()); X500Name issuer = new X500NameBuilder() .addRDN(BCStyle.CN, "issuer") .build(); X500Name subject = new X500NameBuilder() .addRDN(BCStyle.CN, "subject") .build(); ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(keyPair.getPrivate()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509CertificateHolder certHolder = new X509v3CertificateBuilder( issuer, new BigInteger("1000"), Date.from(Instant.now()), Date.from(Instant.now().plusSeconds(100000)), subject, subjectPublicKeyInfo ) .build(signer); return (X509Certificate) certificateFactory. generateCertificate( new ByteArrayInputStream(certHolder.getEncoded())); }
private X509Certificate createCertificate() throws Exception { X509CertificateHolder certHolder = new X509v3CertificateBuilder( new X500NameBuilder().addRDN(BCStyle.CN, "issuer").build(), new BigInteger("1000"), Date.from(Instant.now()), Date.from(Instant.now().plusSeconds(100000)), new X500NameBuilder().addRDN(BCStyle.CN, "subject").build(), SubjectPublicKeyInfo.getInstance(KEYPAIR.getPublic().getEncoded())) .build(new JcaContentSignerBuilder("SHA256withRSA").build(KEYPAIR.getPrivate())); return (X509Certificate) CertificateFactory.getInstance("X.509") .generateCertificate(new ByteArrayInputStream(certHolder.getEncoded())); }
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(); }
/** * 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(); }
/** * 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(); }
/** * Builds a distinguished name from the X509Metadata. * * @return a DN */ private static X500Name buildDistinguishedName(X509Metadata metadata) { X500NameBuilder dnBuilder = new X500NameBuilder(BCStyle.INSTANCE); setOID(dnBuilder, metadata, "C", null); setOID(dnBuilder, metadata, "ST", null); setOID(dnBuilder, metadata, "L", null); setOID(dnBuilder, metadata, "O", "Fathom"); setOID(dnBuilder, metadata, "OU", "Fathom"); setOID(dnBuilder, metadata, "E", metadata.emailAddress); setOID(dnBuilder, metadata, "CN", metadata.commonName); X500Name dn = dnBuilder.build(); return dn; }
public static X500Name newX500Name(String commonName, String orgName, String ouName) { X500NameBuilder b = new X500NameBuilder(BCStyle.INSTANCE); b.addRDN(BCStyle.CN, commonName); b.addRDN(BCStyle.OU, ouName); b.addRDN(BCStyle.O, orgName); return b.build(); }
@Override X500Name getX500SubjectName(X509Certificate cert) throws CertificateEncodingException { X500NameBuilder nameBuilder = new X500NameBuilder(X500Name.getDefaultStyle()); if(multiValue) { nameBuilder.addMultiValuedRDN(typeValues); } else { for (AttributeTypeAndValue typeValue : typeValues) { nameBuilder.addRDN(typeValue); } } return nameBuilder.build(); }
/** * Build self signed certificate from key pair. * @param commonName the certificate common name * @param ipAddress the subject alternative name IP address or null * @param keyPair the key pair. * @return the certificate * @throws Exception if error occurs in certificate generation process. */ private static X509Certificate buildCertificate(final String commonName, final String ipAddress, KeyPair keyPair) throws Exception { final Date notBefore = new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24); final Date notAfter = DateUtils.addYears(notBefore, 100); final BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE); nameBuilder.addRDN(BCStyle.CN, commonName); final SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo( ASN1Sequence.getInstance(keyPair.getPublic().getEncoded())); final X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(nameBuilder.build(), serial, notBefore, notAfter, nameBuilder.build(), subjectPublicKeyInfo); if (ipAddress != null) { certGen.addExtension(Extension.subjectAlternativeName, false, new GeneralNames( new GeneralName(GeneralName.iPAddress, ipAddress))); } final ContentSigner sigGen = new JcaContentSignerBuilder(CERTIFICATE_SIGNATURE_ALGORITHM) .setProvider(PROVIDER).build(keyPair.getPrivate()); final X509Certificate cert = new JcaX509CertificateConverter().setProvider(PROVIDER) .getCertificate(certGen.build(sigGen)); return cert; }
public static X509Certificate generateSelfSignedCertificate( String cn, String ou, String o, String l, String s, String c, KeyPair pair, String signatureType) { try { // Generate self-signed certificate X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.OU, ou); builder.addRDN(BCStyle.O, o); builder.addRDN(BCStyle.L, l); builder.addRDN(BCStyle.ST, s); builder.addRDN(BCStyle.CN, cn); Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30); Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)); BigInteger serial = BigInteger.valueOf(System.currentTimeMillis()); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder( builder.build(), serial, notBefore, notAfter, builder.build(), pair.getPublic()); ContentSigner sigGen = new JcaContentSignerBuilder( signatureType).setProvider(BC).build( pair.getPrivate()); X509Certificate cert = new JcaX509CertificateConverter() .setProvider(BC).getCertificate(certGen.build(sigGen)); cert.checkValidity(new Date()); cert.verify(cert.getPublicKey()); return cert; } catch (Throwable t) { throw new RuntimeException( "Failed to generate self-signed certificate!", t); } }
public static byte[] createCsr(KeyPair keyPair, String clientPcName) throws IOException { X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); builder.addRDN(BCStyle.CN, clientPcName); PKCS10CertificationRequestBuilder requestBuilder = new JcaPKCS10CertificationRequestBuilder(builder.build(), keyPair.getPublic()); try { return requestBuilder.build(new JcaContentSignerBuilder(SHA_256_WITH_ECDSA).setProvider("BC").build(keyPair.getPrivate())).getEncoded(); } catch (OperatorCreationException e) { throw new Error("Certificate Conversion should never result in an Exception.", e); } }