java实现安全证书相关操作

https://blog.csdn.net/zhushanzhi/article/details/77864516

[java] view plain copy
 
 
  1. package test;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileNotFoundException;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.OutputStream;  
  11. import java.io.PrintStream;  
  12. import java.security.Key;  
  13. import java.security.KeyPair;  
  14. import java.security.KeyPairGenerator;  
  15. import java.security.KeyStore;  
  16. import java.security.Principal;  
  17. import java.security.PrivateKey;  
  18. import java.security.PublicKey;  
  19. import java.security.SecureRandom;  
  20. import java.security.Signature;  
  21. import java.security.cert.Certificate;  
  22. import java.security.cert.CertificateException;  
  23. import java.security.cert.CertificateFactory;  
  24. import java.security.cert.CertificateFactorySpi;  
  25. import java.security.cert.X509Certificate;  
  26. import java.util.ArrayList;  
  27. import java.util.Calendar;  
  28. import java.util.Collection;  
  29. import java.util.Date;  
  30. import java.util.Enumeration;  
  31. import java.util.HashMap;  
  32. import java.util.List;  
  33. import java.util.Map;  
  34. import java.util.regex.Matcher;  
  35. import java.util.regex.Pattern;  
  36.   
  37. import javax.crypto.KeyGenerator;  
  38. import javax.crypto.SecretKey;  
  39. import javax.crypto.spec.SecretKeySpec;  
  40.   
  41. import org.junit.Test;  
  42.   
  43. import sun.misc.BASE64Decoder;  
  44. import sun.misc.BASE64Encoder;  
  45. import sun.security.pkcs.ContentInfo;  
  46. import sun.security.pkcs.PKCS10;  
  47. import sun.security.pkcs.PKCS7;  
  48. import sun.security.tools.KeyStoreUtil;  
  49. import sun.security.x509.AlgorithmId;  
  50. import sun.security.x509.CertificateAlgorithmId;  
  51. import sun.security.x509.CertificateIssuerName;  
  52. import sun.security.x509.CertificateSerialNumber;  
  53. import sun.security.x509.CertificateSubjectName;  
  54. import sun.security.x509.CertificateValidity;  
  55. import sun.security.x509.CertificateVersion;  
  56. import sun.security.x509.CertificateX509Key;  
  57. import sun.security.x509.X500Name;  
  58. import sun.security.x509.X500Signer;  
  59. import sun.security.x509.X509CertImpl;  
  60. import sun.security.x509.X509CertInfo;  
  61.   
  62. public class ReadKeyStoreTest {  
  63.     /** 
  64.      * 列出store中所有的私钥和公钥 以及签名信息 
  65.      *  
  66.      * @param ks 
  67.      * @param storePass 
  68.      * @param priKeyPass 
  69.      * @throws Exception 
  70.      */  
  71.     private void listKeyAndCertificate(KeyStore ks, String storePass,  
  72.             String priKeyPass) throws Exception {  
  73.         System.out.println("size=" + ks.size());  
  74.         Enumeration<string> enum1 = ks.aliases();  
  75.         int i = 0;  
  76.         while (enum1.hasMoreElements()) {  
  77.             String alias = enum1.nextElement();  
  78.             System.out.println("第" + (++i) + "个");  
  79.             System.out.println("alias=" + alias);  
  80.             java.security.cert.Certificate c = ks.getCertificate(alias);// alias为条目的别名  
  81.             readX509Certificate((X509Certificate) c);  
  82.             readPriKey(ks, alias, priKeyPass);  
  83.         }  
  84.     }  
  85.   
  86.     /** 
  87.      * 列出store中私钥和cert chain信息 
  88.      *  
  89.      * @param ks 
  90.      * @param alias 
  91.      * @param pass 
  92.      * @throws Exception 
  93.      */  
  94.     private void readPriKey(KeyStore ks, String alias, String pass)  
  95.             throws Exception {  
  96.         Key key = ks.getKey(alias, pass.toCharArray());  
  97.         if (null == key) {  
  98.             System.out.println("no priviate key of " + alias);  
  99.             return;  
  100.         }  
  101.         System.out.println();  
  102.         System.out.println("algorithm=" + key.getAlgorithm());  
  103.         System.out.println("format=" + key.getFormat());  
  104.         System.out.println("toString=" + key);  
  105.         readCertChain(ks, alias);  
  106.     }  
  107.   
  108.     /** 
  109.      * 列出store中 cert chain信息 
  110.      *  
  111.      * @param ks 
  112.      * @param alias 
  113.      * @throws Exception 
  114.      */  
  115.     private void readCertChain(KeyStore ks, String alias) throws Exception {  
  116.         Certificate[] certChain = ks.getCertificateChain(alias);  
  117.         System.out.println("chain of " + alias);  
  118.         if (null == certChain) {  
  119.             System.out.println("no chain");  
  120.             return;  
  121.         }  
  122.         int i = 0;  
  123.         for (Certificate c : certChain) {  
  124.             System.out.println("index " + (i++) + " in chain of " + alias);  
  125.             readX509Certificate((X509Certificate) c);  
  126.         }  
  127.     }  
  128.   
  129.     /** 
  130.      * 列出x509Certificate的基本信息 
  131.      *  
  132.      * @param t 
  133.      */  
  134.     private void readX509Certificate(X509Certificate t) {  
  135.         System.out.println(t);  
  136.         System.out.println("输出证书信息:\n" + t.toString());  
  137.         System.out.println("版本号:" + t.getVersion());  
  138.         System.out.println("序列号:" + t.getSerialNumber().toString(16));  
  139.         System.out.println("主体名:" + t.getSubjectDN());  
  140.         System.out.println("签发者:" + t.getIssuerDN());  
  141.         System.out.println("有效期:" + t.getNotBefore());  
  142.         System.out.println("签名算法:" + t.getSigAlgName());  
  143.         byte[] sig = t.getSignature();// 签名值  
  144.         PublicKey pk = t.getPublicKey();  
  145.         byte[] pkenc = pk.getEncoded();  
  146.         System.out.println("签名 :");  
  147.         for (int i = 0; i < sig.length; i++)  
  148.             System.out.print(sig[i] + ",");  
  149.         System.out.println();  
  150.         System.out.println("公钥: ");  
  151.         for (int i = 0; i < pkenc.length; i++)  
  152.             System.out.print(pkenc[i] + ",");  
  153.         System.out.println();  
  154.     }  
  155.   
  156.     /** 
  157.      * 创建一个新的keystore 
  158.      *  
  159.      * @param storePass 
  160.      * @param storeType 
  161.      *            PKCS12/JKS 
  162.      * @return 
  163.      * @throws Exception 
  164.      */  
  165.     private KeyStore createKeyStore(String storePass, String storeType)  
  166.             throws Exception {  
  167.         KeyStore ks = KeyStore.getInstance(storeType);  
  168.         ks.load(null, storePass.toCharArray());  
  169.         return ks;  
  170.     }  
  171.   
  172.     /** 
  173.      * 加载一个已有的keyStore 
  174.      *  
  175.      * @param path 
  176.      * @param storePass 
  177.      * @param storeType 
  178.      *            PKCS12/JKS 
  179.      * @return 
  180.      * @throws Exception 
  181.      */  
  182.     private KeyStore loadKeyStore(String path, String storePass,  
  183.             String storeType) throws Exception {  
  184.         FileInputStream in = new FileInputStream(path);  
  185.         KeyStore ks = KeyStore.getInstance(storeType);  
  186.         ks.load(in, storePass.toCharArray());  
  187.         in.close();  
  188.         return ks;  
  189.     }  
  190.   
  191.     /** 
  192.      * 从文件加载一个证书 
  193.      *  
  194.      * @param path 
  195.      * @param certType 
  196.      * @return 
  197.      * @throws Exception 
  198.      */  
  199.     private Certificate loadCert(String path, String certType) throws Exception {  
  200.         CertificateFactory cf = CertificateFactory.getInstance(certType);  
  201.         FileInputStream in = new FileInputStream(path);  
  202.         Certificate c = cf.generateCertificate(in);  
  203.         in.close();  
  204.         return c;  
  205.     }  
  206.   
  207.     /** 
  208.      * 生成一个由根证书签名的store 
  209.      *  
  210.      * @param rootStore 
  211.      * @param rootAlias 
  212.      * @param rootKeyPass 
  213.      * @param subjectStr 
  214.      * @param storeType 
  215.      * @param storePass 
  216.      * @param alg 
  217.      * @param keySize 
  218.      * @param keyPass 
  219.      * @return 
  220.      * @throws Exception 
  221.      */  
  222.     public KeyStore generateSignedKeyStore(KeyStore rootStore,  
  223.             String rootAlias, String rootKeyPass, String subjectStr,  
  224.             String storeType, String storePass, String alias, String alg,  
  225.             int keySize, String keyPass) throws Exception {  
  226.   
  227.         PrivateKey rootKey = null;  
  228.         X509CertImpl rootCert = null;  
  229.         X509CertInfo rootInfo = null;  
  230.         CertificateSubjectName rootsubject = null;  
  231.         // 签发者  
  232.         X500Name issueX500Name = new X500Name(subjectStr);  
  233.   
  234.         if (null != rootStore) {  
  235.             rootKey = (PrivateKey) rootStore.getKey(rootAlias,  
  236.                     rootKeyPass.toCharArray());  
  237.             rootCert = (X509CertImpl) rootStore.getCertificate(rootAlias);  
  238.             rootInfo = (X509CertInfo) rootCert.get(X509CertImpl.NAME + "."  
  239.                     + X509CertImpl.INFO);  
  240.             rootsubject = (CertificateSubjectName) rootInfo  
  241.                     .get(X509CertInfo.SUBJECT);  
  242.             issueX500Name = (X500Name) rootsubject  
  243.                     .get(CertificateIssuerName.DN_NAME);  
  244.         }  
  245.   
  246.         // 签发者  
  247.         CertificateIssuerName issuerName = new CertificateIssuerName(  
  248.                 issueX500Name);  
  249.         // 被签发者  
  250.         X500Name subjectX500Name = new X500Name(subjectStr);  
  251.         CertificateSubjectName subjectName = new CertificateSubjectName(  
  252.                 subjectX500Name);  
  253.   
  254.         // 有效期设置  
  255.         Calendar calendar = Calendar.getInstance();  
  256.         Date startDate = calendar.getTime();  
  257.         calendar.add(Calendar.DATE, 85);  
  258.         Date endDate = calendar.getTime();  
  259.         CertificateValidity certificateValidity = new CertificateValidity(  
  260.                 startDate, endDate);  
  261.   
  262.         // 序列号  
  263.         CertificateSerialNumber sn = new CertificateSerialNumber(  
  264.                 (int) (startDate.getTime() / 1000L));  
  265.   
  266.         // 版本  
  267.         CertificateVersion certVersion = new CertificateVersion(  
  268.                 CertificateVersion.V3);  
  269.   
  270.         // 算法  
  271.         // TODO 获取算法的代码有问题  
  272.         AlgorithmId algorithmId = new AlgorithmId(  
  273.                 "RSA".equals(alg) ? AlgorithmId.sha1WithRSAEncryption_oid  
  274.                         : AlgorithmId.sha1WithDSA_oid);  
  275.   
  276.         // 密钥对  
  277.         KeyPairGenerator keygen = KeyPairGenerator.getInstance(alg);  
  278.         keygen.initialize(keySize, new SecureRandom());  
  279.         KeyPair kp = keygen.genKeyPair();  
  280.   
  281.         X509CertInfo certInfo = new X509CertInfo();  
  282.         certInfo.set("version", certVersion);  
  283.         certInfo.set("serialNumber", sn);  
  284.   
  285.         // localX500Signer.getAlgorithmId();  
  286.         certInfo.set("algorithmID", new CertificateAlgorithmId(algorithmId));  
  287.         certInfo.set("key", new CertificateX509Key(kp.getPublic()));  
  288.         certInfo.set("validity", certificateValidity);  
  289.         certInfo.set("subject", subjectName);  
  290.         certInfo.set("issuer", issuerName);  
  291.         // 扩展信息  
  292.         // if (System.getProperty("sun.security.internal.keytool.skid") !=  
  293.         // null)  
  294.         // {  
  295.         // CertificateExtensions localCertificateExtensions = new  
  296.         // CertificateExtensions();  
  297.         // localCertificateExtensions.set("SubjectKeyIdentifier", new  
  298.         // SubjectKeyIdentifierExtension(new  
  299.         // KeyIdentifier(this.publicKey).getIdentifier()));  
  300.         // certInfo.set("extensions", localCertificateExtensions);  
  301.         // }  
  302.   
  303.         X509CertImpl newcert = new X509CertImpl(certInfo);  
  304.         // TODO 这里的签名算法可能有问题 貌似应该用rootcert的签名算法 待测试  
  305.         KeyStore ks = this.createKeyStore(storePass, storeType);  
  306.         Certificate[] certChain = null;  
  307.         // 如果rootStore为空 则生成自签名证书  
  308.         if (null == rootStore) {  
  309.             newcert.sign(kp.getPrivate(), "SHA1WithRSA");  
  310.             certChain = new Certificate[] { newcert };  
  311.         } else {  
  312.             newcert.sign(rootKey, "SHA1WithRSA");  
  313.             certChain = new Certificate[] { newcert, rootCert };  
  314.         }  
  315.   
  316.         // ks.setCertificateEntry("zrbin", newcert);  
  317.         ks.setKeyEntry(alias, kp.getPrivate(), keyPass.toCharArray(), certChain);  
  318.         return ks;  
  319.   
  320.     }  
  321.   
  322.     @Test  
  323.     public void testReadCer() throws Exception {  
  324.         String path = "d:\\test.cer";  
  325.         String certType = "X.509";  
  326.         CertificateFactory cf = CertificateFactory.getInstance(certType);  
  327.         FileInputStream in = new FileInputStream(path);  
  328.         Collection<certificate> cs = (Collection<certificate>) cf  
  329.                 .generateCertificates(in);  
  330.         in.close();  
  331.         System.out.println("size=" + cs.size());  
  332.         for (Certificate c : cs) {  
  333.             readX509Certificate((X509Certificate) c);  
  334.         }  
  335.     }  
  336.   
  337.     @Test  
  338.     public void testReadP12() throws Exception {  
  339.         String storePass = "123456";  
  340.         String keyPass = "123456";  
  341.         String path = "d:\\zrbin.p12";  
  342.         KeyStore ks = loadKeyStore(path, storePass, "PKCS12");  
  343.         listKeyAndCertificate(ks, storePass, keyPass);  
  344.     }  
  345.   
  346.     @Test  
  347.     public void testReadKeyStore() throws Exception {  
  348.         String storePass = "123456";  
  349.         String keyPass = "123456";  
  350.         String path = "d:\\test.keystore";  
  351.         KeyStore ks = loadKeyStore(path, storePass, "JCEKS");  
  352.         listKeyAndCertificate(ks, storePass, keyPass);  
  353.     }  
  354.   
  355.     @Test  
  356.     public void testExportCert() throws FileNotFoundException, Exception {  
  357.         String pass = "123456";  
  358.         FileInputStream in = new FileInputStream("d:\\zrbin.p12");  
  359.         boolean rfc = true;  
  360.         KeyStore ks = KeyStore.getInstance("PKCS12");  
  361.         ks.load(in, pass.toCharArray());  
  362.         Certificate cert = ks.getCertificate("zrbin");  
  363.         PrintStream out = new PrintStream("D:\\zrbin.cer");  
  364.         if (rfc) {  
  365.             BASE64Encoder encoder = new BASE64Encoder();  
  366.             out.println("-----BEGIN CERTIFICATE-----");  
  367.             encoder.encodeBuffer(cert.getEncoded(),  
  368.                     out);  
  369.             out.println("-----END CERTIFICATE-----");  
  370.         } else {  
  371.             out.write(cert.getEncoded());  
  372.         }  
  373.         out.write(cert.getEncoded());  
  374.     }  
  375.   
  376.     @Test  
  377.     public void testImportCert() throws Exception {  
  378.         CertificateFactory cf = CertificateFactory.getInstance("X.509");  
  379.         FileInputStream storeIn = new FileInputStream("d:\\server.keystore");  
  380.         FileInputStream in = new FileInputStream("d:\\zrbin.cer");  
  381.         FileInputStream rootin = new FileInputStream("d:\\root.cer");  
  382.   
  383.         X509CertImpl cert = (X509CertImpl) cf.generateCertificate(in);  
  384.         X509CertImpl rootcert = (X509CertImpl) cf.generateCertificate(rootin);  
  385.   
  386.         KeyStore ks = KeyStore.getInstance("JKS");  
  387.         ks.load(null, "123456".toCharArray());  
  388.         ks.deleteEntry("zrbin");  
  389.         // ks.setCertificateEntry("zrbin", cert);  
  390.         ks.setCertificateEntry("root", rootcert);  
  391.         in.close();  
  392.         FileOutputStream out = new FileOutputStream("d:\\server.keystore");  
  393.         ks.store(out, "123456".toCharArray());  
  394.     }  
  395.   
  396.     @Test  
  397.     public void testImportSigenedCert() throws Exception {  
  398.         String alias = "test";  
  399.         CertificateFactory cf = CertificateFactory.getInstance("X.509");  
  400.         FileInputStream storeIn = new FileInputStream("d:\\test.keystore");  
  401.         KeyStore ks = KeyStore.getInstance("JKS");  
  402.         ks.load(storeIn, "123456".toCharArray());  
  403.         PrivateKey priKey = (PrivateKey) ks.getKey(alias,  
  404.                 "123456".toCharArray());  
  405.         FileInputStream in = new FileInputStream("d:\\test.cer");  
  406.         Collection<certificate> certCollection = (Collection<certificate>) cf  
  407.                 .generateCertificates(in);  
  408.         System.out.println(certCollection.size());  
  409.         if (certCollection.size() == 0) {  
  410.             System.out.println("没有要导入的证书");  
  411.             return;  
  412.         }  
  413.         // 如果没有对应的私钥,直接导入certficateEntry  
  414.         if (null == priKey) {  
  415.             for (Certificate _cert : certCollection) {  
  416.                 ks.setCertificateEntry(alias, _cert);  
  417.                 break;  
  418.             }  
  419.         } else {  
  420.             Certificate importCert = null;  
  421.             for (Certificate cert : certCollection) {  
  422.                 if (ks.getCertificate(alias).getPublicKey()  
  423.                         .equals(cert.getPublicKey())) {  
  424.                     importCert = cert;  
  425.                     break;  
  426.                 }  
  427.             }  
  428.             if (null == importCert) {  
  429.                 System.out.println("错误:no replay cert");  
  430.             }  
  431.             certCollection.remove(importCert);  
  432.             if (X509CertImpl.isSelfSigned((X509Certificate) importCert, null)) {  
  433.                 System.out.println("证书未被ca签名,无需导入");  
  434.             } else {  
  435.                 // 构建认证链  
  436.                 List<certificate> certList = new ArrayList<certificate>(  
  437.                         ks.size());  
  438.                 Map<principal certificate=""> cerMap = new HashMap<principal certificate="">();  
  439.                 Enumeration<string> aliasEnum = ks.aliases();  
  440.                 // 把不包括当前回复的都加到map里  
  441.                 while (aliasEnum.hasMoreElements()) {  
  442.                     String _alias = aliasEnum.nextElement();  
  443.                     if (!_alias.equals(alias)) {  
  444.                         X509CertImpl _cert = (X509CertImpl) ks  
  445.                                 .getCertificate(_alias);  
  446.                         cerMap.put(_cert.getSubjectDN(), _cert);  
  447.                     }  
  448.                 }  
  449.                 for (Certificate cert : certCollection) {  
  450.                     cerMap.put(((X509Certificate) cert).getSubjectDN(), cert);  
  451.                 }  
  452.                 certList.add(importCert);  
  453.                 Principal issuerName = ((X509Certificate) importCert)  
  454.                         .getIssuerDN();  
  455.                 while (cerMap.keySet().contains(issuerName)) {  
  456.                     X509Certificate _rootCert = (X509Certificate) cerMap  
  457.                             .remove(issuerName);  
  458.                     if (null == _rootCert) {  
  459.                         System.out.println(issuerName + "的根证书为空");  
  460.                         return;  
  461.                     }  
  462.                     certList.add(_rootCert);  
  463.                     issuerName = _rootCert.getIssuerDN();  
  464.                 }  
  465.   
  466.                 X509CertImpl rootCert = (X509CertImpl) certList.get(certList  
  467.                         .size() - 1);  
  468.                 if (!X509CertImpl.isSelfSigned(rootCert, null)) {  
  469.                     System.out.println("构建证书链错误,请先导入颁发者(" + issuerName  
  470.                             + ")的CA证书");  
  471.                     return;  
  472.                 }  
  473.                 Certificate[] certChain = certList  
  474.                         .toArray(new Certificate[certList.size()]);  
  475.                 ks.setKeyEntry(alias, priKey, "123456".toCharArray(), certChain);  
  476.   
  477.             }  
  478.         }  
  479.         in.close();  
  480.         FileOutputStream out = new FileOutputStream("d:\\test.keystore");  
  481.         ks.store(out, "123456".toCharArray());  
  482.         out.close();  
  483.   
  484.     }  
  485.   
  486.     @Test  
  487.     public void testGenerateKeyStore() throws Exception {  
  488.         KeyPairGenerator kg = KeyPairGenerator.getInstance("RSA");  
  489.         KeyPair kp = kg.genKeyPair();  
  490.         System.out.println(KeyStoreUtil.niceStoreTypeName("PKCS12"));  
  491.         System.out.println(kp.getPrivate());  
  492.         System.out.println(kp.getPublic());  
  493.         KeyStore ks = KeyStore.getInstance("JKS");  
  494.     }  
  495.   
  496.     @Test  
  497.     public void testX500Name() throws IOException, CertificateException {  
  498.         // for(byte i=48;i<=57;i++){  
  499.         // System.out.println((char)i);  
  500.         // }  
  501.         // RFC 1779 (CN, L, ST, O, OU, C, STREET)  
  502.         // RFC 2253 (CN/name, L/location, ST/station, O/org, OU/orgunit,  
  503.         // C/country, STREET, DC, UID)  
  504.         X500Name subjectName = new X500Name(  
  505.                 "CN=www.jiangtech.com,L=ZuChongZhi road,ST=Shang Hai,O=Jiangdatech,OU=ENTERPRISE APP,C=China,STREET=ZuChongZhi Road");  
  506.         X500Name subjectName1 = new X500Name(  
  507.                 "CN=www.jiangtech.com,L=ZuChongZhi road,ST=Shang Hai,O=Jiangdatech,OU=ENTERPRISE APP,C=China,STREET=ZuChongZhi Road");  
  508.         // X509CertInfo certInfo = new X509CertInfo();  
  509.         // certInfo.set(X509CertInfo.SUBJECT, new CertificateSubjectName(  
  510.         // subjectName));  
  511.         System.out.println(subjectName.hashCode());  
  512.         System.out.println(subjectName1.hashCode());  
  513.     }  
  514.   
  515.     /** 
  516.      * 证书验证 
  517.      *  
  518.      * @throws Exception 
  519.      */  
  520.     @Test  
  521.     public void testValidate() throws Exception {  
  522.         KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");  
  523.         // kpg.initialize()  
  524.         KeyPair kp = kpg.genKeyPair();  
  525.         KeyStore rootStore = this.loadKeyStore("d:/root.keystore", "123456",  
  526.                 "JKS");  
  527.         PrivateKey rootKey = (PrivateKey) rootStore.getKey("jdcert",  
  528.                 "123456".toCharArray());  
  529.         KeyStore store1 = this.loadKeyStore("d:/jd_signed.keystore", "123456",  
  530.                 "JKS");  
  531.         X509CertImpl rootCert = (X509CertImpl) rootStore  
  532.                 .getCertificate("jdcert");  
  533.         X509CertInfo rootInfo = (X509CertInfo) rootCert.get(X509CertImpl.NAME  
  534.                 + "." + X509CertImpl.INFO);  
  535.         CertificateSubjectName rootsubject = (CertificateSubjectName) rootInfo  
  536.                 .get(X509CertInfo.SUBJECT);  
  537.         Certificate[] chain = rootStore.getCertificateChain("jdcert");  
  538.         rootCert.verify(kp.getPublic());  
  539.   
  540.     }  
  541.   
  542.     /** 
  543.      * 测试签发证书 
  544.      */  
  545.     @Test  
  546.     public void testGenerateSignedKeyStore() {  
  547.         try {  
  548.             KeyStore rootStore = this.loadKeyStore("d:/root.keystore",  
  549.                     "123456", "JKS");  
  550.             String rootAlias = "test";  
  551.             String subjectStr = "CN=zhaorb@jiangdatech.com,L=PU Dong,ST=Shang Hai,O=Jiangdatech,OU=ENTERPRISE APP,C=China,STREET=ZuChongZhi Road";  
  552.             String alg = "RSA";  
  553.             String storeType = "JKS";  
  554.             int keySize = 1024;  
  555.             String keyPass = "123456";  
  556.             String rootKeyPass = "123456";  
  557.             String storePass = "123456";  
  558.             String alias = "test";  
  559.             KeyStore ks = this.generateSignedKeyStore(null, rootAlias,  
  560.                     rootKeyPass, subjectStr, storeType, storePass, alias, alg,  
  561.                     keySize, keyPass);  
  562.             OutputStream out = new FileOutputStream(  
  563.                     new File("d:/test.keystore"));  
  564.             ks.store(out, "123456".toCharArray());  
  565.         } catch (Exception e) {  
  566.             e.printStackTrace();  
  567.         }  
  568.   
  569.     }  
  570.       
  571.       
  572.     /** 
  573.      * 测试签发证书 
  574.      */  
  575.     @Test  
  576.     public void testGenerateSecKeyStore() {  
  577.         try {  
  578.             String rootAlias = "test";  
  579.             String subjectStr = "CN=zhaorb@jiangdatech.com,L=PU Dong,ST=Shang Hai,O=Jiangdatech,OU=ENTERPRISE APP,C=China,STREET=ZuChongZhi Road";  
  580.             String alg = "DES";  
  581.             String storeType = "JKS";  
  582.             int keySize = 1024;  
  583.             String keyPass = "123456";  
  584.             String rootKeyPass = "123456";  
  585.             String storePass = "123456";  
  586.             String alias = "test";  
  587.             KeyStore ks = this.createKeyStore("123456", "JCEKS");  
  588.             KeyGenerator keygen = KeyGenerator.getInstance("DES");  
  589.             SecretKey secKey = keygen.generateKey();  
  590.             ks.setKeyEntry(alias, secKey, "123456".toCharArray(),null);  
  591.             OutputStream out = new FileOutputStream(  
  592.                     new File("d:/test.keystore"));  
  593.             ks.store(out, "123456".toCharArray());  
  594.         } catch (Exception e) {  
  595.             e.printStackTrace();  
  596.         }  
  597.   
  598.     }  
  599.       
  600.     @Test  
  601.     /** 
  602.      * 关于p7b的操作 未实现 
  603.      */  
  604.     public void testGeneratePKCS7KeyStore() {  
  605.         try {  
  606.             /*ContentInfo info = new ContentInfo(arg0); 
  607.             //PKCS7 pkcs7 = new PKCS7() 
  608.             String rootAlias = "test"; 
  609.             String subjectStr = "CN=zhaorb@jiangdatech.com,L=PU Dong,ST=Shang Hai,O=Jiangdatech,OU=ENTERPRISE APP,C=China,STREET=ZuChongZhi Road"; 
  610.             String alg = "DES"; 
  611.             String storeType = "JKS"; 
  612.             int keySize = 1024; 
  613.             String keyPass = "123456"; 
  614.             String rootKeyPass = "123456"; 
  615.             String storePass = "123456"; 
  616.             String alias = "test"; 
  617.             KeyStore ks = this.createKeyStore("123456", "PKCS7"); 
  618.             KeyGenerator keygen = KeyGenerator.getInstance("RSA"); 
  619.             //SecretKey secKey = keygen.generateKey(); 
  620.             //ks.setKeyEntry(alias, secKey, "123456".toCharArray(),null); 
  621.             OutputStream out = new FileOutputStream( 
  622.                     new File("d:/test.keystore")); 
  623.             ks.store(out, "123456".toCharArray());*/  
  624.         } catch (Exception e) {  
  625.             e.printStackTrace();  
  626.         }  
  627.   
  628.     }  
  629.       
  630.       
  631.     @Test  
  632.     public void testReadJCEKS() throws Exception{  
  633.         KeyStore ks = this.loadKeyStore("D:/test.keystore","123456", "JCEKS");  
  634.         Enumeration<string> aliasEnum = ks.aliases();  
  635.         while(aliasEnum.hasMoreElements()){  
  636.             String alias = aliasEnum.nextElement();  
  637.             SecretKeySpec secKey = (SecretKeySpec) ks.getKey(alias, "123456".toCharArray());  
  638.             System.out.println(ks.getCertificate(alias));  
  639.             //System.out.println(ks.);  
  640.             System.out.println(secKey.getClass());  
  641.             System.out.println(secKey.getFormat());  
  642.             System.out.println(secKey.getEncoded());  
  643.         }  
  644.     }  
  645.   
  646.     public PKCS10 readCsr() throws Exception {  
  647.         File f = new File("D:/test.csr");  
  648.         InputStream in = new FileInputStream(f);  
  649.         ByteArrayOutputStream out = new ByteArrayOutputStream(1024);  
  650.         byte[] bytes = new byte[(int) f.length()];  
  651.         in.read(bytes);  
  652.         String base64String = new String(bytes, "ISO-8859-1");  
  653.         System.out.println(base64String);  
  654.         Pattern p = Pattern  
  655.                 .compile("-----BEGIN NEW CERTIFICATE REQUEST-----([\\s\\S]*?)-----END NEW CERTIFICATE REQUEST-----([\\s\\S]*)");  
  656.         BASE64Decoder decoder = new BASE64Decoder();  
  657.         Matcher m = p.matcher(base64String);  
  658.         if (m.find()) {  
  659.             String s = m.group(1);  
  660.             System.out.println(s.trim());  
  661.             byte[] bArray = decoder.decodeBuffer(s);  
  662.             PKCS10 csr = new PKCS10(bArray);  
  663.             System.out.println(csr);  
  664.             return csr;  
  665.         }  
  666.         throw new Exception("文件错误 ,无法读取csr");  
  667.     }  
  668.   
  669.     @Test  
  670.     public void testReadCsr() throws Exception {  
  671.         PKCS10 csr = readCsr();  
  672.     }  
  673.   
  674.     @Test  
  675.     public void createCsr() throws Exception {  
  676.         String storePass = "123456";  
  677.         String alias = "test";  
  678.         String alg = null;  
  679.   
  680.         KeyStore ks = this.loadKeyStore("d:/test.keystore", storePass, "JKS");  
  681.         Certificate cert = ks.getCertificate(alias);  
  682.         PrivateKey priKey = (PrivateKey) ks.getKey(alias,  
  683.                 "123456".toCharArray());  
  684.         PublicKey pubKey = cert.getPublicKey();  
  685.         PKCS10 csr = new PKCS10(pubKey);  
  686.         String signAlg = null;  
  687.         if (alg == null) {  
  688.             alg = priKey.getAlgorithm();  
  689.             if (("DSA".equalsIgnoreCase(alg)) || ("DSS".equalsIgnoreCase(alg)))  
  690.                 signAlg = "SHA1WithDSA";  
  691.             else if ("RSA".equalsIgnoreCase((String) alg))  
  692.                 signAlg = "SHA1WithRSA";  
  693.             else  
  694.                 throw new Exception("Cannot derive signature algorithm");  
  695.         }  
  696.         Signature signature = Signature.getInstance(signAlg);  
  697.         signature.initSign(priKey);  
  698.         X500Name x500Name = new X500Name(((X509Certificate) cert)  
  699.                 .getSubjectDN().toString());  
  700.         X500Signer x500Signer = new X500Signer(signature, x500Name);  
  701.         ((PKCS10) csr).encodeAndSign(x500Signer);  
  702.         File f = new File("D:/test.csr");  
  703.         if (f.exists()) {  
  704.             f.delete();  
  705.         }  
  706.         ((PKCS10) csr).print(new PrintStream(new File("D:/test.csr")));  
  707.     }  
  708.   
  709.     /** 
  710.      * 签名 
  711.      *  
  712.      * @throws Exception 
  713.      */  
  714.     @Test  
  715.     public void testSignature() throws Exception {  
  716.         KeyStore rootStore = this.loadKeyStore("d:/root.keystore", "123456",  
  717.                 "JKS");  
  718.         PrivateKey rootKey = (PrivateKey) rootStore.getKey("root",  
  719.                 "123456".toCharArray());  
  720.         X509CertImpl rootX509Cert = (X509CertImpl) rootStore  
  721.                 .getCertificate("root");  
  722.         X500Name issuerX500Name = (X500Name) rootX509Cert.get(X509CertImpl.NAME  
  723.                 + "." + X509CertImpl.INFO + "." + X509CertInfo.SUBJECT + "."  
  724.                 + CertificateSubjectName.DN_NAME);  
  725.   
  726.         // 有效期设置  
  727.         Calendar calendar = Calendar.getInstance();  
  728.         Date startDate = calendar.getTime();  
  729.         calendar.add(Calendar.DATE, 85);  
  730.         Date endDate = calendar.getTime();  
  731.         CertificateValidity certificateValidity = new CertificateValidity(  
  732.                 startDate, endDate);  
  733.   
  734.         // 序列号  
  735.         CertificateSerialNumber sn = new CertificateSerialNumber(  
  736.                 (int) (startDate.getTime() / 1000L));  
  737.   
  738.         PKCS10 csr = this.readCsr();  
  739.         PublicKey pubKey = csr.getSubjectPublicKeyInfo();  
  740.         X500Name subjectX500Name = csr.getSubjectName();  
  741.         // TODO 未实现  
  742.         Signature signature = Signature.getInstance("Sha1WithRSA");  
  743.         X500Signer signer = new X500Signer(signature, subjectX500Name);  
  744.         AlgorithmId algorithmId = signer.getAlgorithmId();  
  745.   
  746.         X509CertInfo info = new X509CertInfo();  
  747.         info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(  
  748.                 algorithmId));  
  749.         info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(  
  750.                 subjectX500Name));  
  751.         info.set(X509CertInfo.ISSUER, new CertificateIssuerName(issuerX500Name));  
  752.         info.set(X509CertInfo.KEY, new CertificateX509Key(pubKey));  
  753.         info.set(X509CertInfo.VERSION, new CertificateVersion(  
  754.                 CertificateVersion.V3));  
  755.         info.set(X509CertInfo.VALIDITY, certificateValidity);  
  756.         info.set(X509CertInfo.SERIAL_NUMBER, sn);  
  757.   
  758.         X509CertImpl newCert = new X509CertImpl(info);  
  759.         newCert.sign(rootKey, "SHA1WithRSA");  
  760.         OutputStream out = new FileOutputStream("d:/test.cer");  
  761.         out.write(newCert.getEncoded());  
  762.         out.write(rootX509Cert.getEncoded());  
  763.         out.close();  
  764.     }  
  765.   
  766. }  
posted @ 2018-07-11 06:17  功夫 熊猫  阅读(3199)  评论(0编辑  收藏  举报