常熟董浜招聘:征服*.PFX(*.p12)——个人信息交换文件

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 06:12:27
2010-08-12

征服*.PFX(*.p12)——个人信息交换文件

文章分类:Java编程 与计费系统打交道,少不了用到加密/解密实现。为了安全起见,通过非对称加密交换对称加密密钥更是不可或缺。那么需要通过什么载体传递非对称算法公钥/私钥信息?数字证书是公钥的载体,而密钥库可以包含公钥、私钥信息。
JKSPKCS#12都是比较常用的两种密钥库格式/标准。对于前者,搞Java开发,尤其是接触过HTTPS平台的朋友,并不陌生。JKS文件(通常为*.jks或*.keystore,扩展名无关)可以通过Java原生工具——KeyTool生成;而后者PKCS#12文件(通常为*.p12或*.pfx,意味个人信息交换文件),则是通过更为常用的OpenSSL工具产生。
当然,这两者之间是可以通过导入/导出的方式进行转换的!当然,这种转换需要通过KeyTool工具进行!
回归正题,计费同事遇到一个难题:合作方交给他们一个*.pfx文件,需要他们从中提取密钥,然后进行加密交互。其实,通过Java直接操作密钥库文件(或个人信息交换文件)对于一般Java开发人员来说,这都是个冷门。不接触数字安全,根本不知所云。况且,Java原生的密钥库文件格式为JKS,如何操作*.pfx文件?密钥库操作需要获知密钥库别名,*.pfx别名是什么?!这些难题都留给了我,当然,我欣然接受并回报硕果!

方案:
  1. 通过keytool密钥库导入命令importkeystore,将密钥库格式由PKCS#12转换为JKS。
  2. 检索新生成的密钥库文件,提取别名信息。
  3. 由密钥库文件导出数字证书(这里将用到别名)。
  4. 通过代码提取公钥/私钥、签名算法等

先看可是转换:
Cmd代码
  1. echo 格式转换   
  2. keytool -importkeystore -v  -srckeystore zlex.pfx -srcstoretype pkcs12 -srcstorepass 123456 -destkeystore zlex.keystore -deststoretype jks -deststorepass 123456  

-importkeystore导入密钥库,通过格式设定,我们可以将PKCS#12文件转换为JKS格式。
-v显示详情
-srckeystore源密钥库,这里是zlex.pfx
-srcstoretype源密钥库格式,这里为pkcs12
-srcstorepass源密钥库密码,这里为123456
-destkeystore目标密钥库,这里为zlex.keystore
-deststoretype目标密钥库格式,这里为jks,默认值也如此
-deststorepass目标密钥库密码,这里为123456
通过这个操作,我们能够获得所需的密钥库文件zlex.keystore。

这时,我们已经获得了密钥库文件,只要确定对应的别名信息,就可以提取公钥/私钥,以及数字证书,进行加密交互了!
Cmd代码
  1. echo 查看证书   
  2. keytool -list -keystore zlex.keystore -storepass 123456 -v  

-list列举密钥库
-keystore密钥库,这里是zlex.keystore
-storepass密钥库密码,这里是123456
-v显示详情

这里需要细致观察一下别名信息!!!就是红框中的数字1!!!
经过我多次尝试,将PKCS#12格式的密钥库转化为JKS格式时,其别名一律为“1”!也就是说,我们完全可以不进行密钥库转换,也能获得公钥/私钥。
现在,我们把证书导出!
Cmd代码
  1. echo 导出证书   
  2. keytool -exportcert -alias 1 -keystore zlex.keystore -file zlex.crt -storepass 123456  

-exportcert导出证书
-alias别名,这里是1
-keystore密钥库,这里是zlex.keystore
-file证书文件,这里是zlex.crt
-storepass密钥库密码,这里是123456

现在证书也导出了,我们可以提取公钥/私钥,进行加密/解密,签名/验证操作了!当然,即便没有证书,我们也能够通过密钥库(JKS格式)文件获得证书,以及公钥/私钥、签名算法等。
补充代码, 其实就是对Java加密技术(八)的修改!
Java代码
  1. /**  
  2.  * 2010-8-11  
  3.  */  
  4. package org.zlex.pfx;   
  5.   
  6. import java.io.FileInputStream;   
  7. import java.security.KeyStore;   
  8. import java.security.PrivateKey;   
  9. import java.security.PublicKey;   
  10. import java.security.Signature;   
  11. import java.security.cert.Certificate;   
  12. import java.security.cert.CertificateFactory;   
  13. import java.security.cert.X509Certificate;   
  14. import java.util.Date;   
  15.   
  16. import javax.crypto.Cipher;   
  17.   
  18. /**  
  19.  * 证书操作类  
  20.  *   
  21.  * @author 梁栋  
  22.  * @since 1.0  
  23.  */  
  24. public class CertificateCoder {   
  25.     /**  
  26.      * Java密钥库(Java Key Store,JKS)KEY_STORE  
  27.      */  
  28.     public static final String KEY_STORE = "JKS";   
  29.   
  30.     public static final String X509 = "X.509";   
  31.   
  32.     /**  
  33.      * 由 KeyStore获得私钥  
  34.      *   
  35.      * @param keyStorePath  
  36.      * @param alias  
  37.      * @param password  
  38.      * @return  
  39.      * @throws Exception  
  40.      */  
  41.     private static PrivateKey getPrivateKey(String keyStorePath, String alias,   
  42.             String password) throws Exception {   
  43.         KeyStore ks = getKeyStore(keyStorePath, password);   
  44.         PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray());   
  45.         return key;   
  46.     }   
  47.   
  48.     /**  
  49.      * 由 Certificate获得公钥  
  50.      *   
  51.      * @param certificatePath  
  52.      * @return  
  53.      * @throws Exception  
  54.      */  
  55.     private static PublicKey getPublicKey(String certificatePath)   
  56.             throws Exception {   
  57.         Certificate certificate = getCertificate(certificatePath);   
  58.         PublicKey key = certificate.getPublicKey();   
  59.         return key;   
  60.     }   
  61.   
  62.     /**  
  63.      * 获得Certificate  
  64.      *   
  65.      * @param certificatePath  
  66.      * @return  
  67.      * @throws Exception  
  68.      */  
  69.     private static Certificate getCertificate(String certificatePath)   
  70.             throws Exception {   
  71.         CertificateFactory certificateFactory = CertificateFactory   
  72.                 .getInstance(X509);   
  73.         FileInputStream in = new FileInputStream(certificatePath);   
  74.   
  75.         Certificate certificate = certificateFactory.generateCertificate(in);   
  76.         in.close();   
  77.   
  78.         return certificate;   
  79.     }   
  80.   
  81.     /**  
  82.      * 获得Certificate  
  83.      *   
  84.      * @param keyStorePath  
  85.      * @param alias  
  86.      * @param password  
  87.      * @return  
  88.      * @throws Exception  
  89.      */  
  90.     private static Certificate getCertificate(String keyStorePath,   
  91.             String alias, String password) throws Exception {   
  92.         KeyStore ks = getKeyStore(keyStorePath, password);   
  93.         Certificate certificate = ks.getCertificate(alias);   
  94.   
  95.         return certificate;   
  96.     }   
  97.   
  98.     /**  
  99.      * 获得KeyStore  
  100.      *   
  101.      * @param keyStorePath  
  102.      * @param password  
  103.      * @return  
  104.      * @throws Exception  
  105.      */  
  106.     private static KeyStore getKeyStore(String keyStorePath, String password)   
  107.             throws Exception {   
  108.         FileInputStream is = new FileInputStream(keyStorePath);   
  109.         KeyStore ks = KeyStore.getInstance(KEY_STORE);   
  110.         ks.load(is, password.toCharArray());   
  111.         is.close();   
  112.         return ks;   
  113.     }   
  114.   
  115.     /**  
  116.      * 私钥加密  
  117.      *   
  118.      * @param data  
  119.      * @param keyStorePath  
  120.      * @param alias  
  121.      * @param password  
  122.      * @return  
  123.      * @throws Exception  
  124.      */  
  125.     public static byte[] encryptByPrivateKey(byte[] data, String keyStorePath,   
  126.             String alias, String password) throws Exception {   
  127.         // 取得私钥   
  128.         PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);   
  129.   
  130.         // 对数据加密   
  131.         Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());   
  132.         cipher.init(Cipher.ENCRYPT_MODE, privateKey);   
  133.   
  134.         return cipher.doFinal(data);   
  135.   
  136.     }   
  137.   
  138.     /**  
  139.      * 私钥解密  
  140.      *   
  141.      * @param data  
  142.      * @param keyStorePath  
  143.      * @param alias  
  144.      * @param password  
  145.      * @return  
  146.      * @throws Exception  
  147.      */  
  148.     public static byte[] decryptByPrivateKey(byte[] data, String keyStorePath,   
  149.             String alias, String password) throws Exception {   
  150.         // 取得私钥   
  151.         PrivateKey privateKey = getPrivateKey(keyStorePath, alias, password);   
  152.   
  153.         // 对数据加密   
  154.         Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());   
  155.         cipher.init(Cipher.DECRYPT_MODE, privateKey);   
  156.   
  157.         return cipher.doFinal(data);   
  158.   
  159.     }   
  160.   
  161.     /**  
  162.      * 公钥加密  
  163.      *   
  164.      * @param data  
  165.      * @param certificatePath  
  166.      * @return  
  167.      * @throws Exception  
  168.      */  
  169.     public static byte[] encryptByPublicKey(byte[] data, String certificatePath)   
  170.             throws Exception {   
  171.   
  172.         // 取得公钥   
  173.         PublicKey publicKey = getPublicKey(certificatePath);   
  174.         // 对数据加密   
  175.         Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());   
  176.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);   
  177.   
  178.         return cipher.doFinal(data);   
  179.   
  180.     }   
  181.   
  182.     /**  
  183.      * 公钥解密  
  184.      *   
  185.      * @param data  
  186.      * @param certificatePath  
  187.      * @return  
  188.      * @throws Exception  
  189.      */  
  190.     public static byte[] decryptByPublicKey(byte[] data, String certificatePath)   
  191.             throws Exception {   
  192.         // 取得公钥   
  193.         PublicKey publicKey = getPublicKey(certificatePath);   
  194.   
  195.         // 对数据加密   
  196.         Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());   
  197.         cipher.init(Cipher.DECRYPT_MODE, publicKey);   
  198.   
  199.         return cipher.doFinal(data);   
  200.   
  201.     }   
  202.   
  203.     /**  
  204.      * 验证Certificate  
  205.      *   
  206.      * @param certificatePath  
  207.      * @return  
  208.      */  
  209.     public static boolean verifyCertificate(String certificatePath) {   
  210.         return verifyCertificate(new Date(), certificatePath);   
  211.     }   
  212.   
  213.     /**  
  214.      * 验证Certificate是否过期或无效  
  215.      *   
  216.      * @param date  
  217.      * @param certificatePath  
  218.      * @return  
  219.      */  
  220.     public static boolean verifyCertificate(Date date, String certificatePath) {   
  221.         boolean status = true;   
  222.         try {   
  223.             // 取得证书   
  224.             Certificate certificate = getCertificate(certificatePath);   
  225.             // 验证证书是否过期或无效   
  226.             status = verifyCertificate(date, certificate);   
  227.         } catch (Exception e) {   
  228.             status = false;   
  229.         }   
  230.         return status;   
  231.     }   
  232.   
  233.     /**  
  234.      * 验证证书是否过期或无效  
  235.      *   
  236.      * @param date  
  237.      * @param certificate  
  238.      * @return  
  239.      */  
  240.     private static boolean verifyCertificate(Date date, Certificate certificate) {   
  241.         boolean status = true;   
  242.         try {   
  243.             X509Certificate x509Certificate = (X509Certificate) certificate;   
  244.             x509Certificate.checkValidity(date);   
  245.         } catch (Exception e) {   
  246.             status = false;   
  247.         }   
  248.         return status;   
  249.     }   
  250.   
  251.     /**  
  252.      * 签名  
  253.      *   
  254.      * @param keyStorePath  
  255.      * @param alias  
  256.      * @param password  
  257.      *   
  258.      * @return  
  259.      * @throws Exception  
  260.      */  
  261.     public static byte[] sign(byte[] sign, String keyStorePath, String alias,   
  262.             String password) throws Exception {   
  263.         // 获得证书   
  264.         X509Certificate x509Certificate = (X509Certificate) getCertificate(   
  265.                 keyStorePath, alias, password);   
  266.         // 获取私钥   
  267.         KeyStore ks = getKeyStore(keyStorePath, password);   
  268.         // 取得私钥   
  269.         PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password   
  270.                 .toCharArray());   
  271.   
  272.         // 构建签名   
  273.         Signature signature = Signature.getInstance(x509Certificate   
  274.                 .getSigAlgName());   
  275.         signature.initSign(privateKey);   
  276.         signature.update(sign);   
  277.         return signature.sign();   
  278.     }   
  279.   
  280.     /**  
  281.      * 验证签名  
  282.      *   
  283.      * @param data  
  284.      * @param sign  
  285.      * @param certificatePath  
  286.      * @return  
  287.      * @throws Exception  
  288.      */  
  289.     public static boolean verify(byte[] data, byte[] sign,   
  290.             String certificatePath) throws Exception {   
  291.         // 获得证书   
  292.         X509Certificate x509Certificate = (X509Certificate) getCertificate(certificatePath);   
  293.         // 获得公钥   
  294.         PublicKey publicKey = x509Certificate.getPublicKey();   
  295.         // 构建签名   
  296.         Signature signature = Signature.getInstance(x509Certificate   
  297.                 .getSigAlgName());   
  298.         signature.initVerify(publicKey);   
  299.         signature.update(data);   
  300.   
  301.         return signature.verify(sign);   
  302.   
  303.     }   
  304.   
  305.     /**  
  306.      * 验证Certificate  
  307.      *   
  308.      * @param keyStorePath  
  309.      * @param alias  
  310.      * @param password  
  311.      * @return  
  312.      */  
  313.     public static boolean verifyCertificate(Date date, String keyStorePath,   
  314.             String alias, String password) {   
  315.         boolean status = true;   
  316.         try {   
  317.             Certificate certificate = getCertificate(keyStorePath, alias,   
  318.                     password);   
  319.             status = verifyCertificate(date, certificate);   
  320.         } catch (Exception e) {   
  321.             status = false;   
  322.         }   
  323.         return status;   
  324.     }   
  325.   
  326.     /**  
  327.      * 验证Certificate  
  328.      *   
  329.      * @param keyStorePath  
  330.      * @param alias  
  331.      * @param password  
  332.      * @return  
  333.      */  
  334.     public static boolean verifyCertificate(String keyStorePath, String alias,   
  335.             String password) {   
  336.         return verifyCertificate(new Date(), keyStorePath, alias, password);   
  337.     }   
  338. }  

相信上述代码已经帮朋友们解决了相当多的问题!
给出测试类:
Java代码
  1. package org.zlex.pfx;   
  2.   
  3. import static org.junit.Assert.*;   
  4.   
  5. import org.apache.commons.codec.binary.Hex;   
  6. import org.junit.Test;   
  7.   
  8. /**  
  9.  * 证书操作验证类  
  10.  *   
  11.  * @author 梁栋  
  12.  * @version 1.0  
  13.  * @since 1.0  
  14.  */  
  15. public class CertificateCoderTest {   
  16.     private String password = "123456";   
  17.     private String alias = "1";   
  18.     private String certificatePath = "zlex.crt";   
  19.     private String keyStorePath = "zlex.keystore";   
  20.   
  21.     @Test  
  22.     public void test() throws Exception {   
  23.         System.err.println("公钥加密——私钥解密");   
  24.         String inputStr = "Ceritifcate";   
  25.         byte[] data = inputStr.getBytes();   
  26.   
  27.         byte[] encrypt = CertificateCoder.encryptByPublicKey(data,   
  28.                 certificatePath);   
  29.   
  30.         byte[] decrypt = CertificateCoder.decryptByPrivateKey(encrypt,   
  31.                 keyStorePath, alias, password);   
  32.         String outputStr = new String(decrypt);   
  33.   
  34.         System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);   
  35.   
  36.         // 验证数据一致   
  37.         assertArrayEquals(data, decrypt);   
  38.   
  39.         // 验证证书有效   
  40.         assertTrue(CertificateCoder.verifyCertificate(certificatePath));   
  41.   
  42.     }   
  43.   
  44.     @Test  
  45.     public void testSign() throws Exception {   
  46.         System.err.println("私钥加密——公钥解密");   
  47.   
  48.         String inputStr = "sign";   
  49.         byte[] data = inputStr.getBytes();   
  50.   
  51.         byte[] encodedData = CertificateCoder.encryptByPrivateKey(data,   
  52.                 keyStorePath, alias, password);   
  53.   
  54.         byte[] decodedData = CertificateCoder.decryptByPublicKey(encodedData,   
  55.                 certificatePath);   
  56.   
  57.         String outputStr = new String(decodedData);   
  58.         System.err.println("加密前: " + inputStr + "\n\r" + "解密后: " + outputStr);   
  59.         assertEquals(inputStr, outputStr);   
  60.   
  61.         System.err.println("私钥签名——公钥验证签名");   
  62.         // 产生签名   
  63.         byte[] sign = CertificateCoder.sign(encodedData, keyStorePath, alias,   
  64.                 password);   
  65.         System.err.println("签名:\r" + Hex.encodeHexString(sign));   
  66.   
  67.         // 验证签名   
  68.         boolean status = CertificateCoder.verify(encodedData, sign,   
  69.                 certificatePath);   
  70.         System.err.println("状态:\r" + status);   
  71.         assertTrue(status);   
  72.   
  73.     }   
  74. }  

第一个测试方法,用于提取公钥/私钥进行加密/解密操作。
第二个测试方法,用于提取签名算法进行签名/验证操作。



OK,任务完成,密钥成功提取,剩下的都是代码基本功了!
  • 大小: 18.3 KB
  • 大小: 23 KB
  • 大小: 12.7 KB
  • 大小: 22.4 KB
  • 大小: 22.4 KB
3 楼 snowolf 2010-11-18   引用 maybe723 写道那对于单个cer格式的证书,这种证书没有私钥而只有公钥和CA的签名吧,这种证书在双向认证中,服务器端是不能认别出对方的身份并做签名的吧,而做签名要使用私钥,那这个私钥是保存在哪里?
cer证书文件本身就是算法以及公钥的载体,而私钥就需要私密保存,不对外公布了!2 楼 maybe723 2010-11-17   引用 那对于单个cer格式的证书,这种证书没有私钥而只有公钥和CA的签名吧,这种证书在双向认证中,服务器端是不能认别出对方的身份并做签名的吧,而做签名要使用私钥,那这个私钥是保存在哪里?1 楼 wukele 2010-08-12   引用 相信以后会用到。