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(); }
public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, CertificateParsingException { Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); List<String> emails = new ArrayList<>(); if (alternativeNames != null) { for(List<?> san : alternativeNames) { Integer type = (Integer) san.get(0); if (type == 1) { emails.add((String) san.get(1)); } } } X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject(); if (emails.size() == 0) { emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue())); } String name = IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()); if (emails.size() >= 1) { return new Pair<>(Jid.fromString(emails.get(0)), name); } else { return null; } }
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; }
/** * Gets the common name from the given X500Name. * * @param name the X.500 name * @return the common name, null if not found */ public static String getCommonName(X500Name name) { if (name == null) { return null; } RDN[] rdns = name.getRDNs(BCStyle.CN); if (rdns.length == 0) { return null; } return rdns[0].getFirst().getValue().toString(); }
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; }
@Override public UserDetails loadUserByUsername(String certDN) throws UsernameNotFoundException { logger.debug("certDN: " + certDN); SimpleGrantedAuthority role = new SimpleGrantedAuthority("ROLE_USER"); Collection<GrantedAuthority> roles = new ArrayList<>(); roles.add(role); X500Name x500name = new X500Name(certDN); //User user = new User(getElement(x500name, BCStyle.CN), "", true /*enabled*/, true /* not-expired */, true /* cred-not-expired*/, true /* not-locked*/, roles); //InetOrgPerson person = new InetOrgPerson(); InetOrgPerson.Essence essence = new InetOrgPerson.Essence(); String name = CertificateHandler.getElement(x500name, BCStyle.CN); essence.setUsername(name); essence.setUid(name); essence.setDn(certDN); essence.setCn(new String[]{name}); essence.setSn(name); essence.setO(CertificateHandler.getElement(x500name, BCStyle.O)); essence.setOu(CertificateHandler.getElement(x500name, BCStyle.OU)); essence.setAuthorities(roles); essence.setDescription(certDN); logger.debug("Parsed certificate, name: " + name); return essence.createUserDetails(); }
/** * 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(); }
@Test public void testSlashesInServiceName() throws Exception { String serviceNameWithSlashes = "service/name/with/slashes"; String serviceNameWithoutSlashes = "servicenamewithslashes"; CertificateNamesGenerator certificateNamesGenerator = new CertificateNamesGenerator(serviceNameWithSlashes, mockTaskSpec, mockPodInstance); Assert.assertEquals(String.format("%s-%s.%s", POD_NAME, TestConstants.TASK_NAME, serviceNameWithoutSlashes), certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN)[0].getFirst().getValue().toString()); List<String> names = Arrays.stream(certificateNamesGenerator.getSANs().getNames()) .map(name -> name.getName().toString()) .collect(Collectors.toList()); Assert.assertEquals(1, names.size()); Assert.assertTrue(names.contains(taskDnsName(TestConstants.TASK_NAME, serviceNameWithoutSlashes))); Assert.assertFalse(names.contains(taskDnsName("*", serviceNameWithoutSlashes))); Assert.assertFalse(names.contains(taskVipName("*", serviceNameWithoutSlashes))); // echo -n "some-pod-test-task-name.servicenamewithslashes.autoip.dcos.thisdcos.directory" | sha1sum Assert.assertEquals("c535f13128f2f15d1765f151114908b41c1eed65", certificateNamesGenerator.getSANsHash()); }
static void verifyCertificateCommonName(X500Name subject, String commonName) { List<AttributeTypeAndValue> attributesAndValues = Arrays.stream(subject.getRDNs()) .flatMap(rdn -> rdn.isMultiValued() ? Stream.of(rdn.getTypesAndValues()) : Stream.of(rdn.getFirst())) .filter(attr -> attr.getType() == BCStyle.CN) .collect(Collectors.toList()); if (attributesAndValues.size() != 1) { throw new IllegalArgumentException("Only 1 common name should be set"); } String actualCommonName = DERUTF8String.getInstance(attributesAndValues.get(0).getValue()).getString(); if (! actualCommonName.equals(commonName)) { throw new IllegalArgumentException("Expected common name to be " + commonName + ", but was " + actualCommonName); } }
@Test public void testGenerateInstanceRefreshRequestSubDomain() { File privkey = new File("./src/test/resources/test_private_k0.pem"); PrivateKey privateKey = Crypto.loadPrivateKey(privkey); InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system", "test", privateKey, "aws", 3600); assertNotNull(req); PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr()); assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq)); X500Name x500name = certReq.getSubject(); RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0]; assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue())); assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0)); }
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); }
private Set<String> rolesFromDN(String userDN) throws LDAPException, GeneralSecurityException { SearchRequest searchRequest = new SearchRequest(config.getRoleBaseDN(), SearchScope.SUB, Filter.createEqualityFilter("uniqueMember", userDN)); Set<String> roles = Sets.newLinkedHashSet(); LDAPConnection connection = connectionFactory.getLDAPConnection(); try { SearchResult sr = connection.search(searchRequest); for (SearchResultEntry sre : sr.getSearchEntries()) { X500Name x500Name = new X500Name(sre.getDN()); RDN[] rdns = x500Name.getRDNs(BCStyle.CN); if (rdns.length == 0) { logger.error("Could not create X500 Name for role:" + sre.getDN()); } else { String commonName = IETFUtils.valueToString(rdns[0].getFirst().getValue()); roles.add(commonName); } } } finally { connection.close(); } return roles; }
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); } } }
/** * Checks if the CSR contains the right parameters. * <p> * This is not supposed to be a Bouncy Castle test. If the * {@link PKCS10CertificationRequest} contains the right parameters, we assume that * Bouncy Castle encodes it properly. */ @SuppressWarnings("unchecked") private void csrTest(PKCS10CertificationRequest csr) { X500Name name = csr.getSubject(); assertThat(name.getRDNs(BCStyle.CN), arrayContaining(new RDNMatcher("abc.de"))); assertThat(name.getRDNs(BCStyle.C), arrayContaining(new RDNMatcher("XX"))); assertThat(name.getRDNs(BCStyle.L), arrayContaining(new RDNMatcher("Testville"))); assertThat(name.getRDNs(BCStyle.O), arrayContaining(new RDNMatcher("Testing Co"))); assertThat(name.getRDNs(BCStyle.OU), arrayContaining(new RDNMatcher("Testunit"))); assertThat(name.getRDNs(BCStyle.ST), arrayContaining(new RDNMatcher("ABC"))); Attribute[] attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); assertThat(attr.length, is(1)); ASN1Encodable[] extensions = attr[0].getAttrValues().toArray(); assertThat(extensions.length, is(1)); GeneralNames names = GeneralNames.fromExtensions((Extensions) extensions[0], Extension.subjectAlternativeName); assertThat(names.getNames(), arrayContaining(new GeneralNameMatcher("abc.de"), new GeneralNameMatcher("fg.hi"), new GeneralNameMatcher("jklm.no"), new GeneralNameMatcher("pqr.st"), new GeneralNameMatcher("uv.wx"), new GeneralNameMatcher("y.z"), new GeneralNameMatcher("*.wild.card"))); }
/** * 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 void validateSignatureNode(SignatureWidgetAnnotation signatureWidgetAnnotation, SignatureValidator signatureValidator) throws SignatureIntegrityException { SignatureFieldDictionary fieldDictionary = signatureWidgetAnnotation.getFieldDictionary(); if (fieldDictionary != null) { // try and parse out the signer info. X509Certificate certificate = signatureValidator.getSignerCertificate(); X500Principal principal = certificate.getIssuerX500Principal(); X500Name x500name = new X500Name(principal.getName()); if (x500name.getRDNs() != null) { commonName = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.CN); organization = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.O); emailAddress = SignatureUtilities.parseRelativeDistinguishedName(x500name, BCStyle.EmailAddress); } } }
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); }
public static String getSubjectCNFromCertificate(X509Certificate certificate) { try { X500Name x500name = new JcaX509CertificateHolder(certificate).getIssuer(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; return IETFUtils.valueToString(cn.getFirst().getValue()); } catch (CertificateEncodingException e) { log.error("Unable to get issuer CN", e); return null; } }
@Override public HttpResponse handle(HttpRequest request, MiddlewareChain chain) { request = MixinUtils.mixin(request, new Class[]{PrincipalAvailable.class}); String clientDN = request.getHeaders().get("X-Client-DN"); if (!isAuthenticated((PrincipalAvailable) request) && clientDN != null) { RDN cn = new X500Name(clientDN).getRDNs(BCStyle.CN)[0]; String account = IETFUtils.valueToString(cn.getFirst().getValue()); } return castToHttpResponse(chain.next(request)); }
private static Map<ASN1ObjectIdentifier, Integer> createDnOrderMap() { Map<ASN1ObjectIdentifier, Integer> orderMap = new HashMap<>(); int count = 0; orderMap.put(BCStyle.CN, count++); orderMap.put(BCStyle.L, count++); orderMap.put(BCStyle.ST, count++); orderMap.put(BCStyle.O, count++); orderMap.put(BCStyle.OU, count++); orderMap.put(BCStyle.C, count++); orderMap.put(BCStyle.STREET, count++); orderMap.put(BCStyle.DC, count++); orderMap.put(BCStyle.UID, count++); return Collections.unmodifiableMap(orderMap); }
public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, CertificateParsingException { Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); List<String> emails = new ArrayList<>(); if (alternativeNames != null) { for(List<?> san : alternativeNames) { Integer type = (Integer) san.get(0); if (type == 1) { emails.add((String) san.get(1)); } } } X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject(); if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) { emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue())); } String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null; if (emails.size() >= 1) { return new Pair<>(Jid.fromString(emails.get(0)), name); } else if (name != null){ try { Jid jid = Jid.fromString(name); if (jid.isBareJid() && !jid.isDomainJid()) { return new Pair<>(jid,null); } } catch (InvalidJidException e) { return null; } } return null; }
private static List<String> getCommonNames(X509Certificate certificate) { List<String> domains = new ArrayList<>(); try { X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject(); RDN[] rdns = x500name.getRDNs(BCStyle.CN); for (int i = 0; i < rdns.length; ++i) { domains.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[i].getFirst().getValue())); } return domains; } catch (CertificateEncodingException e) { return domains; } }
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())); }
@Test public void testGetSubject() throws Exception { CertificateNamesGenerator certificateNamesGenerator = new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance); RDN[] cnRDNs = certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN); Assert.assertEquals(cnRDNs.length, 1); Assert.assertEquals(String.format("%s-%s.%s", POD_NAME, TestConstants.TASK_NAME, TestConstants.SERVICE_NAME), cnRDNs[0].getFirst().getValue().toString()); }
@Test public void testGetSubjectWithLongCN() throws Exception { Mockito.when(mockTaskSpec.getName()).thenReturn(UUID.randomUUID().toString()); CertificateNamesGenerator certificateNamesGenerator = new CertificateNamesGenerator(UUID.randomUUID().toString(), mockTaskSpec, mockPodInstance); RDN[] cnRDNs = certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN); Assert.assertEquals(cnRDNs.length, 1); Assert.assertEquals(64, cnRDNs[0].getFirst().getValue().toString().length()); }