JAVA RSA密钥对的生成与验证

      在上一篇《 Java&keytool生成RSA密钥》中,我们用keytool先生成密钥库和公钥证书,然后通过代码方式获得文件和BASE64串形式的公私密钥对,而其实根本无这么复杂,可直接通过JAVA代码获得公私密钥对。代码如下:
Java代码   收藏代码
  1. package com.bijian.test;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.ObjectOutputStream;  
  5. import java.security.Key;  
  6. import java.security.KeyPair;  
  7. import java.security.KeyPairGenerator;  
  8. import java.security.NoSuchAlgorithmException;  
  9. import java.security.SecureRandom;  
  10.   
  11. import sun.misc.BASE64Encoder;  
  12.   
  13. public class KeyPairGenUtil {  
  14.   
  15.     /** 指定加密算法为RSA */  
  16.     private static final String ALGORITHM = "RSA";  
  17.     /** 密钥长度,用来初始化 */  
  18.     private static final int KEYSIZE = 1024;  
  19.     /** 指定公钥存放文件 */  
  20.     private static String PUBLIC_KEY_FILE = "PublicKey";  
  21.     /** 指定私钥存放文件 */  
  22.     private static String PRIVATE_KEY_FILE = "PrivateKey";  
  23.   
  24.     public static void main(String[] args) throws Exception {  
  25.         generateKeyPair();  
  26.         genKeyPair();  
  27.     }  
  28.   
  29.     /** 
  30.     * 生成密钥对 
  31.     * @throws Exception 
  32.     */  
  33.     private static void generateKeyPair() throws Exception {  
  34.   
  35.         //     /** RSA算法要求有一个可信任的随机数源 */  
  36.         //     SecureRandom secureRandom = new SecureRandom();  
  37.         /** 为RSA算法创建一个KeyPairGenerator对象 */  
  38.         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);  
  39.   
  40.         /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */  
  41.         //     keyPairGenerator.initialize(KEYSIZE, secureRandom);  
  42.         keyPairGenerator.initialize(KEYSIZE);  
  43.   
  44.         /** 生成密匙对 */  
  45.         KeyPair keyPair = keyPairGenerator.generateKeyPair();  
  46.   
  47.         /** 得到公钥 */  
  48.         Key publicKey = keyPair.getPublic();  
  49.   
  50.         /** 得到私钥 */  
  51.         Key privateKey = keyPair.getPrivate();  
  52.   
  53.         ObjectOutputStream oos1 = null;  
  54.         ObjectOutputStream oos2 = null;  
  55.         try {  
  56.             /** 用对象流将生成的密钥写入文件 */  
  57.             oos1 = new ObjectOutputStream(new FileOutputStream(PUBLIC_KEY_FILE));  
  58.             oos2 = new ObjectOutputStream(new FileOutputStream(PRIVATE_KEY_FILE));  
  59.             oos1.writeObject(publicKey);  
  60.             oos2.writeObject(privateKey);  
  61.         } catch (Exception e) {  
  62.             throw e;  
  63.         } finally {  
  64.             /** 清空缓存,关闭文件输出流 */  
  65.             oos1.close();  
  66.             oos2.close();  
  67.         }  
  68.     }  
  69.   
  70.     private static void genKeyPair() throws NoSuchAlgorithmException {  
  71.           
  72.         /** RSA算法要求有一个可信任的随机数源 */  
  73.         SecureRandom secureRandom = new SecureRandom();  
  74.           
  75.         /** 为RSA算法创建一个KeyPairGenerator对象 */  
  76.         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);  
  77.   
  78.         /** 利用上面的随机数据源初始化这个KeyPairGenerator对象 */  
  79.         keyPairGenerator.initialize(KEYSIZE, secureRandom);  
  80.         //keyPairGenerator.initialize(KEYSIZE);  
  81.   
  82.         /** 生成密匙对 */  
  83.         KeyPair keyPair = keyPairGenerator.generateKeyPair();  
  84.   
  85.         /** 得到公钥 */  
  86.         Key publicKey = keyPair.getPublic();  
  87.   
  88.         /** 得到私钥 */  
  89.         Key privateKey = keyPair.getPrivate();  
  90.   
  91.         byte[] publicKeyBytes = publicKey.getEncoded();  
  92.         byte[] privateKeyBytes = privateKey.getEncoded();  
  93.   
  94.         String publicKeyBase64 = new BASE64Encoder().encode(publicKeyBytes);  
  95.         String privateKeyBase64 = new BASE64Encoder().encode(privateKeyBytes);  
  96.   
  97.         System.out.println("publicKeyBase64.length():" + publicKeyBase64.length());  
  98.         System.out.println("publicKeyBase64:" + publicKeyBase64);  
  99.   
  100.         System.out.println("privateKeyBase64.length():" + privateKeyBase64.length());  
  101.         System.out.println("privateKeyBase64:" + privateKeyBase64);  
  102.     }  
  103. }  

        运行结果:


        用上一篇验证公私钥对加签验签、加解密的代码验证,也都是OK的。附上加解密验证的代码如下。

Java代码   收藏代码
  1. package com.bijian.test;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.io.ObjectInputStream;  
  6. import java.security.Key;  
  7.   
  8. import javax.crypto.Cipher;  
  9.   
  10. import sun.misc.BASE64Decoder;  
  11. import sun.misc.BASE64Encoder;  
  12.   
  13. public class RSAUtil {  
  14.       
  15.     /** 指定加密算法为RSA */  
  16.     private static final String ALGORITHM = "RSA";  
  17.     /** 指定公钥存放文件 */  
  18.     private static String PUBLIC_KEY_FILE = "PublicKey";  
  19.     /** 指定私钥存放文件 */  
  20.     private static String PRIVATE_KEY_FILE = "PrivateKey";  
  21.   
  22.     public static void main(String[] args) throws Exception {  
  23.           
  24.         String source = "你好nihao";// 要加密的字符串  
  25.         System.out.println("准备用公钥加密的字符串为:" + source);  
  26.           
  27.         String cryptograph = encrypt(source);// 生成的密文  
  28.         System.out.print("用公钥加密后的结果为:" + cryptograph);  
  29.         System.out.println();  
  30.          
  31.         String target = decrypt(cryptograph);// 解密密文  
  32.         System.out.println("用私钥解密后的字符串为:" + target);  
  33.         System.out.println();     
  34.     }  
  35.       
  36.     /** 
  37.      * 加密方法 
  38.      * @param source 源数据 
  39.      * @return 
  40.      * @throws Exception 
  41.      */  
  42.     public static String encrypt(String source) throws Exception {  
  43.           
  44.         Key publicKey = getKey(PUBLIC_KEY_FILE);  
  45.   
  46.         /** 得到Cipher对象来实现对源数据的RSA加密 */  
  47.         Cipher cipher = Cipher.getInstance(ALGORITHM);  
  48.         cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  49.         byte[] b = source.getBytes();  
  50.         /** 执行加密操作 */  
  51.         byte[] b1 = cipher.doFinal(b);  
  52.         BASE64Encoder encoder = new BASE64Encoder();  
  53.         return encoder.encode(b1);  
  54.     }  
  55.   
  56.     /** 
  57.      * 解密算法 
  58.      * @param cryptograph    密文 
  59.      * @return 
  60.      * @throws Exception 
  61.      */  
  62.     public static String decrypt(String cryptograph) throws Exception {  
  63.           
  64.         Key privateKey = getKey(PRIVATE_KEY_FILE);  
  65.   
  66.         /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */  
  67.         Cipher cipher = Cipher.getInstance(ALGORITHM);  
  68.         cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  69.         BASE64Decoder decoder = new BASE64Decoder();  
  70.         byte[] b1 = decoder.decodeBuffer(cryptograph);  
  71.   
  72.         /** 执行解密操作 */  
  73.         byte[] b = cipher.doFinal(b1);  
  74.         return new String(b);  
  75.     }  
  76.       
  77.     private static Key getKey(String fileName) throws Exception, IOException {  
  78.         Key key;  
  79.         ObjectInputStream ois = null;  
  80.         try {  
  81.             /** 将文件中的私钥对象读出 */  
  82.             ois = new ObjectInputStream(new FileInputStream(fileName));  
  83.             key = (Key) ois.readObject();  
  84.         } catch (Exception e) {  
  85.             throw e;  
  86.         } finally {  
  87.             ois.close();  
  88.         }  
  89.         return key;  
  90.     }  
  91. }  

        运行结果:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子非鱼yy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值