javax.security.auth.x500.X500Principal Java Examples

The following examples show how to use javax.security.auth.x500.X500Principal. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SunX509KeyManagerImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private static X500Principal[] convertPrincipals(Principal[] principals) {
    List<X500Principal> list = new ArrayList<>(principals.length);
    for (int i = 0; i < principals.length; i++) {
        Principal p = principals[i];
        if (p instanceof X500Principal) {
            list.add((X500Principal)p);
        } else {
            try {
                list.add(new X500Principal(p.getName()));
            } catch (IllegalArgumentException e) {
                // ignore
            }
        }
    }
    return list.toArray(new X500Principal[list.size()]);
}
 
Example #2
Source File: AbstractX509KeyManager.java    From cyberduck with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @param issuers The list of acceptable CA issuer subject names or null if it does not matter which issuers are used
 * @return True if certificate matches issuer and key type
 */
protected boolean matches(final Certificate c, final String[] keyTypes, final Principal[] issuers) {
    if(!(c instanceof X509Certificate)) {
        log.warn(String.format("Certificate %s is not of type X509", c));
        return false;
    }
    if(!Arrays.asList(keyTypes).contains(c.getPublicKey().getAlgorithm())) {
        log.warn(String.format("Key type %s does not match any of %s", c.getPublicKey().getAlgorithm(),
                Arrays.toString(keyTypes)));
        return false;
    }
    if(null == issuers || Arrays.asList(issuers).isEmpty()) {
        // null if it does not matter which issuers are used
        return true;
    }
    final X500Principal issuer = ((X509Certificate) c).getIssuerX500Principal();
    if(!Arrays.asList(issuers).contains(issuer)) {
        log.warn(String.format("Issuer %s does not match", issuer));
        return false;
    }
    return true;
}
 
Example #3
Source File: X509CertificateBuilder.java    From vespa with Apache License 2.0 6 votes vote down vote up
private X509CertificateBuilder(X500Principal issuer,
                               X500Principal subject,
                               Instant notBefore,
                               Instant notAfter,
                               PublicKey certPublicKey,
                               PrivateKey caPrivateKey,
                               SignatureAlgorithm signingAlgorithm,
                               BigInteger serialNumber) {
    this.issuer = issuer;
    this.subject = subject;
    this.notBefore = notBefore;
    this.notAfter = notAfter;
    this.certPublicKey = certPublicKey;
    this.caPrivateKey = caPrivateKey;
    this.signingAlgorithm = signingAlgorithm;
    this.serialNumber = serialNumber;
}
 
Example #4
Source File: Synch3.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) {
    Subject subject = new Subject();
    final Set principals = subject.getPrincipals();
    principals.add(new X500Principal("CN=Alice"));
    new Thread() {
        {
            start();
        }
        public void run() {
            X500Principal p = new X500Principal("CN=Bob");
            while (!finished) {
                principals.add(p);
                principals.remove(p);
            }
        }
    };
    for (int i = 0; i < 1000; i++) {
        subject.getPrincipals(X500Principal.class);
    }
    finished = true;
}
 
Example #5
Source File: X509CRLSelector.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a copy of this object.
 *
 * @return the copy
 */
public Object clone() {
    try {
        X509CRLSelector copy = (X509CRLSelector)super.clone();
        if (issuerNames != null) {
            copy.issuerNames =
                    new HashSet<Object>(issuerNames);
            copy.issuerX500Principals =
                    new HashSet<X500Principal>(issuerX500Principals);
        }
        return copy;
    } catch (CloneNotSupportedException e) {
        /* Cannot happen */
        throw new InternalError(e.toString(), e);
    }
}
 
Example #6
Source File: SunX509KeyManagerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private static X500Principal[] convertPrincipals(Principal[] principals) {
    List<X500Principal> list = new ArrayList<>(principals.length);
    for (int i = 0; i < principals.length; i++) {
        Principal p = principals[i];
        if (p instanceof X500Principal) {
            list.add((X500Principal)p);
        } else {
            try {
                list.add(new X500Principal(p.getName()));
            } catch (IllegalArgumentException e) {
                // ignore
            }
        }
    }
    return list.toArray(new X500Principal[list.size()]);
}
 
Example #7
Source File: EscapedChars.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {

        String dn="CN=\\#user";
        X500Principal xp = new X500Principal(dn);

        System.out.println("RFC2253 DN is " +
            xp.getName(X500Principal.RFC2253));
        System.out.println("CANONICAL DN is is " +
            xp.getName(X500Principal.CANONICAL));

        String dn1 = xp.getName(X500Principal.CANONICAL);
        if (!(dn1.substring(3,5).equals("\\#")))
            throw new Exception("Leading # not escaped");

        X500Principal xp1 = new X500Principal(dn1);
        System.out.println("CANONICAL DN is " +
            xp1.getName(X500Principal.CANONICAL));
    }
 
Example #8
Source File: X509CertImpl.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Extract the subject or issuer X500Principal from an X509Certificate.
 * Parses the encoded form of the cert to preserve the principal's
 * ASN.1 encoding.
 */
private static X500Principal getX500Principal(X509Certificate cert,
        boolean getIssuer) throws Exception {
    byte[] encoded = cert.getEncoded();
    DerInputStream derIn = new DerInputStream(encoded);
    DerValue tbsCert = derIn.getSequence(3)[0];
    DerInputStream tbsIn = tbsCert.data;
    DerValue tmp;
    tmp = tbsIn.getDerValue();
    // skip version number if present
    if (tmp.isContextSpecific((byte)0)) {
      tmp = tbsIn.getDerValue();
    }
    // tmp always contains serial number now
    tmp = tbsIn.getDerValue();              // skip signature
    tmp = tbsIn.getDerValue();              // issuer
    if (getIssuer == false) {
        tmp = tbsIn.getDerValue();          // skip validity
        tmp = tbsIn.getDerValue();          // subject
    }
    byte[] principalBytes = tmp.toByteArray();
    return new X500Principal(principalBytes);
}
 
Example #9
Source File: X509CRLSelector.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: SSLKeyStoreLoader.java    From tessera with Apache License 2.0 6 votes vote down vote up
static TrustManager[] fromPemCertificatesFile(List<Path> trustedCertificates)
        throws GeneralSecurityException, IOException {
    final KeyStore trustStore = KeyStore.getInstance(KEYSTORE_TYPE);
    trustStore.load(null, null);

    List<X509Certificate> certificates = new ArrayList<>();

    for (Path path : trustedCertificates) {
        certificates.addAll(getCertificates(path));
    }

    for (X509Certificate certificate : certificates) {
        X500Principal principal = certificate.getSubjectX500Principal();
        trustStore.setCertificateEntry(principal.getName("RFC2253"), certificate);
    }

    final TrustManagerFactory trustManagerFactory =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return trustManagerFactory.getTrustManagers();
}
 
Example #11
Source File: X509CRLImpl.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract the issuer X500Principal from an X509CRL. Parses the encoded
 * form of the CRL to preserve the principal's ASN.1 encoding.
 *
 * Called by java.security.cert.X509CRL.getIssuerX500Principal().
 */
public static X500Principal getIssuerX500Principal(X509CRL crl) {
    try {
        byte[] encoded = crl.getEncoded();
        DerInputStream derIn = new DerInputStream(encoded);
        DerValue tbsCert = derIn.getSequence(3)[0];
        DerInputStream tbsIn = tbsCert.data;

        DerValue tmp;
        // skip version number if present
        byte nextByte = (byte)tbsIn.peekByte();
        if (nextByte == DerValue.tag_Integer) {
            tmp = tbsIn.getDerValue();
        }

        tmp = tbsIn.getDerValue();  // skip signature
        tmp = tbsIn.getDerValue();  // issuer
        byte[] principalBytes = tmp.toByteArray();
        return new X500Principal(principalBytes);
    } catch (Exception e) {
        throw new RuntimeException("Could not parse issuer", e);
    }
}
 
Example #12
Source File: X509CertImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract the subject or issuer X500Principal from an X509Certificate.
 * Parses the encoded form of the cert to preserve the principal's
 * ASN.1 encoding.
 */
private static X500Principal getX500Principal(X509Certificate cert,
        boolean getIssuer) throws Exception {
    byte[] encoded = cert.getEncoded();
    DerInputStream derIn = new DerInputStream(encoded);
    DerValue tbsCert = derIn.getSequence(3)[0];
    DerInputStream tbsIn = tbsCert.data;
    DerValue tmp;
    tmp = tbsIn.getDerValue();
    // skip version number if present
    if (tmp.isContextSpecific((byte)0)) {
      tmp = tbsIn.getDerValue();
    }
    // tmp always contains serial number now
    tmp = tbsIn.getDerValue();              // skip signature
    tmp = tbsIn.getDerValue();              // issuer
    if (getIssuer == false) {
        tmp = tbsIn.getDerValue();          // skip validity
        tmp = tbsIn.getDerValue();          // subject
    }
    byte[] principalBytes = tmp.toByteArray();
    return new X500Principal(principalBytes);
}
 
Example #13
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeysForAPILessThanM(String keyAlias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, CertificateException, UnrecoverableEntryException, NoSuchPaddingException, KeyStoreException, InvalidKeyException, IOException {
    // Generate a key pair for encryption
    Calendar start = Calendar.getInstance();
    Calendar end = Calendar.getInstance();
    end.add(Calendar.YEAR, 30);
    KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext)
            .setAlias(keyAlias)
            .setSubject(new X500Principal("CN=" + keyAlias))
            .setSerialNumber(BigInteger.TEN)
            .setStartDate(start.getTime())
            .setEndDate(end.getTime())
            .build();
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM_NAME, ANDROID_KEY_STORE_NAME);
    kpg.initialize(spec);
    kpg.generateKeyPair();

    saveEncryptedKey();
}
 
Example #14
Source File: SubjectCNMapper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
public void performMapping(Map<String,Object> contextMap, Principal principal)
{
   if(principal instanceof X500Principal == false)
      return;
   if(contextMap == null)
      throw PicketBoxMessages.MESSAGES.invalidNullArgument("contextMap");

   X509Certificate[] certs = (X509Certificate[]) contextMap.get("X509");
   if(certs != null)
   {
     SubjectCNMapping sdn = new SubjectCNMapping();
     principal = sdn.toPrinicipal(certs);
     PicketBoxLogger.LOGGER.traceMappedX500Principal(principal);
   }
   
   result.setMappedObject(principal);
}
 
Example #15
Source File: PKIXValidator.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Populate the trustedSubjects Map using the DN and public keys from
 * the list of trusted certificates
 *
 * @return Map containing each subject DN and one or more public keys
 *    tied to those DNs.
 */
private Map<X500Principal, List<PublicKey>> setTrustedSubjects() {
    Map<X500Principal, List<PublicKey>> subjectMap = new HashMap<>();

    for (X509Certificate cert : trustedCerts) {
        X500Principal dn = cert.getSubjectX500Principal();
        List<PublicKey> keys;
        if (subjectMap.containsKey(dn)) {
            keys = subjectMap.get(dn);
        } else {
            keys = new ArrayList<PublicKey>();
            subjectMap.put(dn, keys);
        }
        keys.add(cert.getPublicKey());
    }

    return subjectMap;
}
 
Example #16
Source File: SunX509KeyManagerImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
synchronized Set<X500Principal> getIssuerX500Principals() {
    // lazy initialization
    if (issuerX500Principals == null) {
        issuerX500Principals = new HashSet<X500Principal>();
        for (int i = 0; i < certificates.length; i++) {
            issuerX500Principals.add(
                        certificates[i].getIssuerX500Principal());
        }
    }
    return issuerX500Principals;
}
 
Example #17
Source File: X509CRLImpl.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * CRL constructor, revoked certs, no extensions.
 *
 * @param issuer the name of the CA issuing this CRL.
 * @param thisUpdate the Date of this issue.
 * @param nextUpdate the Date of the next CRL.
 * @param badCerts the array of CRL entries.
 *
 * @exception CRLException on parsing/construction errors.
 */
public X509CRLImpl(X500Name issuer, Date thisDate, Date nextDate,
                   X509CRLEntry[] badCerts)
    throws CRLException
{
    this.issuer = issuer;
    this.thisUpdate = thisDate;
    this.nextUpdate = nextDate;
    if (badCerts != null) {
        X500Principal crlIssuer = getIssuerX500Principal();
        X500Principal badCertIssuer = crlIssuer;
        for (int i = 0; i < badCerts.length; i++) {
            X509CRLEntryImpl badCert = (X509CRLEntryImpl)badCerts[i];
            try {
                badCertIssuer = getCertIssuer(badCert, badCertIssuer);
            } catch (IOException ioe) {
                throw new CRLException(ioe);
            }
            badCert.setCertificateIssuer(crlIssuer, badCertIssuer);
            X509IssuerSerial issuerSerial = new X509IssuerSerial
                (badCertIssuer, badCert.getSerialNumber());
            this.revokedMap.put(issuerSerial, badCert);
            this.revokedList.add(badCert);
            if (badCert.hasExtensions()) {
                this.version = 1;
            }
        }
    }
}
 
Example #18
Source File: X500PrincipalTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Inits X500Principal with byte array with wrong length field
 * checks if proper exception is thrown
 */
public void testIllegalInputArray() {
    try {
        byte[] mess = { 0x30, 0x18, 0x31, 0x0A, 0x30, 0x08, 0x06, 0x03,
                0x55, 0x04, 0x03, 0x13, 0x01, 0x42, 0x31, 0x0A, 0x30, 0x08,
                0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x01, 0x41 };
        mess[3] = 0x12;//length field
        new X500Principal(mess);

        fail("No IllegalArgumentException on input array with improper length field");
    } catch (IllegalArgumentException e) {
    }
}
 
Example #19
Source File: X509CRLSelector2Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * setIssuers(Collection <X500Principal> issuers) method testing. Tests if
 * CRLs with any issuers match the selector in the case of null issuerNames
 * criteria, if specified issuers match the selector, and if not specified
 * issuer does not match the selector.
 */
public void testSetIssuersLjava_util_Collection() {
    X509CRLSelector selector = new X509CRLSelector();
    X500Principal iss1 = new X500Principal("O=First Org.");
    X500Principal iss2 = new X500Principal("O=Second Org.");
    X500Principal iss3 = new X500Principal("O=Third Org.");
    TestCRL crl1 = new TestCRL(iss1);
    TestCRL crl2 = new TestCRL(iss2);
    TestCRL crl3 = new TestCRL(iss3);

    selector.setIssuers(null);
    assertTrue("Any CRL issuers should match in the case of null issuers.",
            selector.match(crl1) && selector.match(crl2));

    ArrayList<X500Principal> issuers = new ArrayList<X500Principal>(2);
    issuers.add(iss1);
    issuers.add(iss2);
    selector.setIssuers(issuers);
    assertTrue("The CRL should match the selection criteria.", selector
            .match(crl1)
            && selector.match(crl2));
    assertFalse("The CRL should not match the selection criteria.",
            selector.match(crl3));
    issuers.add(iss3);
    assertFalse("The internal issuer collection is not protected "
            + "against the modifications.", selector.match(crl3));
}
 
Example #20
Source File: TrustRootIndex.java    From styT with Apache License 2.0 5 votes vote down vote up
public BasicTrustRootIndex(X509Certificate... caCerts) {
  subjectToCaCerts = new LinkedHashMap<>();
  for (X509Certificate caCert : caCerts) {
    X500Principal subject = caCert.getSubjectX500Principal();
    Set<X509Certificate> subjectCaCerts = subjectToCaCerts.get(subject);
    if (subjectCaCerts == null) {
      subjectCaCerts = new LinkedHashSet<>(1);
      subjectToCaCerts.put(subject, subjectCaCerts);
    }
    subjectCaCerts.add(caCert);
  }
}
 
Example #21
Source File: ExtensibleTrustManagerImplTest.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldForwardCallsToMockForMatchingAlternativeNames() throws CertificateException {
    when(topOfChain.getSubjectX500Principal())
            .thenReturn(new X500Principal("CN=example.com, OU=Smarthome, O=Eclipse, C=DE"));
    when(topOfChain.getSubjectAlternativeNames())
            .thenReturn(constructAlternativeNames("example1.com", "example.org"));

    subject.checkClientTrusted(chain, "just");

    verify(trustmanager).checkClientTrusted(chain, "just", (Socket) null);
    verifyNoMoreInteractions(trustmanager);
}
 
Example #22
Source File: LDAPCertStoreHelper.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public X509CertSelector wrap(X509CertSelector selector,
                             X500Principal certSubject,
                             String ldapDN)
    throws IOException
{
    return new LDAPCertStore.LDAPCertSelector(selector, certSubject, ldapDN);
}
 
Example #23
Source File: CertificateUtils.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static byte[] createCSR(DistinguishedName distingueshedName, KeyPair keyPair) {
   String csrSignatureAlgorithm = RaPropertiesLoader.getProperty("csr.signature.algorithm");

   try {
      X500Principal x500Principal = new X500Principal(distingueshedName.asNormalizedEhealthDN());
      JcaPKCS10CertificationRequestBuilder csrBuilder = new JcaPKCS10CertificationRequestBuilder(x500Principal, keyPair.getPublic());
      PKCS10CertificationRequest csr = csrBuilder.build((new JcaContentSignerBuilder(csrSignatureAlgorithm)).setProvider(new BouncyCastleProvider()).build(keyPair.getPrivate()));
      return csr.getEncoded();
   } catch (OperatorCreationException var6) {
      throw new IllegalArgumentException(var6);
   } catch (IOException var7) {
      throw new IllegalArgumentException(var7);
   }
}
 
Example #24
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Generates a RSA public/private key pair to encrypt AES key
 * @param context
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 */
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void generateKeyPair(Context context) throws KeyStoreException,
        CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException,
        InvalidAlgorithmParameterException {

    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);

    if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
        // generate a RSA key pair to encrypt/decrypt AES key from preferences
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", KEY_STORE_ANDROID);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS_AMAZE)
                .setSubject(new X500Principal("CN=" + KEY_ALIAS_AMAZE))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();

        keyPairGenerator.initialize(spec);
        keyPairGenerator.generateKeyPair();
    }
}
 
Example #25
Source File: SSLClientCertificateRequest.java    From 365browser with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new asynchronous request to select a client certificate.
 *
 * @param nativePtr         The native object responsible for this request.
 * @param window            A WindowAndroid instance.
 * @param keyTypes          The list of supported key exchange types.
 * @param encodedPrincipals The list of CA DistinguishedNames.
 * @param hostName          The server host name is available (empty otherwise).
 * @param port              The server port if available (0 otherwise).
 * @return                  true on success.
 * Note that nativeOnSystemRequestComplete will be called iff this method returns true.
 */
@CalledByNative
private static boolean selectClientCertificate(final long nativePtr, final WindowAndroid window,
        final String[] keyTypes, byte[][] encodedPrincipals, final String hostName,
        final int port) {
    ThreadUtils.assertOnUiThread();

    final Activity activity = window.getActivity().get();
    if (activity == null) {
        Log.w(TAG, "Certificate request on GC'd activity.");
        return false;
    }

    // Build the list of principals from encoded versions.
    Principal[] principals = null;
    if (encodedPrincipals.length > 0) {
        principals = new X500Principal[encodedPrincipals.length];
        try {
            for (int n = 0; n < encodedPrincipals.length; n++) {
                principals[n] = new X500Principal(encodedPrincipals[n]);
            }
        } catch (Exception e) {
            Log.w(TAG, "Exception while decoding issuers list: " + e);
            return false;
        }
    }

    KeyChainCertSelectionCallback callback =
            new KeyChainCertSelectionCallback(activity.getApplicationContext(),
                nativePtr);
    KeyChainCertSelectionWrapper keyChain = new KeyChainCertSelectionWrapper(activity,
            callback, keyTypes, principals, hostName, port, null);
    maybeShowCertSelection(keyChain, callback,
            new CertSelectionFailureDialog(activity));

    // We've taken ownership of the native ssl request object.
    return true;
}
 
Example #26
Source File: P11KeyStore.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void storeCert(String alias, X509Certificate cert)
            throws PKCS11Exception, CertificateException {

    ArrayList<CK_ATTRIBUTE> attrList = new ArrayList<CK_ATTRIBUTE>();
    attrList.add(ATTR_TOKEN_TRUE);
    attrList.add(ATTR_CLASS_CERT);
    attrList.add(ATTR_X509_CERT_TYPE);
    attrList.add(new CK_ATTRIBUTE(CKA_SUBJECT,
                            cert.getSubjectX500Principal().getEncoded()));
    attrList.add(new CK_ATTRIBUTE(CKA_ISSUER,
                            cert.getIssuerX500Principal().getEncoded()));
    attrList.add(new CK_ATTRIBUTE(CKA_SERIAL_NUMBER,
                            cert.getSerialNumber().toByteArray()));
    attrList.add(new CK_ATTRIBUTE(CKA_VALUE, cert.getEncoded()));

    if (alias != null) {
        attrList.add(new CK_ATTRIBUTE(CKA_LABEL, alias));
        attrList.add(new CK_ATTRIBUTE(CKA_ID, alias));
    } else {
        // ibutton requires something to be set
        // - alias must be unique
        attrList.add(new CK_ATTRIBUTE(CKA_ID,
                    getID(cert.getSubjectX500Principal().getName
                                    (X500Principal.CANONICAL), cert)));
    }

    Session session = null;
    try {
        session = token.getOpSession();
        token.p11.C_CreateObject(session.id(),
                    attrList.toArray(new CK_ATTRIBUTE[attrList.size()]));
    } finally {
        token.releaseSession(session);
    }
}
 
Example #27
Source File: X509CRLImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return the issuer as X500Principal. Overrides method in X509CRL
 * to provide a slightly more efficient version.
 */
public X500Principal getIssuerX500Principal() {
    if (issuerPrincipal == null) {
        issuerPrincipal = issuer.asX500Principal();
    }
    return issuerPrincipal;
}
 
Example #28
Source File: X500PrincipalTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Inits X500Principal with the string with special characters - \\'space''space'B
 * gets Name in CANONICAL format
 * compares with expected value of name - \'space''space'b
 */
public void testNameSpaces_CANONICAL_02() throws Exception {
    String dn = "CN=\\  B";
    X500Principal principal = new X500Principal(dn);
    String s = principal.getName(X500Principal.CANONICAL);
    assertEquals("cn=b", s);

}
 
Example #29
Source File: DistinguishedNameParser.java    From TrustKit-Android with MIT License 5 votes vote down vote up
public DistinguishedNameParser(X500Principal principal) {
    // RFC2253 is used to ensure we get attributes in the reverse
    // order of the underlying ASN.1 encoding, so that the most
    // significant values of repeated attributes occur first.
    this.dn = principal.getName(X500Principal.RFC2253);
    this.length = this.dn.length();
}
 
Example #30
Source File: DistributionPointFetcher.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Fetch CRLs from certStores.
 *
 * @throws CertStoreException if there is an error retrieving the CRLs from
 *         one of the CertStores and no other CRLs are retrieved from
 *         the other CertStores. If more than one CertStore throws an
 *         exception then the one from the last CertStore is thrown.
 */
private static Collection<X509CRL> getCRLs(X500Name name,
                                           X500Principal certIssuer,
                                           List<CertStore> certStores)
    throws CertStoreException
{
    if (debug != null) {
        debug.println("Trying to fetch CRL from DP " + name);
    }
    X509CRLSelector xcs = new X509CRLSelector();
    xcs.addIssuer(name.asX500Principal());
    xcs.addIssuer(certIssuer);
    Collection<X509CRL> crls = new ArrayList<>();
    CertStoreException savedCSE = null;
    for (CertStore store : certStores) {
        try {
            for (CRL crl : store.getCRLs(xcs)) {
                crls.add((X509CRL)crl);
            }
        } catch (CertStoreException cse) {
            if (debug != null) {
                debug.println("Exception while retrieving " +
                    "CRLs: " + cse);
                cse.printStackTrace();
            }
            savedCSE = new PKIX.CertStoreTypeException(store.getType(),cse);
        }
    }
    // only throw CertStoreException if no CRLs are retrieved
    if (crls.isEmpty() && savedCSE != null) {
        throw savedCSE;
    } else {
        return crls;
    }
}