如何用java RSA生成生成公钥私钥(非对称加密)

时间:2025-03-12 07:11:13
package com; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import .PKCS8EncodedKeySpec; import .X509EncodedKeySpec; import ; import ; import ; import ; import .BASE64Decoder; import .BASE64Encoder; public class CreateSecretKey {     public static final String KEY_ALGORITHM = "RSA";     private static final String PUBLIC_KEY = "RSAPublicKey";     private static final String PRIVATE_KEY = "RSAPrivateKey";     public static final String SIGNATURE_ALGORITHM="MD5withRSA";      /**      * RSA最大加密明文大小      */     private static final int MAX_ENCRYPT_BLOCK = 117;          /**      * RSA最大解密密文大小      */     private static final int MAX_DECRYPT_BLOCK = 128;     //获得公钥字符串     public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {         //获得map中的公钥对象 转为key对象         Key key = (Key) (PUBLIC_KEY);         //编码返回字符串         return encryptBASE64(());     }     //获得私钥字符串     public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {         //获得map中的私钥对象 转为key对象         Key key = (Key) (PRIVATE_KEY);         //编码返回字符串         return encryptBASE64(());     }          //获取公钥     public static PublicKey getPublicKey(String key) throws Exception {           byte[] keyBytes;           keyBytes = (new BASE64Decoder()).decodeBuffer(key);           X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);           KeyFactory keyFactory = (KEY_ALGORITHM);           PublicKey publicKey = (keySpec);           return publicKey;       }            //获取私钥     public static PrivateKey getPrivateKey(String key) throws Exception {           byte[] keyBytes;           keyBytes = (new BASE64Decoder()).decodeBuffer(key);           PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);           KeyFactory keyFactory = (KEY_ALGORITHM);           PrivateKey privateKey = (keySpec);           return privateKey;       }          //解码返回byte     public static byte[] decryptBASE64(String key) throws Exception {         return (new BASE64Decoder()).decodeBuffer(key);     }     //编码返回字符串     public static String encryptBASE64(byte[] key) throws Exception {         return (new BASE64Encoder()).encodeBuffer(key);     }          //***************************签名和验证*******************************       public static byte[] sign(byte[] data,String privateKeyStr) throws Exception{         PrivateKey priK = getPrivateKey(privateKeyStr);         Signature sig = (SIGNATURE_ALGORITHM);              (priK);         (data);         return ();       }            public static boolean verify(byte[] data,byte[] sign,String publicKeyStr) throws Exception{         PublicKey pubK = getPublicKey(publicKeyStr);         Signature sig = (SIGNATURE_ALGORITHM);         (pubK);         (data);         return (sign);       }          //************************加密解密**************************       public static byte[] encrypt(byte[] plainText,String publicKeyStr)throws Exception{           PublicKey publicKey = getPublicKey(publicKeyStr);           Cipher cipher = (KEY_ALGORITHM);           (Cipher.ENCRYPT_MODE, publicKey);           int inputLen = ;         ByteArrayOutputStream out = new ByteArrayOutputStream();         int offSet = 0;         int i = 0;         byte[] cache;         while (inputLen - offSet > 0) {             if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {                 cache = (plainText, offSet, MAX_ENCRYPT_BLOCK);             } else {                 cache = (plainText, offSet, inputLen - offSet);             }             (cache, 0, );             i++;             offSet = i * MAX_ENCRYPT_BLOCK;         }         byte[] encryptText = ();         ();           return encryptText;       }              public static byte[] decrypt(byte[] encryptText,String privateKeyStr)throws Exception{           PrivateKey privateKey = getPrivateKey(privateKeyStr);           Cipher cipher = (KEY_ALGORITHM);           (Cipher.DECRYPT_MODE, privateKey);           int inputLen = ;         ByteArrayOutputStream out = new ByteArrayOutputStream();         int offSet = 0;         byte[] cache;         int i = 0;         // 对数据分段解密         while (inputLen - offSet > 0) {             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {                 cache = (encryptText, offSet, MAX_DECRYPT_BLOCK);             } else {                 cache = (encryptText, offSet, inputLen - offSet);             }             (cache, 0, );             i++;             offSet = i * MAX_DECRYPT_BLOCK;         }         byte[] plainText = ();         ();           return plainText;       }       public static void main(String[] args) {         Map<String, Object> keyMap;         byte[] cipherText;         String input = "Hello World!";         try {             keyMap = initKey();             String publicKey = getPublicKeyStr(keyMap);             ("公钥------------------");             (publicKey);             String privateKey = getPrivateKeyStr(keyMap);             ("私钥------------------");             (privateKey);                          ("测试可行性-------------------");             ("明文======="+input);                          cipherText = encrypt((),publicKey);              //加密后的东西              ("密文======="+new String(cipherText));             //开始解密              byte[] plainText = decrypt(cipherText,privateKey);              ("解密后明文===== " + new String(plainText));             ("验证签名-----------");                          String str="被签名的内容";               ("\n原文:"+str);               byte[] signature=sign((),privateKey);               boolean status=verify((), signature,publicKey);               ("验证情况:"+status);           } catch (Exception e) {             ();         }     } }