| <?XML version="1.0" encoding="UTF-8" standalone="no"?> <invoice XMLns="http://www.company.com/accounting"> <items> <item> <desc>Applied Cryptography</desc> <type>book</type> <unitprice>44.50</unitprice> <quantity>1</quantity> </item> </items> <creditcard> <number>123456789</number> <expiry>10/20/2009</expiry> <lastname>John</lastname> <firstname>Smith</firstname> </creditcard> </invoice> |
| keytool -genkey -keysize 512 -sigalg DSA -dname "cn=Young Yang, ou=Architecture, o=Company, L=New York, ST=NY, c=US" -alias biz -keypass kp1234 -keystore bizkeystore -storepass sp1234 -validity 180 |
| public static KeyPair getKeyPair(String store,String sPass,String kPass,String alias) throws CertificateException, IOException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException{ KeyStore ks = loadKeyStore(store,sPass); KeyPair keyPair = null; Key key = null; PublicKey publicKey = null; PrivateKey privateKey = null; if (ks.containsAlias(alias)){ key = ks.getKey(alias,kPass.toCharArray()); if (key instanceof PrivateKey){ Certificate cert = ks.getCertificate(alias); publicKey = cert.getPublicKey(); privateKey = (PrivateKey)key; return new KeyPair(publicKey,privateKey); }else{ return null; } } else { return null; } } |
| public static PublicKey getPublicKey(String store, String sPass, String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{ KeyStore ks = loadKeyStore(store, sPass); Certificate cert = ks.getCertificate(alias); return cert.getPublicKey(); } |
| private static KeyStore loadKeyStore(String store, String sPass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{ KeyStore myKS = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(store); myKS.load(fis,sPass.toCharArray()); fis.close(); return myKS; } |
伴随JDK提供的keytool还可以把存储在一个密钥储存文件内的证书输出到系统文件中。例如,为了创建一个包含X509证书(关联于别名为biz的密钥入口)的biz.cer文件,我们可以从文件夹./etcdirectory下运行下列命令:
keytool -export -alias biz -file biz.cer -keystore bizkeystore -storepass sp1234
这个证书实现认证我们讨论上面的公共密钥。
我们还在示例中包括了一个Java类-CertificateInfo,用于把一个证书中的一些有趣的信息输出到System.out。为了试验这一点,读者可以运行Ant目标certInfo。然而,要理解该代码及其输出,必须具有DSA和RSA算法的基本知识。当然,读者可以安全地绕过这个程序而继续阅读本文后面的内容。