public static void main(String[] args) throws Exception { byte[] data = "Hello".getBytes(); X500Name n = new X500Name("cn=Me"); CertAndKeyGen cakg = new CertAndKeyGen("RSA", "SHA256withRSA"); cakg.generate(1024); X509Certificate cert = cakg.getSelfCertificate(n, 1000); MessageDigest md = MessageDigest.getInstance("SHA-256"); PKCS9Attributes authed = new PKCS9Attributes(new PKCS9Attribute[]{ new PKCS9Attribute(PKCS9Attribute.CONTENT_TYPE_OID, ContentInfo.DATA_OID), new PKCS9Attribute(PKCS9Attribute.MESSAGE_DIGEST_OID, md.digest(data)), }); Signature s = Signature.getInstance("SHA256withRSA"); s.initSign(cakg.getPrivateKey()); s.update(authed.getDerEncoding()); byte[] sig = s.sign(); SignerInfo signerInfo = new SignerInfo( n, cert.getSerialNumber(), AlgorithmId.get("SHA-256"), authed, AlgorithmId.get("SHA256withRSA"), sig, null ); PKCS7 pkcs7 = new PKCS7( new AlgorithmId[] {signerInfo.getDigestAlgorithmId()}, new ContentInfo(data), new X509Certificate[] {cert}, new SignerInfo[] {signerInfo}); if (pkcs7.verify(signerInfo, data) == null) { throw new Exception("Not verified"); } }
/** * Returns the X.509 certificate listed in this PKCS7 block * which has a matching serial number and Issuer name, or * null if one is not found. * * @param serial the serial number of the certificate to retrieve. * @param issuerName the Distinguished Name of the Issuer. */ public X509Certificate getCertificate(BigInteger serial, X500Name issuerName) { if (certificates != null) { if (certIssuerNames == null) populateCertIssuerNames(); for (int i = 0; i < certificates.length; i++) { X509Certificate cert = certificates[i]; BigInteger thisSerial = cert.getSerialNumber(); if (serial.equals(thisSerial) && issuerName.equals(certIssuerNames[i])) { return cert; } } } return null; }
/** * Write the certificate file with a digital signature. */ private void writeSignatureBlock(Signature signature, X509Certificate publicKey, PrivateKey privateKey) throws IOException, GeneralSecurityException { SignerInfo signerInfo = new SignerInfo( new X500Name(publicKey.getIssuerX500Principal().getName()), publicKey.getSerialNumber(), AlgorithmId.get(DIGEST_ALGORITHM), AlgorithmId.get(privateKey.getAlgorithm()), signature.sign()); PKCS7 pkcs7 = new PKCS7( new AlgorithmId[]{AlgorithmId.get(DIGEST_ALGORITHM)}, new ContentInfo(ContentInfo.DATA_OID, null), new X509Certificate[]{publicKey}, new SignerInfo[]{signerInfo}); pkcs7.encodeSignedData(mOutputJar); }
/** Write the certificate file with a digital signature. */ private void writeSignatureBlock(Signature signature, X509Certificate publicKey, PrivateKey privateKey) throws IOException, GeneralSecurityException { SignerInfo signerInfo = new SignerInfo( new X500Name(publicKey.getIssuerX500Principal().getName()), publicKey.getSerialNumber(), AlgorithmId.get(DIGEST_ALGORITHM), AlgorithmId.get(privateKey.getAlgorithm()), signature.sign()); PKCS7 pkcs7 = new PKCS7( new AlgorithmId[] { AlgorithmId.get(DIGEST_ALGORITHM) }, new ContentInfo(ContentInfo.DATA_OID, null), new X509Certificate[] { publicKey }, new SignerInfo[] { signerInfo }); pkcs7.encodeSignedData(mOutputJar); }
/** * Parse an argument of the form passed to setIssuerNames, * returning a Collection of issuerX500Principals. * Throw an IOException if the argument is malformed. * * @param names a {@code Collection} of names. Each entry is a * String or a byte array (the name, in string or ASN.1 * DER encoded form, respectively). <Code>Null</Code> is * not an acceptable value. * @return a HashSet of issuerX500Principals * @throws IOException if a parsing error occurs */ private static HashSet<X500Principal> parseIssuerNames(Collection<Object> names) throws IOException { HashSet<X500Principal> x500Principals = new HashSet<X500Principal>(); for (Iterator<Object> t = names.iterator(); t.hasNext(); ) { Object nameObject = t.next(); if (nameObject instanceof String) { x500Principals.add(new X500Name((String)nameObject).asX500Principal()); } else { try { x500Principals.add(new X500Principal((byte[])nameObject)); } catch (IllegalArgumentException e) { throw (IOException)new IOException("Invalid name").initCause(e); } } } return x500Principals; }
public SignerInfo(X500Name issuerName, BigInteger serial, AlgorithmId digestAlgorithmId, PKCS9Attributes authenticatedAttributes, AlgorithmId digestEncryptionAlgorithmId, byte[] encryptedDigest, PKCS9Attributes unauthenticatedAttributes) { this.version = BigInteger.ONE; this.issuerName = issuerName; this.certificateSerialNumber = serial; this.digestAlgorithmId = digestAlgorithmId; this.authenticatedAttributes = authenticatedAttributes; this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId; this.encryptedDigest = encryptedDigest; this.unauthenticatedAttributes = unauthenticatedAttributes; }
/** * Create the signed certificate request. This will later be * retrieved in either string or binary format. * * @param subject identifies the signer (by X.500 name). * @param signature private key and signing algorithm to use. * @exception IOException on errors. * @exception CertificateException on certificate handling errors. * @exception SignatureException on signature handling errors. */ public void encodeAndSign(X500Name subject, Signature signature) throws CertificateException, IOException, SignatureException { DerOutputStream out, scratch; byte[] certificateRequestInfo; byte[] sig; if (encoded != null) throw new SignatureException("request is already signed"); this.subject = subject; /* * Encode cert request info, wrap in a sequence for signing */ scratch = new DerOutputStream(); scratch.putInteger(BigInteger.ZERO); // PKCS #10 v1.0 subject.encode(scratch); // X.500 name scratch.write(subjectPublicKeyInfo.getEncoded()); // public key attributeSet.encode(scratch); out = new DerOutputStream(); out.write(DerValue.tag_Sequence, scratch); // wrap it! certificateRequestInfo = out.toByteArray(); scratch = out; /* * Sign it ... */ signature.update(certificateRequestInfo, 0, certificateRequestInfo.length); sig = signature.sign(); /* * Build guts of SIGNED macro */ AlgorithmId algId = null; try { algId = AlgorithmId.get(signature.getAlgorithm()); } catch (NoSuchAlgorithmException nsae) { throw new SignatureException(nsae); } algId.encode(scratch); // sig algorithm scratch.putBitString(sig); // sig /* * Wrap those guts in a sequence */ out = new DerOutputStream(); out.write(DerValue.tag_Sequence, scratch); encoded = out.toByteArray(); }
/** * Check if the certificate allows use of the given DNS name. * * From RFC2818: * If a subjectAltName extension of type dNSName is present, that MUST * be used as the identity. Otherwise, the (most specific) Common Name * field in the Subject field of the certificate MUST be used. Although * the use of the Common Name is existing practice, it is deprecated and * Certification Authorities are encouraged to use the dNSName instead. * * Matching is performed using the matching rules specified by * [RFC2459]. If more than one identity of a given type is present in * the certificate (e.g., more than one dNSName name, a match in any one * of the set is considered acceptable.) */ private void matchDNS(String expectedName, X509Certificate cert) throws CertificateException { Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames(); if (subjAltNames != null) { boolean foundDNS = false; for ( List<?> next : subjAltNames) { if (((Integer)next.get(0)).intValue() == ALTNAME_DNS) { foundDNS = true; String dnsName = (String)next.get(1); if (isMatched(expectedName, dnsName)) { return; } } } if (foundDNS) { // if certificate contains any subject alt names of type DNS // but none match, reject throw new CertificateException("No subject alternative DNS " + "name matching " + expectedName + " found."); } } X500Name subjectName = getSubjectX500Name(cert); DerValue derValue = subjectName.findMostSpecificAttribute (X500Name.commonName_oid); if (derValue != null) { try { if (isMatched(expectedName, derValue.getAsString())) { return; } } catch (IOException e) { // ignore } } String msg = "No name matching " + expectedName + " found"; throw new CertificateException(msg); }
/** * Compares the specified Object with this <code>X500Principal</code> * for equality. * * <p> * * @param o Object to be compared for equality with this * <code>X500Principal</code>. * * @return true if the specified Object is equal equal to this * <code>X500Principal</code>. */ public boolean equals(Object o) { if (o == null) return false; if (this == o) return true; if (o instanceof X500Principal) { X500Principal that = (X500Principal)o; try { X500Name thatX500Name = new X500Name(that.getName()); return thisX500Name.equals(thatX500Name); } catch (Exception e) { // any parsing exceptions, return false return false; } } else if (o instanceof Principal) { // this will return 'true' if 'o' is a sun.security.x509.X500Name // and the X500Names are equal return o.equals(thisX500Name); } return false; }
/** * Reads this object from a stream (i.e., deserializes it) */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, java.io.NotActiveException, ClassNotFoundException { s.defaultReadObject(); // re-create thisX500Name thisX500Name = new X500Name(name); }
/** * Searches for entries matching given user id, baseDn and attribute. * * @param name LDAP/AD user id * @param baseDn user/role baseDn * @param attributeName attribute name to search for. * @return list of {@link X500Name} matching the given user id. * @throws LdapException if there are any errors searching LDAP or invalid user id. */ private @Nonnull List<X500Name> search(String name, String baseDn, String attributeName) throws LdapException { SearchExecutor executor = new SearchExecutor(); executor.setBaseDn(baseDn); executor.setSearchScope(SearchScope.SUBTREE); executor.setSearchCache(cache); // Use "*" to query all the attributes. SearchFilter filter = new SearchFilter(String.format("(%s=%s)", attributeName, name)); SearchResult result = executor.search(pcf, filter).getResult(); return result.getEntries().stream().map(entry -> { try { return new X500Name(entry.getDn()); } catch (IOException ex) { throw new RuntimeException(ex); } }).collect(Collectors.toList()); }
/** * Return the subject of a certificate as X500Name, by reparsing if * necessary. X500Name should only be used if access to name components * is required, in other cases X500Principal is to be preferred. * * This method is currently used from within JSSE, do not remove. */ public static X500Name getSubjectX500Name(X509Certificate cert) throws CertificateParsingException { try { Principal subjectDN = cert.getSubjectDN(); if (subjectDN instanceof X500Name) { return (X500Name)subjectDN; } else { X500Principal subjectX500 = cert.getSubjectX500Principal(); return new X500Name(subjectX500.getEncoded()); } } catch (IOException e) { throw(CertificateParsingException) new CertificateParsingException().initCause(e); } }
/** * Parse an argument of the form passed to setIssuerNames, * returning a Collection of issuerX500Principals. * Throw an IOException if the argument is malformed. * * @param names a {@code Collection} of names. Each entry is a * String or a byte array (the name, in string or ASN.1 * DER encoded form, respectively). <Code>Null</Code> is * not an acceptable value. * @return a HashSet of issuerX500Principals * @throws IOException if a parsing error occurs */ private static HashSet<X500Principal> parseIssuerNames(Collection<Object> names) throws IOException { HashSet<X500Principal> x500Principals = new HashSet<>(); for (Iterator<Object> t = names.iterator(); t.hasNext(); ) { Object nameObject = t.next(); if (nameObject instanceof String) { x500Principals.add(new X500Name((String)nameObject).asX500Principal()); } else { try { x500Principals.add(new X500Principal((byte[])nameObject)); } catch (IllegalArgumentException e) { throw (IOException)new IOException("Invalid name").initCause(e); } } } return x500Principals; }
@Test public void testCheckToken() throws Exception { CertAndKeyGen gen = new CertAndKeyGen("RSA", "SHA1WithRSA", null); gen.generate(1024); X509Certificate cert = gen.getSelfCertificate(new X500Name("CN=ROOT"), new Date(), 10000000); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); String alias = "temp"; String loc = "./temp.jks"; String password = "changeit"; ks.load(null, password.toCharArray()); ks.setCertificateEntry(alias, cert); FileOutputStream fos = new FileOutputStream(loc); ks.store(fos, password.toCharArray()); fos.close(); Mockito.when(configSvc.getProxyConfigurationSetting( PlatformConfigurationKey.APP_TRUSTSTORE)).thenReturn(loc); Mockito.when(configSvc.getProxyConfigurationSetting( PlatformConfigurationKey.APP_TRUSTSTORE_PASSWORD)) .thenReturn(password); Mockito.when(configSvc.getProxyConfigurationSetting( PlatformConfigurationKey.APP_TRUSTSTORE_BSS_ALIAS)) .thenReturn(alias); String token = UUID.randomUUID().toString(); MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(token.getBytes(StandardCharsets.UTF_8)); byte[] tokenHash = md.digest(); Key key = gen.getPrivateKey(); Cipher c = Cipher.getInstance(key.getAlgorithm()); c.init(Cipher.ENCRYPT_MODE, key); String tokenSignature = Base64 .encodeBase64URLSafeString(c.doFinal(tokenHash)); boolean check = platformSvc.checkToken(token, tokenSignature); assertTrue(check); Files.delete(new File(loc).toPath()); }
public SignerInfo(X500Name issuerName, BigInteger serial, AlgorithmId digestAlgorithmId, AlgorithmId digestEncryptionAlgorithmId, byte[] encryptedDigest) { this.version = BigInteger.ONE; this.issuerName = issuerName; this.certificateSerialNumber = serial; this.digestAlgorithmId = digestAlgorithmId; this.digestEncryptionAlgorithmId = digestEncryptionAlgorithmId; this.encryptedDigest = encryptedDigest; }
/** * Populate array of Issuer DNs from certificates and convert * each Principal to type X500Name if necessary. */ private void populateCertIssuerNames() { if (certificates == null) return; certIssuerNames = new Principal[certificates.length]; for (int i = 0; i < certificates.length; i++) { X509Certificate cert = certificates[i]; Principal certIssuerName = cert.getIssuerDN(); if (!(certIssuerName instanceof X500Name)) { // must extract the original encoded form of DN for // subsequent name comparison checks (converting to a // String and back to an encoded DN could cause the // types of String attribute values to be changed) try { X509CertInfo tbsCert = new X509CertInfo(cert.getTBSCertificate()); certIssuerName = (Principal) tbsCert.get(X509CertInfo.ISSUER + "." + X509CertInfo.DN_NAME); } catch (Exception e) { // error generating X500Name object from the cert's // issuer DN, leave name as is. } } certIssuerNames[i] = certIssuerName; } }
/** * Assembles a PKCS #7 signed data message that optionally includes a * signature timestamp. * * @param signature the signature bytes * @param signerChain the signer's X.509 certificate chain * @param content the content that is signed; specify null to not include * it in the PKCS7 data * @param signatureAlgorithm the name of the signature algorithm * @param tsaURI the URI of the Timestamping Authority; or null if no * timestamp is requested * @param tSAPolicyID the TSAPolicyID of the Timestamping Authority as a * numerical object identifier; or null if we leave the TSA server * to choose one. This argument is only used when tsaURI is provided * @return the bytes of the encoded PKCS #7 signed data message * @throws NoSuchAlgorithmException The exception is thrown if the signature * algorithm is unrecognised. * @throws CertificateException The exception is thrown if an error occurs * while processing the signer's certificate or the TSA's * certificate. * @throws IOException The exception is thrown if an error occurs while * generating the signature timestamp or while generating the signed * data message. */ public static byte[] generateSignedData(byte[] signature, X509Certificate[] signerChain, byte[] content, String signatureAlgorithm, URI tsaURI, String tSAPolicyID) throws CertificateException, IOException, NoSuchAlgorithmException { // Generate the timestamp token PKCS9Attributes unauthAttrs = null; if (tsaURI != null) { // Timestamp the signature HttpTimestamper tsa = new HttpTimestamper(tsaURI); byte[] tsToken = generateTimestampToken(tsa, tSAPolicyID, signature); // Insert the timestamp token into the PKCS #7 signer info element // (as an unsigned attribute) unauthAttrs = new PKCS9Attributes(new PKCS9Attribute[]{ new PKCS9Attribute( PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_STR, tsToken)}); } // Create the SignerInfo X500Name issuerName = X500Name.asX500Name(signerChain[0].getIssuerX500Principal()); BigInteger serialNumber = signerChain[0].getSerialNumber(); String encAlg = AlgorithmId.getEncAlgFromSigAlg(signatureAlgorithm); String digAlg = AlgorithmId.getDigAlgFromSigAlg(signatureAlgorithm); SignerInfo signerInfo = new SignerInfo(issuerName, serialNumber, AlgorithmId.get(digAlg), null, AlgorithmId.get(encAlg), signature, unauthAttrs); // Create the PKCS #7 signed data message SignerInfo[] signerInfos = {signerInfo}; AlgorithmId[] algorithms = {signerInfo.getDigestAlgorithmId()}; // Include or exclude content ContentInfo contentInfo = (content == null) ? new ContentInfo(ContentInfo.DATA_OID, null) : new ContentInfo(content); PKCS7 pkcs7 = new PKCS7(algorithms, contentInfo, signerChain, signerInfos); ByteArrayOutputStream p7out = new ByteArrayOutputStream(); pkcs7.encodeSignedData(p7out); return p7out.toByteArray(); }
/** * Parses an encoded, signed PKCS #10 certificate request, verifying * the request's signature as it does so. This constructor would * typically be used by a Certificate Authority, from which a new * certificate would then be constructed. * * @param data the DER-encoded PKCS #10 request. * @exception IOException for low level errors reading the data * @exception SignatureException when the signature is invalid * @exception NoSuchAlgorithmException when the signature * algorithm is not supported in this environment */ public PKCS10(byte[] data) throws IOException, SignatureException, NoSuchAlgorithmException { DerInputStream in; DerValue[] seq; AlgorithmId id; byte[] sigData; Signature sig; encoded = data; // // Outer sequence: request, signature algorithm, signature. // Parse, and prepare to verify later. // in = new DerInputStream(data); seq = in.getSequence(3); if (seq.length != 3) throw new IllegalArgumentException("not a PKCS #10 request"); data = seq[0].toByteArray(); // reusing this variable id = AlgorithmId.parse(seq[1]); sigData = seq[2].getBitString(); // // Inner sequence: version, name, key, attributes // BigInteger serial; DerValue val; serial = seq[0].data.getBigInteger(); if (!serial.equals(BigInteger.ZERO)) throw new IllegalArgumentException("not PKCS #10 v1"); subject = new X500Name(seq[0].data); subjectPublicKeyInfo = X509Key.parse(seq[0].data.getDerValue()); // Cope with a somewhat common illegal PKCS #10 format if (seq[0].data.available() != 0) attributeSet = new PKCS10Attributes(seq[0].data); else attributeSet = new PKCS10Attributes(); if (seq[0].data.available() != 0) throw new IllegalArgumentException("illegal PKCS #10 data"); // // OK, we parsed it all ... validate the signature using the // key and signature algorithm we found. // try { sig = Signature.getInstance(id.getName()); sig.initVerify(subjectPublicKeyInfo); sig.update(data); if (!sig.verify(sigData)) throw new SignatureException("Invalid PKCS #10 signature"); } catch (InvalidKeyException e) { throw new SignatureException("invalid key"); } }
/** * get hop distance of one GeneralName from another in links where * the names need not have an ancestor/descendant relationship. * For example, the hop distance from ou=D,ou=C,o=B,c=US to * ou=F,ou=E,ou=C,o=B,c=US is 3: D->C, C->E, E->F. The hop distance * from ou=C,o=B,c=US to ou=D,ou=C,o=B,c=US is -1: C->D * * @param base GeneralName * @param test GeneralName to be tested against base * @param incomparable the value to return if the names are * incomparable * @return distance of test name from base measured in hops in the * namespace hierarchy, where 0 means exact match. Result * is positive if path is some number of up hops followed by * some number of down hops; result is negative if path is * some number of down hops. */ static int hops(GeneralNameInterface base, GeneralNameInterface test, int incomparable) { int baseRtest = base.constrains(test); switch (baseRtest) { case GeneralNameInterface.NAME_DIFF_TYPE: if (debug != null) { debug.println("Builder.hops(): Names are different types"); } return incomparable; case GeneralNameInterface.NAME_SAME_TYPE: /* base and test are in different subtrees */ break; case GeneralNameInterface.NAME_MATCH: /* base matches test */ return 0; case GeneralNameInterface.NAME_WIDENS: /* base is ancestor of test */ return (test.subtreeDepth()-base.subtreeDepth()); case GeneralNameInterface.NAME_NARROWS: /* base is descendant of test */ return (test.subtreeDepth()-base.subtreeDepth()); default: // should never occur return incomparable; } /* names are in different subtrees */ if (base.getType() != GeneralNameInterface.NAME_DIRECTORY) { if (debug != null) { debug.println("Builder.hops(): hopDistance not implemented " + "for this name type"); } return incomparable; } X500Name baseName = (X500Name)base; X500Name testName = (X500Name)test; X500Name commonName = baseName.commonAncestor(testName); if (commonName == null) { if (debug != null) { debug.println("Builder.hops(): Names are in different " + "namespaces"); } return incomparable; } else { int commonDistance = commonName.subtreeDepth(); int baseDistance = baseName.subtreeDepth(); int testDistance = testName.subtreeDepth(); return (baseDistance + testDistance - (2 * commonDistance)); } }
@Override public int compare(X509Certificate cert1, X509Certificate cert2) { /* * if either cert certifies the target, always * put at head of list. */ X500Principal targetSubject = buildParams.targetSubject(); if (cert1.getSubjectX500Principal().equals(targetSubject)) { return -1; } if (cert2.getSubjectX500Principal().equals(targetSubject)) { return 1; } int targetDist1; int targetDist2; try { X500Name targetSubjectName = X500Name.asX500Name(targetSubject); targetDist1 = Builder.targetDistance( null, cert1, targetSubjectName); targetDist2 = Builder.targetDistance( null, cert2, targetSubjectName); } catch (IOException e) { if (debug != null) { debug.println("IOException in call to Builder.targetDistance"); e.printStackTrace(); } throw new ClassCastException ("Invalid target subject distinguished name"); } if (targetDist1 == targetDist2) return 0; if (targetDist1 == -1) return 1; if (targetDist1 < targetDist2) return -1; return 1; }
/** * Searches role name for given userDN. * * @param userDN userDN * @return userDN roles. * @throws LdapException if there are any errors searching LDAP. */ public @Nonnull List<String> getRoles(String userDN) throws LdapException { List<X500Name> names = search(userDN, config.getRoleBaseDn(), config.getRoleAttribute()); return names.stream().map(x -> { try { return x.getCommonName(); } catch (IOException e) { throw new RuntimeException(e); } }).collect(Collectors.toList()); }
/** * Creates an LDAPCRLSelector. * * @param selector the X509CRLSelector to wrap * @param certIssuers the issuer DNs of the CRLs that you want * to retrieve via LDAP * @param ldapDN the LDAP DN where the CRL is stored */ LDAPCRLSelector(X509CRLSelector selector, Collection<X500Principal> certIssuers, String ldapDN) throws IOException { this.selector = selector == null ? new X509CRLSelector() : selector; this.certIssuers = certIssuers; issuerNames = new HashSet<>(); issuerNames.add(ldapDN); issuers = new HashSet<>(); issuers.add(new X500Name(ldapDN).asX500Principal()); }
/** * Reads this object from a stream (i.e., deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, java.io.NotActiveException, ClassNotFoundException { // re-create thisX500Name thisX500Name = new X500Name((byte[])s.readObject()); }
@Override public OneOpsUser loadUserByUsername(String username) throws UsernameNotFoundException { try { List<X500Name> x500Names = ldapClient.searchUser(username); if (x500Names.size() == 0) { throw new UsernameNotFoundException("Can't load the user details for " + username); } X500Name x500Name = x500Names.get(0); List<SimpleGrantedAuthority> authorities = singletonList(new SimpleGrantedAuthority(USER.authority())); return new OneOpsUser(username, null, authorities, x500Name.getCommonName(), DEFAULT_DOMAIN); } catch (IOException | LdapException e) { throw new UsernameNotFoundException("Can't load the user details for " + username, e); } }
public static void main(String args[]) throws Exception { try { // This used to throw java.lang.OutOfMemoryError, from which no // recovery is possible. // In the example below, the correct DN would be: "CN=John Doe" X500Name name = new X500Name("John Doe"); System.out.println(name.toString()); } catch (IOException ioe) { } }
/** * Returns the common name from LDAP entry. Usually, AD common name has * <b>"FullName - UserId"</b> format. If that's the case, only full name * is returned as the common name. * * @param ldapUser ldap entry * @param username default name if there is no cn. * @return common name. */ private String getCommonName(LdapEntry ldapUser, String username) { String cn; try { cn = new X500Name(ldapUser.getDn()).getCommonName(); if (cn != null && cn.endsWith(username)) { cn = cn.split("-")[0].trim(); } } catch (IOException e) { cn = username; } return cn; }