Java 类java.security.Certificate 实例源码

项目:netbeansplugins    文件:KeyTool.java   
private void keystorecerts2Hashtable(KeyStore keystore, Hashtable hashtable)
throws Exception {
    Enumeration enumeration = keystore.aliases();
    do
    {
        if(!enumeration.hasMoreElements())
            break;
        String s = (String)enumeration.nextElement();
        java.security.cert.Certificate certificate = keystore.getCertificate(s);
        if(certificate != null) {
            java.security.Principal principal = ((X509Certificate)certificate).getSubjectDN();
            Vector vector = (Vector)hashtable.get(principal);
            if(vector == null) {
                vector = new Vector();
                vector.addElement(certificate);
            } else
                if(!vector.contains(certificate))
                    vector.addElement(certificate);
            hashtable.put(principal, vector);
        }
    } while(true);
}
项目:In-the-Box-Fork    文件:Identity2Test.java   
/**
 * @tests java.security.Identity#certificates()
 */
@TestTargetNew(
    level = TestLevel.COMPLETE,
    notes = "",
    method = "certificates",
    args = {}
)
public void test_certificates() throws Exception {
           IdentitySubclass sub = new IdentitySubclass("test",
                   new IdentityScopeSubclass());
           CertificateFactory cf = CertificateFactory.getInstance("X.509");
           X509Certificate cert[] = new X509Certificate[1];
           cert[0] = (X509Certificate) cf.generateCertificate(certArray);
           sub.setPublicKey(cert[0].getPublicKey());
           CertificateImpl certImpl = new CertificateImpl(cert[0]);
           sub.addCertificate(certImpl);
           java.security.Certificate[] certs = sub.certificates();
           assertEquals("Certificate not contained in the identity",
                   certs[0], certImpl);
}
项目:netbeansplugins    文件:KeyTool.java   
private void doCertReq(String s, String s1, PrintStream printstream)
throws Exception {
    if(s == null)
        s = keyAlias;
    Object aobj[] = recoverPrivateKey(s, storePass, keyPass);
    PrivateKey privatekey = (PrivateKey)aobj[0];
    if(keyPass == null)
        keyPass = (char[])(char[])aobj[1];
    java.security.cert.Certificate certificate = keyStore.getCertificate(s);
    if(certificate == null) {
        MessageFormat messageformat = new MessageFormat(rb.getString("alias has no public key (certificate)"));
        Object aobj1[] = {
            s
        };
        throw new Exception(messageformat.format(((Object) (aobj1))));
    }
    PKCS10 pkcs10 = new PKCS10(certificate.getPublicKey());
    if(s1 == null) {
        String s2 = privatekey.getAlgorithm();
        if(s2.equalsIgnoreCase("DSA") || s2.equalsIgnoreCase("DSS"))
            s1 = "SHA1WithDSA";
        else
            if(s2.equalsIgnoreCase("RSA"))
                s1 = "MD5WithRSA";
            else
                throw new Exception(rb.getString("Cannot derive signature algorithm"));
    }
    Signature signature = Signature.getInstance(s1);
    signature.initSign(privatekey);
    X500Name x500name = new X500Name(((X509Certificate)certificate).getSubjectDN().toString());
    X500Signer x500signer = new X500Signer(signature, x500name);
    pkcs10.encodeAndSign(x500signer);
    pkcs10.print(printstream);
}
项目:netbeansplugins    文件:KeyTool.java   
private void doPrintCert(InputStream inputstream, PrintStream printstream)
throws Exception {
    Collection collection = null;
    try {
        collection = cf.generateCertificates(inputstream);
    } catch(CertificateException certificateexception) {
        throw new Exception(rb.getString("Failed to parse input"), certificateexception);
    }
    if(collection.isEmpty())
        throw new Exception(rb.getString("Empty input"));
    java.security.cert.Certificate acertificate[] = (java.security.cert.Certificate[])(java.security.cert.Certificate[])collection.toArray(new java.security.cert.Certificate[collection.size()]);
    for(int i = 0; i < acertificate.length; i++) {
        X509Certificate x509certificate = null;
        try {
            x509certificate = (X509Certificate)acertificate[i];
        } catch(ClassCastException classcastexception) {
            throw new Exception(rb.getString("Not X.509 certificate"));
        }
        if(acertificate.length > 1) {
            MessageFormat messageformat = new MessageFormat(rb.getString("Certificate[(i + 1)]:"));
            Object aobj[] = {
                new Integer(i + 1)
            };
            printstream.println(messageformat.format(((Object) (aobj))));
        }
        printX509Cert(x509certificate, printstream);
        if(i < acertificate.length - 1)
            printstream.println();
    }

}
项目:netbeansplugins    文件:KeyTool.java   
private boolean installReply(String s, InputStream inputstream)
throws Exception {
    if(s == null)
        s = keyAlias;
    Object aobj[] = recoverPrivateKey(s, storePass, keyPass);
    PrivateKey privatekey = (PrivateKey)aobj[0];
    if(keyPass == null)
        keyPass = (char[])(char[])aobj[1];
    java.security.cert.Certificate certificate = keyStore.getCertificate(s);
    if(certificate == null) {
        MessageFormat messageformat = new MessageFormat(rb.getString("alias has no public key (certificate)"));
        Object aobj1[] = {
            s
        };
        throw new Exception(messageformat.format(((Object) (aobj1))));
    }
    Collection collection = cf.generateCertificates(inputstream);
    if(collection.isEmpty())
        throw new Exception(rb.getString("Reply has no certificates"));
    java.security.cert.Certificate acertificate[] = (java.security.cert.Certificate[])(java.security.cert.Certificate[])collection.toArray(new java.security.cert.Certificate[collection.size()]);
    java.security.cert.Certificate acertificate1[];
    if(acertificate.length == 1)
        acertificate1 = establishCertChain(certificate, acertificate[0]);
    else
        acertificate1 = validateReply(s, certificate, acertificate);
    if(acertificate1 != null) {
        keyStore.setKeyEntry(s, privatekey, keyPass == null ? storePass : keyPass, acertificate1);
        return true;
    } else {
        return false;
    }
}
项目:netbeansplugins    文件:KeyTool.java   
private void dumpCert(java.security.cert.Certificate certificate, PrintStream printstream)
throws IOException, CertificateException {
    if(rfc) {
        BASE64Encoder base64encoder = new BASE64Encoder();
        printstream.println("-----BEGIN CERTIFICATE-----");
        base64encoder.encodeBuffer(certificate.getEncoded(), printstream);
        printstream.println("-----END CERTIFICATE-----");
    } else {
        printstream.write(certificate.getEncoded());
    }
}
项目:netbeansplugins    文件:KeyTool.java   
private String getCertFingerPrint(String s, java.security.cert.Certificate certificate)
throws Exception {
    byte abyte0[] = certificate.getEncoded();
    MessageDigest messagedigest = MessageDigest.getInstance(s);
    byte abyte1[] = messagedigest.digest(abyte0);
    return toHexString(abyte1);
}
项目:netbeansplugins    文件:KeyTool.java   
private java.security.cert.Certificate[] establishCertChain(java.security.cert.Certificate certificate, java.security.cert.Certificate certificate1)
throws Exception {
    if(certificate != null) {
        java.security.PublicKey publickey = certificate.getPublicKey();
        java.security.PublicKey publickey1 = certificate1.getPublicKey();
        if(!publickey.equals(publickey1))
            throw new Exception(rb.getString("Public keys in reply and keystore don't match"));
        if(certificate1.equals(certificate))
            throw new Exception(rb.getString("Certificate reply and certificate in keystore are identical"));
    }
    Hashtable hashtable = null;
    if(keyStore.size() > 0) {
        hashtable = new Hashtable(11);
        keystorecerts2Hashtable(keyStore, hashtable);
    }
    if(trustcacerts && caks != null && caks.size() > 0) {
        if(hashtable == null)
            hashtable = new Hashtable(11);
        keystorecerts2Hashtable(caks, hashtable);
    }
    Vector vector = new Vector(2);
    if(buildChain((X509Certificate)certificate1, vector, hashtable)) {
        java.security.cert.Certificate acertificate[] = new java.security.cert.Certificate[vector.size()];
        int i = 0;
        for(int j = vector.size() - 1; j >= 0; j--) {
            acertificate[i] = (java.security.cert.Certificate)vector.elementAt(j);
            i++;
        }

        return acertificate;
    } else {
        throw new Exception(rb.getString("Failed to establish chain from reply"));
    }
}
项目:netbeansplugins    文件:KeyTool.java   
private void doImportIdentityDatabase(InputStream inputstream)
throws Exception {
    java.security.cert.Certificate acertificate[] = null;
    boolean flag = false;
    IdentityDatabase identitydatabase = IdentityDatabase.fromStream(inputstream);
    Enumeration enumeration = identitydatabase.identities();
    do
    {
        if(!enumeration.hasMoreElements())
            break;
        Identity identity = (Identity)enumeration.nextElement();
        X509Certificate x509certificate = null;
        if((!(identity instanceof SystemSigner) || !((SystemSigner)identity).isTrusted()) && (!(identity instanceof SystemIdentity) || !((SystemIdentity)identity).isTrusted()))
            continue;
        if(keyStore.containsAlias(identity.getName())) {
            MessageFormat messageformat = new MessageFormat(rb.getString("Keystore entry for <id.getName()> already exists"));
            Object aobj[] = {
                identity.getName()
            };
            System.err.println(messageformat.format(((Object) (aobj))));
            continue;
        }
        Certificate acertificate1[] = identity.certificates();
        if(acertificate1 == null || acertificate1.length <= 0)
            continue;
        DerOutputStream deroutputstream = new DerOutputStream();
        acertificate1[0].encode(deroutputstream);
        byte abyte0[] = deroutputstream.toByteArray();
        ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(abyte0);
        x509certificate = (X509Certificate)cf.generateCertificate(bytearrayinputstream);
        bytearrayinputstream.close();
        if(isSelfSigned(x509certificate)) {
            java.security.PublicKey publickey = x509certificate.getPublicKey();
            try {
                x509certificate.verify(publickey);
            } catch(Exception exception) {
                continue;
            }
        }
        if(identity instanceof SystemSigner) {
            MessageFormat messageformat1 = new MessageFormat(rb.getString("Creating keystore entry for <id.getName()> ..."));
            Object aobj1[] = {
                identity.getName()
            };
            System.err.println(messageformat1.format(((Object) (aobj1))));
            if(acertificate == null)
                acertificate = new java.security.cert.Certificate[1];
            acertificate[0] = x509certificate;
            PrivateKey privatekey = ((SystemSigner)identity).getPrivateKey();
            keyStore.setKeyEntry(identity.getName(), privatekey, storePass, acertificate);
        } else {
            keyStore.setCertificateEntry(identity.getName(), x509certificate);
        }
        kssave = true;
    } while(true);
    if(!kssave)
        System.err.println(rb.getString("No entries from identity database added"));
}
项目:netbeansplugins    文件:KeyTool.java   
private void doPrintEntry(String s, PrintStream printstream, boolean flag) throws Exception {
    if(storePass == null && flag)
        printWarning();

    if(!keyStore.containsAlias(s)) {
        MessageFormat messageformat = new MessageFormat(rb.getString("Alias <alias> does not exist"));
        Object aobj[] = {
            s
        };
        throw new Exception(messageformat.format(((Object) (aobj))));
    }
    if(verbose || rfc || debug) {
        MessageFormat messageformat1 = new MessageFormat(rb.getString("Alias name: alias"));
        Object aobj1[] = {
            s
        };
        printstream.println(messageformat1.format(((Object) (aobj1))));
        if(!token) {
            MessageFormat messageformat2 = new MessageFormat(rb.getString("Creation date: keyStore.getCreationDate(alias)"));
            Object aobj4[] = {
                keyStore.getCreationDate(s)
            };
            printstream.println(messageformat2.format(((Object) (aobj4))));
        }
    } else if(!token) {
        MessageFormat messageformat3 = new MessageFormat(rb.getString("alias, keyStore.getCreationDate(alias), "));
        Object aobj2[] = {
            s, keyStore.getCreationDate(s)
        };
        printstream.print(messageformat3.format(((Object) (aobj2))));
    } else {
        MessageFormat messageformat4 = new MessageFormat(rb.getString("alias, "));
        Object aobj3[] = {
            s
        };
        printstream.print(messageformat4.format(((Object) (aobj3))));
    }

    if(keyStore.isKeyEntry(s)) {
        if(verbose || rfc || debug)
            printstream.println(rb.getString("Entry type: keyEntry"));
        else
            printstream.println(rb.getString("keyEntry,"));
        java.security.cert.Certificate acertificate[] = keyStore.getCertificateChain(s);
        if(acertificate != null)
            if(verbose || rfc || debug) {
            printstream.println((new StringBuilder()).append(rb.getString("Certificate chain length: ")).append(acertificate.length).toString());
            for(int i = 0; i < acertificate.length; i++) {
                MessageFormat messageformat5 = new MessageFormat(rb.getString("Certificate[(i + 1)]:"));
                Object aobj5[] = {
                    new Integer(i + 1)
                };
                printstream.println(messageformat5.format(((Object) (aobj5))));
                if(verbose && (acertificate[i] instanceof X509Certificate))
                    printX509Cert((X509Certificate)(X509Certificate)acertificate[i], printstream);
                else if(debug)
                    printstream.println(acertificate[i].toString());
                else
                    dumpCert(acertificate[i], printstream);
            }
            } else {
            printstream.println((new StringBuilder()).append(rb.getString("Certificate fingerprint (MD5): ")).append(getCertFingerPrint("MD5", acertificate[0])).toString());
            }
    } else {
        java.security.cert.Certificate certificate = keyStore.getCertificate(s);
        if(verbose && (certificate instanceof X509Certificate)) {
            printstream.println(rb.getString("Entry type: trustedCertEntry\n"));
            printX509Cert((X509Certificate)certificate, printstream);
        } else if(rfc) {
            printstream.println(rb.getString("Entry type: trustedCertEntry\n"));
            dumpCert(certificate, printstream);
        } else if(debug) {
            printstream.println(certificate.toString());
        } else {
            printstream.println(rb.getString("trustedCertEntry,"));
            printstream.println((new StringBuilder()).append(rb.getString("Certificate fingerprint (MD5): ")).append(getCertFingerPrint("MD5", certificate)).toString());
        }
    }
}
项目:netbeansplugins    文件:KeyTool.java   
private boolean addTrustedCert(String s, InputStream inputstream)
    throws Exception {
        X509Certificate x509certificate;
        if(s == null)
            throw new Exception(rb.getString("Must specify alias"));
        if(keyStore.containsAlias(s)) {
            MessageFormat messageformat = new MessageFormat(rb.getString("Certificate not imported, alias <alias> already exists"));
            Object aobj[] = {
                s
            };
            throw new Exception(messageformat.format(((Object) (aobj))));
        }
        x509certificate = null;
        try {
            x509certificate = (X509Certificate)cf.generateCertificate(inputstream);
        } catch(ClassCastException classcastexception) {
            throw new Exception(rb.getString("Input not an X.509 certificate"));
        } catch(CertificateException certificateexception) {
            throw new Exception(rb.getString("Input not an X.509 certificate"));
        }
        boolean flag = false;
        if(isSelfSigned(x509certificate)) {
            x509certificate.verify(x509certificate.getPublicKey());
            flag = true;
        }
        if(noprompt) {
            keyStore.setCertificateEntry(s, x509certificate);
            return true;
        }
        String s1 = null;
        String s3 = keyStore.getCertificateAlias(x509certificate);
        if(s3 != null) {
            MessageFormat messageformat1 = new MessageFormat(rb.getString("Certificate already exists in keystore under alias <trustalias>"));
            Object aobj1[] = {
                s3
            };
            System.err.println(messageformat1.format(((Object) (aobj1))));
            s1 = getYesNoReply(rb.getString("Do you still want to add it? [no]:  "));
        } else
            if(flag) {
            if(trustcacerts && caks != null && (s3 = caks.getCertificateAlias(x509certificate)) != null) {
                MessageFormat messageformat2 = new MessageFormat(rb.getString("Certificate already exists in system-wide CA keystore under alias <trustalias>"));
                Object aobj2[] = {
                    s3
                };
                System.err.println(messageformat2.format(((Object) (aobj2))));
                s1 = getYesNoReply(rb.getString("Do you still want to add it to your own keystore? [no]:  "));
            }
            if(s3 == null) {
                printX509Cert(x509certificate, System.out);
                s1 = getYesNoReply(rb.getString("Trust this certificate? [no]:  "));
            }
            }
        if(s1 != null)
            if(s1.equals("YES")) {
            keyStore.setCertificateEntry(s, x509certificate);
            return true;
            } else {
            return false;
            }
        java.security.cert.Certificate acertificate[] = establishCertChain(null, x509certificate);
// DECOMPILE?
//        if(acertificate == null)
//            break MISSING_BLOCK_LABEL_469;
        keyStore.setCertificateEntry(s, x509certificate);
        return true;
// DECOMPILE?
//        Exception exception;
//        exception;
//        printX509Cert(x509certificate, System.out);
//        String s2 = getYesNoReply(rb.getString("Trust this certificate? [no]:  "));
//        if(s2.equals("YES")) {
//            keyStore.setCertificateEntry(s, x509certificate);
//            return true;
//        } else{
//            return false;
//        }
//        return false;
    }
项目:netbeansplugins    文件:KeyTool.java   
private boolean isTrusted(java.security.cert.Certificate certificate)
throws Exception {
    if(keyStore.getCertificateAlias(certificate) != null)
        return true;
    return trustcacerts && caks != null && caks.getCertificateAlias(certificate) != null;
}
项目:OpenUnison    文件:UnisonConfigManagerImpl.java   
private void initSSL() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException {
    if (this.getKeyManagerFactory() == null) {
        return;
    }

    KeyStore cacerts = KeyStore.getInstance(KeyStore.getDefaultType());





    String cacertsPath = System.getProperty("javax.net.ssl.trustStore");
    if (cacertsPath == null) {
        cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
    }

    cacerts.load(new FileInputStream(cacertsPath), null);

    Enumeration<String> enumer = cacerts.aliases();
    while (enumer.hasMoreElements()) {
        String alias = enumer.nextElement();
        java.security.cert.Certificate cert = cacerts.getCertificate(alias);
        this.ks.setCertificateEntry(alias, cert);
    }

    SSLContext sslctx = SSLContexts.custom().loadTrustMaterial(this.ks).loadKeyMaterial(this.ks,this.cfg.getKeyStorePassword().toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx,SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
    httpClientRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", sf)
            .register("https", sslsf)
            .build();

    globalHttpClientConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(false).setAuthenticationEnabled(false).build();


}