List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:org.cesecore.certificates.certificate.request.RequestMessageTest.java
License:Open Source License
private PKCS10CertificationRequest createP10(final String subjectDN) throws IOException, OperatorCreationException { // Create a P10 with extensions, in this case altNames with a DNS name ASN1EncodableVector altnameattr = new ASN1EncodableVector(); altnameattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest); // AltNames/*ww w .ja va 2s . co m*/ // String[] namearray = altnames.split(","); GeneralNames san = CertTools.getGeneralNamesFromAltName("dNSName=foo1.bar.com"); ExtensionsGenerator extgen = new ExtensionsGenerator(); extgen.addExtension(Extension.subjectAlternativeName, false, san); Extensions exts = extgen.generate(); altnameattr.add(new DERSet(exts)); // Add a challenge password as well ASN1EncodableVector pwdattr = new ASN1EncodableVector(); pwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword); ASN1EncodableVector pwdvalues = new ASN1EncodableVector(); pwdvalues.add(new DERUTF8String("foo123")); pwdattr.add(new DERSet(pwdvalues)); // Complete the Attribute section of the request, the set (Attributes) // contains one sequence (Attribute) ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new DERSequence(altnameattr)); v.add(new DERSequence(pwdattr)); DERSet attributes = new DERSet(v); // Create the PKCS10 X500Name dn = new X500Name(subjectDN); PKCS10CertificationRequest basicpkcs10 = CertTools.genPKCS10CertificationRequest("SHA1WithRSA", dn, keyPair.getPublic(), attributes, keyPair.getPrivate(), null); return basicpkcs10; }
From source file:org.cesecore.certificates.ocsp.standalone.StandaloneOcspResponseGeneratorSessionTest.java
License:Open Source License
/** * Build an OCSP request, that will optionally be signed if authentication parameters are specified * // w w w . jav a2 s .c o m * @param ocspAuthenticationCertificate signing certificate * @param ocspAuthenticationPrivateKey private key to sign with * @param caCertificate issuer of the queried certificate * @param certificateSerialnumber serial number of the certificate to be queried * @return * @throws Exception */ private OCSPReq buildOcspRequest(final X509Certificate ocspAuthenticationCertificate, final PrivateKey ocspAuthenticationPrivateKey, final X509Certificate caCertificate, final BigInteger certificateSerialnumber) throws Exception { final OCSPReqBuilder ocspReqBuilder = new OCSPReqBuilder(); if (ocspAuthenticationCertificate != null) { // Signed requests are required to have an OCSPRequest.TBSRequest.requestorName ocspReqBuilder.setRequestorName(new X500Name(ocspAuthenticationCertificate.getSubjectDN().getName())); } ocspReqBuilder.addRequest(new JcaCertificateID(SHA1DigestCalculator.buildSha1Instance(), caCertificate, certificateSerialnumber)); ocspReqBuilder.setRequestExtensions( new Extensions(new Extension[] { new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString("123456789".getBytes())) })); if (ocspAuthenticationCertificate != null && ocspAuthenticationPrivateKey != null) { // Create a signed request final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(AlgorithmConstants.SIGALG_SHA1_WITH_RSA) .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(ocspAuthenticationPrivateKey), 20480); return ocspReqBuilder.build(signer, new X509CertificateHolder[] { new X509CertificateHolder(ocspAuthenticationCertificate.getEncoded()) }); } else { // Create an unsigned request return ocspReqBuilder.build(); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
License:Open Source License
private X509Certificate getSelfCertificate(String myname, long validity, String sigAlg, KeyPair keyPair) throws InvalidKeyException, CertificateException { final long currentTime = new Date().getTime(); final Date firstDate = new Date(currentTime - 24 * 60 * 60 * 1000); final Date lastDate = new Date(currentTime + validity * 1000); final X500Name issuer = new X500Name(myname); final BigInteger serno = BigInteger.valueOf(firstDate.getTime()); final PublicKey publicKey = keyPair.getPublic(); if (publicKey == null) { throw new InvalidKeyException("Public key is null"); }//from w ww. j a va2 s .c o m try { final X509v3CertificateBuilder cg = new JcaX509v3CertificateBuilder(issuer, serno, firstDate, lastDate, issuer, publicKey); log.debug("Keystore signing algorithm " + sigAlg); final ContentSigner signer = new BufferingContentSigner( new JcaContentSignerBuilder(sigAlg).setProvider(this.providerName).build(keyPair.getPrivate()), 20480); final X509CertificateHolder cert = cg.build(signer); return (X509Certificate) CertTools.getCertfromByteArray(cert.getEncoded()); } catch (OperatorCreationException e) { log.error("Error creating content signer: ", e); throw new CertificateException(e); } catch (IOException e) { throw new CertificateException("Could not read certificate", e); } }
From source file:org.cesecore.keys.util.KeyStoreTools.java
License:Open Source License
/** Generates a certificate request (CSR) in PKCS#10 format and writes to file * @param alias for the key to be used//from www. j a v a2 s . c om * @param dn the DN to be used. If null the 'CN=alias' will be used * @param explicitEccParameters false should be default and will use NamedCurve encoding of ECC public keys (IETF recommendation), use true to include all parameters explicitly (ICAO ePassport requirement). * @throws Exception */ public void generateCertReq(String alias, String sDN, boolean explicitEccParameters) throws Exception { PublicKey publicKey = getCertificate(alias).getPublicKey(); final PrivateKey privateKey = getPrivateKey(alias); if (log.isDebugEnabled()) { log.debug("alias: " + alias + " SHA1 of public key: " + CertTools.getFingerprintAsString(publicKey.getEncoded())); } String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(publicKey).iterator().next(); if (sigAlg == null) { sigAlg = "SHA1WithRSA"; } if (sigAlg.contains("ECDSA") && explicitEccParameters) { log.info("Using explicit parameter encoding for ECC key."); publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC"); } else { log.info("Using named curve parameter encoding for ECC key."); } X500Name sDNName = sDN != null ? new X500Name(sDN) : new X500Name("CN=" + alias); final PKCS10CertificationRequest certReq = CertTools.genPKCS10CertificationRequest(sigAlg, sDNName, publicKey, new DERSet(), privateKey, this.keyStore.getProvider().getName()); ContentVerifierProvider verifier = CertTools.genContentVerifierProvider(publicKey); if (!certReq.isSignatureValid(verifier)) { String msg = intres.getLocalizedMessage("token.errorcertreqverify", alias); throw new Exception(msg); } String filename = alias + ".pem"; final Writer writer = new FileWriter(filename); writer.write(CertTools.BEGIN_CERTIFICATE_REQUEST + "\n"); writer.write(new String(Base64.encode(certReq.getEncoded()))); writer.write("\n" + CertTools.END_CERTIFICATE_REQUEST + "\n"); writer.close(); log.info("Wrote csr to file: " + filename); }
From source file:org.cesecore.util.CertTools.java
License:Open Source License
/** * From an altName string as defined in getSubjectAlternativeName * /*from w ww. ja v a2s . c o m*/ * @param altName * @return ASN.1 GeneralNames * @see #getSubjectAlternativeName */ public static GeneralNames getGeneralNamesFromAltName(final String altName) { if (log.isTraceEnabled()) { log.trace(">getGeneralNamesFromAltName: " + altName); } final ASN1EncodableVector vec = new ASN1EncodableVector(); for (final String email : CertTools.getEmailFromDN(altName)) { vec.add(new GeneralName(1, /*new DERIA5String(iter.next())*/email)); } for (final String dns : CertTools.getPartsFromDN(altName, CertTools.DNS)) { vec.add(new GeneralName(2, new DERIA5String(dns))); } final String directoryName = getDirectoryStringFromAltName(altName); if (directoryName != null) { //final X500Name x500DirectoryName = new X500Name(directoryName); final X500Name x500DirectoryName = new X500Name(LDAPDN.unescapeRDN(directoryName)); final GeneralName gn = new GeneralName(4, x500DirectoryName); vec.add(gn); } for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI)) { vec.add(new GeneralName(6, new DERIA5String(uri))); } for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI1)) { vec.add(new GeneralName(6, new DERIA5String(uri))); } for (final String uri : CertTools.getPartsFromDN(altName, CertTools.URI2)) { vec.add(new GeneralName(6, new DERIA5String(uri))); } for (final String addr : CertTools.getPartsFromDN(altName, CertTools.IPADDR)) { final byte[] ipoctets = StringTools.ipStringToOctets(addr); if (ipoctets.length > 0) { final GeneralName gn = new GeneralName(7, new DEROctetString(ipoctets)); vec.add(gn); } else { log.error("Cannot parse/encode ip address, ignoring: " + addr); } } // UPN is an OtherName see method getUpn... for asn.1 definition for (final String upn : CertTools.getPartsFromDN(altName, CertTools.UPN)) { final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(CertTools.UPN_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DERUTF8String(upn))); vec.add(GeneralName.getInstance(new DERTaggedObject(false, 0, new DERSequence(v)))); } // PermanentIdentifier is an OtherName see method getPermananentIdentifier... for asn.1 definition for (final String permanentIdentifier : CertTools.getPartsFromDN(altName, CertTools.PERMANENTIDENTIFIER)) { final String[] values = getPermanentIdentifierValues(permanentIdentifier); final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName v.add(new ASN1ObjectIdentifier(CertTools.PERMANENTIDENTIFIER_OBJECTID)); // First the PermanentIdentifier sequence final ASN1EncodableVector piSeq = new ASN1EncodableVector(); if (values[0] != null) { piSeq.add(new DERUTF8String(values[0])); } if (values[1] != null) { piSeq.add(new ASN1ObjectIdentifier(values[1])); } v.add(new DERTaggedObject(true, 0, new DERSequence(piSeq))); // GeneralName gn = new GeneralName(new DERSequence(v), 0); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } for (final String guid : CertTools.getPartsFromDN(altName, CertTools.GUID)) { final ASN1EncodableVector v = new ASN1EncodableVector(); byte[] guidbytes = Hex.decode(guid); if (guidbytes != null) { v.add(new ASN1ObjectIdentifier(CertTools.GUID_OBJECTID)); v.add(new DERTaggedObject(true, 0, new DEROctetString(guidbytes))); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } else { log.error("Cannot decode hexadecimal guid, ignoring: " + guid); } } // Krb5PrincipalName is an OtherName, see method getKrb5Principal...for ASN.1 definition for (final String principalString : CertTools.getPartsFromDN(altName, CertTools.KRB5PRINCIPAL)) { // Start by parsing the input string to separate it in different parts if (log.isDebugEnabled()) { log.debug("principalString: " + principalString); } // The realm is the last part moving back until an @ final int index = principalString.lastIndexOf('@'); String realm = ""; if (index > 0) { realm = principalString.substring(index + 1); } if (log.isDebugEnabled()) { log.debug("realm: " + realm); } // Now we can have several principals separated by / final ArrayList<String> principalarr = new ArrayList<String>(); int jndex = 0; int bindex = 0; while (jndex < index) { // Loop and add all strings separated by / jndex = principalString.indexOf('/', bindex); if (jndex == -1) { jndex = index; } String s = principalString.substring(bindex, jndex); if (log.isDebugEnabled()) { log.debug("adding principal name: " + s); } principalarr.add(s); bindex = jndex + 1; } // Now we must construct the rather complex asn.1... final ASN1EncodableVector v = new ASN1EncodableVector(); // this is the OtherName v.add(new ASN1ObjectIdentifier(CertTools.KRB5PRINCIPAL_OBJECTID)); // First the Krb5PrincipalName sequence final ASN1EncodableVector krb5p = new ASN1EncodableVector(); // The realm is the first tagged GeneralString krb5p.add(new DERTaggedObject(true, 0, new DERGeneralString(realm))); // Second is the sequence of principal names, which is at tagged position 1 in the krb5p final ASN1EncodableVector principals = new ASN1EncodableVector(); // According to rfc4210 the type NT-UNKNOWN is 0, and according to some other rfc this type should be used... principals.add(new DERTaggedObject(true, 0, new ASN1Integer(0))); // The names themselves are yet another sequence final Iterator<String> i = principalarr.iterator(); final ASN1EncodableVector names = new ASN1EncodableVector(); while (i.hasNext()) { String principalName = (String) i.next(); names.add(new DERGeneralString(principalName)); } principals.add(new DERTaggedObject(true, 1, new DERSequence(names))); krb5p.add(new DERTaggedObject(true, 1, new DERSequence(principals))); v.add(new DERTaggedObject(true, 0, new DERSequence(krb5p))); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } // To support custom OIDs in altNames, they must be added as an OtherName of plain type UTF8String for (final String oid : CertTools.getCustomOids(altName)) { for (final String oidValue : CertTools.getPartsFromDN(altName, oid)) { final ASN1EncodableVector v = new ASN1EncodableVector(); v.add(new ASN1ObjectIdentifier(oid)); v.add(new DERTaggedObject(true, 0, new DERUTF8String(oidValue))); final ASN1Primitive gn = new DERTaggedObject(false, 0, new DERSequence(v)); vec.add(gn); } } if (vec.size() > 0) { return GeneralNames.getInstance(new DERSequence(vec)); } return null; }
From source file:org.cesecore.util.CertToolsTest.java
License:Open Source License
@Test public void test16GetSubjectAltNameStringWithDirectoryName() throws Exception { log.trace(">test16GetSubjectAltNameStringWithDirectoryName()"); Certificate cer = CertTools.getCertfromByteArray(altNameCertWithDirectoryName); String altNames = CertTools.getSubjectAlternativeName(cer); log.debug(altNames);// w ww . j a va 2 s.c om String name = CertTools.getPartFromDN(altNames, CertTools.UPN); assertEquals("testDirName@jamador.pki.gva.es", name); assertEquals("testDirName@jamador.pki.gva.es", CertTools.getUPNAltName(cer)); name = CertTools.getPartFromDN(altNames, CertTools.DIRECTORYNAME); assertEquals("CN=testDirName|dir|name", name.replace("cn=", "CN=")); assertEquals(name.substring("CN=".length()), (new X500Name("CN=testDirName|dir|name").getRDNs()[0].getFirst().getValue()).toString()); String altName = "rfc822name=foo@bar.se, uri=http://foo.bar.se, directoryName=" + LDAPDN.escapeRDN("CN=testDirName, O=Foo, OU=Bar, C=SE") + ", dnsName=foo.bar.se"; GeneralNames san = CertTools.getGeneralNamesFromAltName(altName); GeneralName[] gns = san.getNames(); boolean found = false; for (int i = 0; i < gns.length; i++) { int tag = gns[i].getTagNo(); if (tag == 4) { found = true; ASN1Encodable enc = gns[i].getName(); X500Name dir = (X500Name) enc; String str = dir.toString(); log.debug("DirectoryName: " + str); assertEquals("CN=testDirName,O=Foo,OU=Bar,C=SE", str); } } assertTrue(found); altName = "rfc822name=foo@bar.se, rfc822name=foo@bar.com, uri=http://foo.bar.se, directoryName=" + LDAPDN.escapeRDN("CN=testDirName, O=Foo, OU=Bar, C=SE") + ", dnsName=foo.bar.se, dnsName=foo.bar.com"; san = CertTools.getGeneralNamesFromAltName(altName); gns = san.getNames(); int dnscount = 0; int rfc822count = 0; for (int i = 0; i < gns.length; i++) { int tag = gns[i].getTagNo(); if (tag == 2) { dnscount++; ASN1Encodable enc = gns[i].getName(); DERIA5String dir = (DERIA5String) enc; String str = dir.getString(); log.info("DnsName: " + str); } if (tag == 1) { rfc822count++; ASN1Encodable enc = gns[i].getName(); DERIA5String dir = (DERIA5String) enc; String str = dir.getString(); log.info("Rfc822Name: " + str); } } assertEquals(2, dnscount); assertEquals(2, rfc822count); log.trace("<test16GetSubjectAltNameStringWithDirectoryName()"); }
From source file:org.cesecore.util.CertToolsTest.java
License:Open Source License
/** * Tests the following methods://from w w w . j a va 2s .c om * <ul> * <li>{@link CertTools.checkNameConstraints}</li> * <li>{@link NameConstraint.parseNameConstraintsList}</li> * <li>{@link NameConstraint.toGeneralSubtrees}</li> * </ul> */ @Test public void testNameConstraints() throws Exception { final String permitted = "C=SE,CN=example.com\n" + "example.com\n" + "@mail.example\n" + "user@host.com\n" + "10.0.0.0/8\n" + " C=SE, CN=spacing \n"; final String excluded = "forbidden.example.com\n" + "postmaster@mail.example\n" + "10.1.0.0/16\n" + "::/0"; // IPv6 final List<Extension> extensions = new ArrayList<Extension>(); GeneralSubtree[] permittedSubtrees = NameConstraint .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(permitted)); GeneralSubtree[] excludedSubtrees = NameConstraint .toGeneralSubtrees(NameConstraint.parseNameConstraintsList(excluded)); byte[] extdata = new NameConstraints(permittedSubtrees, excludedSubtrees).toASN1Primitive().getEncoded(); extensions.add(new Extension(Extension.nameConstraints, false, extdata)); final KeyPair testkeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA); X509Certificate cacert = CertTools.genSelfCertForPurpose("C=SE,CN=Test Name Constraints CA", 365, null, testkeys.getPrivate(), testkeys.getPublic(), AlgorithmConstants.SIGALG_SHA1_WITH_RSA, true, X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign, null, null, "BC", true, extensions); // Allowed subject DNs final X500Name validDN = new X500Name("C=SE,CN=example.com"); // re-used below CertTools.checkNameConstraints(cacert, validDN, null); CertTools.checkNameConstraints(cacert, new X500Name("C=SE,CN=spacing"), null); // Allowed subject alternative names CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.dNSName, "example.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.dNSName, "x.sub.example.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "someuser@mail.example"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "user@host.com"))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.0.0.1").getAddress())))); CertTools.checkNameConstraints(cacert, validDN, new GeneralNames(new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.255.255.255").getAddress())))); // Disallowed subject DN checkNCException(cacert, new X500Name("C=DK,CN=example.com"), null, "Disallowed DN (wrong field value) was accepted"); checkNCException(cacert, new X500Name("C=SE,O=Company,CN=example.com"), null, "Disallowed DN (extra field) was accepted"); // Disallowed SAN // The commented out lines are allowed by BouncyCastle but disallowed by the RFC checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "bad.com"), "Disallowed SAN (wrong DNS name) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.dNSName, "forbidden.example.com"), "Disallowed SAN (excluded DNS subdomain) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.rfc822Name, "wronguser@host.com"), "Disallowed SAN (wrong e-mail) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("10.1.0.1").getAddress())), "Disallowed SAN (excluded IPv4 address) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("192.0.2.1").getAddress())), "Disallowed SAN (wrong IPv4 address) was accepted"); checkNCException(cacert, validDN, new GeneralName(GeneralName.iPAddress, new DEROctetString(InetAddress.getByName("2001:DB8::").getAddress())), "Disallowed SAN (IPv6 address) was accepted"); }
From source file:org.codice.ddf.condition.SignerCondition.java
License:Open Source License
private static String getExtendedCertAttribute(X500Principal principal, ASN1ObjectIdentifier identifier) { RDN[] rdNs = new X500Name(principal.getName()).getRDNs(identifier); if (rdNs != null && rdNs.length > 0) { AttributeTypeAndValue attributeTypeAndValue = rdNs[0].getFirst(); if (attributeTypeAndValue != null) { return attributeTypeAndValue.getValue().toString(); }// w ww . j ava 2 s.c o m } return ""; }
From source file:org.codice.ddf.security.ocsp.checker.OcspCheckerTest.java
License:Open Source License
@Test public void testConvertingX509CertificatesToBcCertificates() throws Exception { OcspChecker ocspChecker = new OcspChecker(factory, eventAdmin); Certificate certificate = ocspChecker.convertToBouncyCastleCert(trustedCertX509); assertThat(certificate, is(notNullValue())); assertThat(trustedCertX509.getSerialNumber(), equalTo(certificate.getSerialNumber().getValue())); assertThat(trustedCertX509.getNotAfter(), equalTo(certificate.getEndDate().getDate())); assertThat(trustedCertX509.getNotBefore(), equalTo(certificate.getStartDate().getDate())); X500Principal subjectX500Principal = trustedCertX509.getSubjectX500Principal(); X500Name x500name = new X500Name(subjectX500Principal.getName(X500Principal.RFC1779)); assertThat(x500name, equalTo(certificate.getSubject())); }
From source file:org.commonjava.util.jhttpc.INTERNAL.util.SSLUtils.java
License:Apache License
public static void extractAliases(Certificate certificate, Set<String> aliases) throws CertificateParsingException { Logger logger = LoggerFactory.getLogger(SSLUtils.class); X509Certificate cert = (X509Certificate) certificate; // logger.debug( "Extracting aliases from:\n\n{}\n\n", cert ); X500Principal x500Principal = cert.getSubjectX500Principal(); X500Name x500Name = new X500Name(x500Principal.getName(X500Principal.RFC1779)); logger.trace("Certificate X.500 name: '{}'", x500Name.toString()); RDN[] matchingRDNs = x500Name.getRDNs(BCStyle.CN); if (matchingRDNs != null && matchingRDNs.length > 0) { RDN cn = matchingRDNs[0];//www . java 2 s .co m AttributeTypeAndValue typeAndValue = cn.getFirst(); if (typeAndValue != null) { String alias = IETFUtils.valueToString(typeAndValue.getValue()); logger.trace("Found certificate alias: '{}'", alias); aliases.add(alias); } } Collection<List<?>> subjectAlternativeNames = cert.getSubjectAlternativeNames(); if (subjectAlternativeNames != null) { for (List<?> names : subjectAlternativeNames) { if (names.size() > 1 && (DNSNAME_TYPE.equals(names.get(0)))) { String alias = (String) names.get(1); logger.trace("Found subjectAlternativeName: '{}'", alias); aliases.add(alias); } } } else { logger.debug("NO SubjectAlternativeNames available!"); } }