zoukankan      html  css  js  c++  java
  • RSA算法加密 工具类

      1 import java.io.ByteArrayInputStream;
      2 import java.io.ByteArrayOutputStream;
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileOutputStream;
      6 import java.io.InputStream;
      7 import java.io.OutputStream;
      8 
      9 import it.sauronsoftware.base64.Base64;
     10 public class Base64Utils{
     11     /** */
     12     /**
     13      * 文件读取缓冲区大小
     14      */
     15     private static final int CACHE_SIZE = 1024;
     16 
     17     /** */
     18     /**
     19      * <p>
     20      * BASE64字符串解码为二进制数据
     21      * </p>
     22      * 
     23      * @param base64
     24      * @return
     25      * @throws Exception
     26      */
     27     public static byte[] decode(String base64) throws Exception {
     28         return Base64.decode(base64.getBytes("UTF-8"));
     29     }
     30 
     31     /** */
     32     /**
     33      * <p>
     34      * 二进制数据编码为BASE64字符串
     35      * </p>
     36      * 
     37      * @param bytes
     38      * @return
     39      * @throws Exception
     40      */
     41     public static String encode(byte[] bytes) throws Exception {
     42         return new String(Base64.encode(bytes));
     43     }
     44 
     45     /** */
     46     /**
     47      * <p>
     48      * 将文件编码为BASE64字符串
     49      * </p>
     50      * <p>
     51      * 大文件慎用,可能会导致内存溢出
     52      * </p>
     53      * 
     54      * @param filePath
     55      *            文件绝对路径
     56      * @return
     57      * @throws Exception
     58      */
     59     public static String encodeFile(String filePath) throws Exception {
     60         byte[] bytes = fileToByte(filePath);
     61         return encode(bytes);
     62     }
     63 
     64     /** */
     65     /**
     66      * <p>
     67      * BASE64字符串转回文件
     68      * </p>
     69      * 
     70      * @param filePath
     71      *            文件绝对路径
     72      * @param base64
     73      *            编码字符串
     74      * @throws Exception
     75      */
     76     public static void decodeToFile(String filePath, String base64) throws Exception {
     77         byte[] bytes = decode(base64);
     78         byteArrayToFile(bytes, filePath);
     79     }
     80 
     81     /** */
     82     /**
     83      * <p>
     84      * 文件转换为二进制数组
     85      * </p>
     86      * 
     87      * @param filePath
     88      *            文件路径
     89      * @return
     90      * @throws Exception
     91      */
     92     public static byte[] fileToByte(String filePath) throws Exception {
     93         byte[] data = new byte[0];
     94         File file = new File(filePath);
     95         if (file.exists()) {
     96             FileInputStream in = new FileInputStream(file);
     97             ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
     98             byte[] cache = new byte[CACHE_SIZE];
     99             int nRead = 0;
    100             while ((nRead = in.read(cache)) != -1) {
    101                 out.write(cache, 0, nRead);
    102                 out.flush();
    103             }
    104             out.close();
    105             in.close();
    106             data = out.toByteArray();
    107         }
    108         return data;
    109     }
    110 
    111     /** */
    112     /**
    113      * <p>
    114      * 二进制数据写文件
    115      * </p>
    116      * 
    117      * @param bytes
    118      *            二进制数据
    119      * @param filePath
    120      *            文件生成目录
    121      */
    122     public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {
    123         InputStream in = new ByteArrayInputStream(bytes);
    124         File destFile = new File(filePath);
    125         if (!destFile.getParentFile().exists()) {
    126             destFile.getParentFile().mkdirs();
    127         }
    128         destFile.createNewFile();
    129         OutputStream out = new FileOutputStream(destFile);
    130         byte[] cache = new byte[CACHE_SIZE];
    131         int nRead = 0;
    132         while ((nRead = in.read(cache)) != -1) {
    133             out.write(cache, 0, nRead);
    134             out.flush();
    135         }
    136         out.close();
    137         in.close();
    138     }
    139 
    140 }
    View Code

    base64Utils

    import java.io.ByteArrayOutputStream;
    import java.security.Key;
    import java.security.KeyFactory;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.PrivateKey;
    import java.security.PublicKey;
    import java.security.Signature;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.HashMap;
    import java.util.Map;
    
    import javax.crypto.Cipher;
    public class RSAUtils{
        /** */
        /**
         * 加密算法RSA
         */
        public static final String KEY_ALGORITHM = "RSA";
    
        /** */
        /**
         * 签名算法
         */
        public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
    
        /** */
        /**
         * 获取公钥的key
         */
        private static final String PUBLIC_KEY = "RSAPublicKey";
    
        /** */
        /**
         * 获取私钥的key
         */
        private static final String PRIVATE_KEY = "RSAPrivateKey";
    
        /** */
        /**
         * RSA最大加密明文大小
         */
        private static final int MAX_ENCRYPT_BLOCK = 117;
    
        /** */
        /**
         * RSA最大解密密文大小
         */
        private static final int MAX_DECRYPT_BLOCK = 128;
    
        /** */
        /**
         * <p>
         * 生成密钥对(公钥和私钥)
         * </p>
         * 
         * @return
         * @throws Exception
         */
        public static Map<String, Object> genKeyPair() throws Exception {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
            Map<String, Object> keyMap = new HashMap<String, Object>(2);
            keyMap.put(PUBLIC_KEY, publicKey);
            keyMap.put(PRIVATE_KEY, privateKey);
            return keyMap;
        }
    
        /** */
        /**
         * <p>
         * 用私钥对信息生成数字签名
         * </p>
         * 
         * @param data
         *            已加密数据
         * @param privateKey
         *            私钥(BASE64编码)
         * 
         * @return
         * @throws Exception
         */
        public static String sign(byte[] data, String privateKey) throws Exception {
            byte[] keyBytes = Base64Utils.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateK);
            signature.update(data);
            return Base64Utils.encode(signature.sign());
        }
    
        /** */
        /**
         * <p>
         * 校验数字签名
         * </p>
         * 
         * @param data
         *            已加密数据
         * @param publicKey
         *            公钥(BASE64编码)
         * @param sign
         *            数字签名
         * 
         * @return
         * @throws Exception
         * 
         */
        public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
            byte[] keyBytes = Base64Utils.decode(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicK);
            signature.update(data);
            return signature.verify(Base64Utils.decode(sign));
        }
    
        /** */
        /**
         * <P>
         * 私钥解密
         * </p>
         * 
         * @param encryptedData
         *            已加密数据
         * @param privateKey
         *            私钥(BASE64编码)
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
            byte[] keyBytes = Base64Utils.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateK);
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        }
    
        /** */
        /**
         * <p>
         * 公钥解密
         * </p>
         * 
         * @param encryptedData
         *            已加密数据
         * @param publicKey
         *            公钥(BASE64编码)
         * @return
         * @throws Exception
         */
        public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
            byte[] keyBytes = Base64Utils.decode(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicK);
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();
            return decryptedData;
        }
    
        /** */
        /**
         * <p>
         * 公钥加密
         * </p>
         * 
         * @param data
         *            源数据
         * @param publicKey
         *            公钥(BASE64编码)
         * @return
         * @throws Exception
         */
        public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
            byte[] keyBytes = Base64Utils.decode(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        }
    
        /** */
        /**
         * <p>
         * 私钥加密
         * </p>
         * 
         * @param data
         *            源数据
         * @param privateKey
         *            私钥(BASE64编码)
         * @return
         * @throws Exception
         */
        public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
            byte[] keyBytes = Base64Utils.decode(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateK);
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            return encryptedData;
        }
    
        /** */
        /**
         * <p>
         * 获取私钥
         * </p>
         * 
         * @param keyMap
         *            密钥对
         * @return
         * @throws Exception
         */
        public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
            Key key = (Key) keyMap.get(PRIVATE_KEY);
            return Base64Utils.encode(key.getEncoded());
        }
    
        /** */
        /**
         * <p>
         * 获取公钥
         * </p>
         * 
         * @param keyMap
         *            密钥对
         * @return
         * @throws Exception
         */
        public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
            Key key = (Key) keyMap.get(PUBLIC_KEY);
            return Base64Utils.encode(key.getEncoded());
        }
    
        /**
         * java端公钥加密
         */
        public static String encryptedDataOnJava(String data, String PUBLICKEY) {
            try {
                data = Base64Utils.encode(encryptByPublicKey(data.getBytes(), PUBLICKEY));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return data;
        }
    
        /**
         * java端私钥解密
         */
        public static String decryptDataOnJava(String data, String PRIVATEKEY) {
            String temp = "";
            try {
                byte[] rs = Base64Utils.decode(data);
                temp = new String(RSAUtils.decryptByPrivateKey(rs, PRIVATEKEY),"UTF-8"); //以utf-8的方式生成字符串
    
            } catch (Exception e) {
                e.printStackTrace();
            }
            return temp;
        }
    
    }
    View Code

    rsa 获取公私钥 加解密 算法

    往事如烟,余生有我.
  • 相关阅读:
    Linux下安装破解JIRA 6.3.6 并连接MYSQL5
    centos7 系统安装问题汇总
    CentOS7安装iptables防火墙
    Vue全家桶实战 从零独立开发企业级电商系统
    小米笔记本pro充电10秒断开
    mac电脑的使用
    autojs解决方案
    auto.js连接vscode
    小米6手机刷机亲测详解
    #002前端基础-JS-浏览器中堆栈内存的底层处理
  • 原文地址:https://www.cnblogs.com/assistants/p/11655134.html
Copyright © 2011-2022 走看看