公钥加密,私钥解密示例程序(JAVA)

公钥加密,私钥解密示例程序(JAVA)

    最近再研究Java安全方面的东西,总结一下,大家有用到的可以参考下。

        1.证书生成        

        前提:JDK已安装且正确配置环境变量

        首先在C盘建立目录 MyKeyStore,用来存放证书库以及导出的证书文件,然后在命令行执行下列2句

        下句含义:在当前目录创建 TestStore 密钥库,库密码 000000 ,创建证书 TestKey2 :非对称密钥,RSA 算法,key密码为 000000 ,存于 TestStore

        C:/MyKeyStore > keytool -genkey -alias TestKey2 -dname "CN=test222" -keyalg RSA -keystore TestStore -storepass 000000 -keypass 000000

        下句含义:将 TestStore 库中的 TestKey2 导出为证书文件 TestKey2.cer ,这里可能需要将 export 修改为 exportcert

        C:/MyKeyStore > keytool -export -alias TestKey2 -file TestKey2.cer -keystore TestStore -storepass 000000

        证书库证书保存证书的公私钥,导出的证书文件只携带公钥

      

        2.代码实例              

[java] view plain copy

  1.     public static void main(String[] args) throws Exception {  
  2.   
  3.     byte[] msg = "test!中文".getBytes("UTF8"); // 待加解密的消息  
  4.   
  5.     // 用证书的公钥加密  
  6.     CertificateFactory cff = CertificateFactory.getInstance("X.509");  
  7.     FileInputStream fis1 = new FileInputStream("C://MyKeyStore//TestKey2.cer"); // 证书文件  
  8.     Certificate cf = cff.generateCertificate(fis1);  
  9.     PublicKey pk1 = cf.getPublicKey(); // 得到证书文件携带的公钥  
  10.     Cipher c1 = Cipher.getInstance("RSA/ECB/PKCS1Padding"); // 定义算法:RSA  
  11.     c1.init(Cipher.ENCRYPT_MODE, pk1);  
  12.     byte[] msg1 = c1.doFinal(msg); // 加密后的数据  
  13.   
  14.     // 用证书的私钥解密 - 该私钥存在生成该证书的密钥库中  
  15.     FileInputStream fis2 = new FileInputStream("C://MyKeyStore//TestStore");  
  16.     KeyStore ks = KeyStore.getInstance("JKS"); // 加载证书库  
  17.     char[] kspwd = "000000".toCharArray(); // 证书库密码  
  18.     char[] keypwd = "000000".toCharArray(); // 证书密码  
  19.     ks.load(fis2, kspwd); // 加载证书  
  20.     PrivateKey pk2 = (PrivateKey) ks.getKey("TestKey2", keypwd); // 获取证书私钥  
  21.     fis2.close();  
  22.     Cipher c2 = Cipher.getInstance("RSA/ECB/PKCS1Padding");  
  23.     c2.init(Cipher.DECRYPT_MODE, pk2);  
  24.     byte[] msg2 = c2.doFinal(msg1); // 解密后的数据  
  25.   
  26.     System.out.println(new String(msg2, "UTF8")); // 将解密数据转为字符串  

猜你喜欢

转载自blog.csdn.net/rainyear/article/details/84756213