zoukankan      html  css  js  c++  java
  • RSA非对称加密Java实现

    原文

    加密基础方法类

     1 import java.security.MessageDigest;
     2 import sun.misc.BASE64Decoder;
     3 import sun.misc.BASE64Encoder;
     4 public class SecurityBase {
     5     public static final String KEY_SHA="SHA";
     6     public static final String KEY_MD5="MD5";
     7     //BASE64解密
     8     public static byte[] decryptBASE64(String key) throws Exception{
     9         return (new BASE64Decoder()).decodeBuffer(key);
    10     }
    11     //BASE64加密
    12     public static String encryptBASE64(byte[] key)throws Exception{
    13         return (new BASE64Encoder()).encodeBuffer(key);
    14     }
    15     //MD5加密
    16     public static byte[] encryptMD5(byte[] data)throws Exception{
    17         MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);
    18         md5.update(data);
    19         return md5.digest();
    20     }
    21     //SHA加密
    22     public static byte[] encryptSHA(byte[] data)throws Exception{
    23         MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
    24         sha.update(data);
    25         return sha.digest();
    26     }
    27 }

    RSA非对称加密实现类

      1 import java.security.Key;
      2 import java.security.KeyFactory;
      3 import java.security.KeyPair;
      4 import java.security.KeyPairGenerator;
      5 import java.security.PrivateKey;
      6 import java.security.PublicKey;
      7 import java.security.Signature;
      8 import java.security.interfaces.RSAPrivateKey;
      9 import java.security.interfaces.RSAPublicKey;
     10 import java.security.spec.PKCS8EncodedKeySpec;
     11 import java.security.spec.X509EncodedKeySpec;
     12 import java.util.HashMap;
     13 import java.util.Map;
     14 import javax.crypto.Cipher;
     15 public class RSASecurity extends SecurityBase {
     16     public static final String KEY_ALGORTHM="RSA";
     17     public static final String SIGNATURE_ALGORITHM="MD5withRSA";
     18     public static final String PUBLIC_KEY = "RSAPublicKey";//公钥
     19     public static final String PRIVATE_KEY = "RSAPrivateKey";//私钥
     20     /**
     21      * 初始化密钥
     22      * @return
     23      * @throws Exception
     24      */
     25     public static Map<String,Key> createKeys()throws Exception{
     26         KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KEY_ALGORTHM);
     27         keyPairGenerator.initialize(1024);
     28         KeyPair keyPair = keyPairGenerator.generateKeyPair();
     29         //公钥
     30         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
     31         //私钥
     32         RSAPrivateKey privateKey =  (RSAPrivateKey) keyPair.getPrivate();
     33         Map<String,Key> keyMap = new HashMap<String, Key>(2);
     34         keyMap.put(PUBLIC_KEY, publicKey);
     35         keyMap.put(PRIVATE_KEY, privateKey);
     36         return keyMap;
     37     }
     38     /**
     39      * 取得公钥,并转化为String类型
     40      * @param keyMap
     41      * @return
     42      * @throws Exception
     43      */
     44     public static String getPublicKey(Map<String, Key> keyMap)throws Exception{
     45         Key key = keyMap.get(PUBLIC_KEY);  
     46         return encryptBASE64(key.getEncoded());     
     47     }
     48     /**
     49      * 取得私钥,并转化为String类型
     50      * @param keyMap
     51      * @return
     52      * @throws Exception
     53      */
     54     public static String getPrivateKey(Map<String, Key> keyMap) throws Exception{
     55         Key key =  keyMap.get(PRIVATE_KEY);  
     56         return encryptBASE64(key.getEncoded());     
     57     }
     58     /**
     59      * 用私钥加密
     60      * @param data  加密数据
     61      * @param key   密钥
     62      * @return
     63      * @throws Exception
     64      */
     65     public static byte[] encryptByPrivateKey(byte[] data,String key)throws Exception{
     66         //解密密钥
     67         byte[] keyBytes = decryptBASE64(key);
     68         //取私钥
     69         PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
     70         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
     71         Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
     72         //对数据加密
     73         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
     74         cipher.init(Cipher.ENCRYPT_MODE, privateKey);
     75         return cipher.doFinal(data);
     76     }
     77     /**
     78      * 用私钥解密
     79      * @param data  加密数据
     80      * @param key   密钥
     81      * @return
     82      * @throws Exception
     83      */
     84     public static byte[] decryptByPrivateKey(byte[] data,String key)throws Exception{
     85         //对私钥解密
     86         byte[] keyBytes = decryptBASE64(key);
     87         PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
     88         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
     89         Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
     90         //对数据解密
     91         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
     92         cipher.init(Cipher.DECRYPT_MODE, privateKey);
     93         return cipher.doFinal(data);
     94     }
     95     /**
     96      * 用公钥加密
     97      * @param data  加密数据
     98      * @param key   密钥
     99      * @return
    100      * @throws Exception
    101      */
    102     public static byte[] encryptByPublicKey(byte[] data,String key)throws Exception{
    103         //对公钥解密
    104         byte[] keyBytes = decryptBASE64(key);
    105         //取公钥
    106         X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    107         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    108         Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    109         //对数据解密
    110         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    111         cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    112         return cipher.doFinal(data);
    113     }
    114     /**
    115      * 用公钥解密
    116      * @param data  加密数据
    117      * @param key   密钥
    118      * @return
    119      * @throws Exception
    120      */
    121     public static byte[] decryptByPublicKey(byte[] data,String key)throws Exception{
    122         //对私钥解密
    123         byte[] keyBytes = decryptBASE64(key);
    124         X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    125         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    126         Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    127         //对数据解密
    128         Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    129         cipher.init(Cipher.DECRYPT_MODE, publicKey);
    130         return cipher.doFinal(data);
    131     }
    132     /**
    133      *  用私钥对信息生成数字签名
    134      * @param data  //加密数据
    135      * @param privateKey    //私钥
    136      * @return
    137      * @throws Exception
    138      */
    139     public static String sign(byte[] data,String privateKey)throws Exception{
    140         //解密私钥
    141         byte[] keyBytes = decryptBASE64(privateKey);
    142         //构造PKCS8EncodedKeySpec对象
    143         PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
    144         //指定加密算法
    145         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    146         //取私钥匙对象
    147         PrivateKey privateKey2 = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    148         //用私钥对信息生成数字签名
    149         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    150         signature.initSign(privateKey2);
    151         signature.update(data);
    152         return encryptBASE64(signature.sign());
    153     }
    154     /**
    155      * 校验数字签名
    156      * @param data  加密数据
    157      * @param publicKey 公钥
    158      * @param sign  数字签名
    159      * @return
    160      * @throws Exception
    161      */
    162     public static boolean verify(byte[] data,String publicKey,String sign)throws Exception{
    163         //解密公钥
    164         byte[] keyBytes = decryptBASE64(publicKey);
    165         //构造X509EncodedKeySpec对象
    166         X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
    167         //指定加密算法
    168         KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
    169         //取公钥匙对象
    170         PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);
    171         Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    172         signature.initVerify(publicKey2);
    173         signature.update(data);
    174         //验证签名是否正常
    175         return signature.verify(decryptBASE64(sign));
    176     }
    177     /**
    178      * 
    179      * @Title: main
    180      * @Description: 测试
    181      * @param @param args
    182      * @return void
    183      * @throws
    184      */
    185     public static void main(String[] args) {
    186         try {
    187             Map<String,Key> data = createKeys();
    188             String content = "JavaRsaEncoder";
    189             System.out.println("加密前:"+content);
    190             String encode = encryptBASE64(encryptByPrivateKey(content.getBytes(), getPrivateKey(data)));
    191             System.out.println("加密后:"+encode);
    192             String decode = new String(decryptByPublicKey(decryptBASE64(encode), getPublicKey(data)));
    193             System.out.println("解密后:"+decode);
    194         } catch (Exception e) {
    195             e.printStackTrace();
    196         }
    197     }
    198 }

    运行结果

    1 加密前:JavaRsaEncoder
    2 加密后:l+vhbdRdq3dc5nr6m4jSIuW0ufKeCYBw4ds2Es9/SmPa/Dp298gZsT8KkZRwlKcm60+MV67fVMyG
    3 OgwCZWbqQqmu8Mr+ZuqUWWnIZ0fIi1JAaqiwqsg7SaIkvixU35HHdsxmNMdK+1qPDWBE5sCjSCJ+
    4 xaG0Y8BOpyGDlpL9bOc=
    5 解密后:JavaRsaEncoder
  • 相关阅读:
    Struts2快速后台验证 使用
    Python发送邮件
    【Python】【Flask】前端调用后端方法
    后台参数验证的几种方式
    使用 jQuery 进行前端验证
    postman接口测试——笔记
    安全测试
    jQuery 是javascript的一个库(常用插件、处理器)
    javascript 的 事件类型(事件)
    JavaScript的 基本数据类型---对象
  • 原文地址:https://www.cnblogs.com/libaoting/p/4108680.html
Copyright © 2011-2022 走看看