RSA加密工具类

package com.trust.common.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


import javax.crypto.Cipher;



/**
 * RSA加签验签工具类
 * 
 */
public class RSAUtil {

    private static final String encode = "utf-8";
    /**
     * 加密算法:RSA
     */
    private static final String ENCRYPT_ALG_RSA = "RSA";
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * RSA签名
     * 
     * @param priKey RSA私钥
     * @param params 原始信息
     * @return 返回字符串
     * @throws Exception 异常
     */
    public static String rsaSign(String priKey, Map<String, String> params) throws Exception {
        if (StringUtils.isBlank(priKey) || params == null || params.size() == 0) {
            throw new Exception("RsaSignUtil.rsaSign error,params is blank");
        }

        String src = paramConvertor(params);

        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
            KeyFactory fac = KeyFactory.getInstance("RSA");
            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
            Signature sigEng = Signature.getInstance("SHA256WithRSA");
            sigEng.initSign(privateKey);
            sigEng.update(src.getBytes(encode));
            byte[] signature = sigEng.sign();
            return Base64.encodeBase64String(signature).replaceAll("\r|\n", "");
        } catch (Exception e) {
            throw new Exception("RsaSignUtil.rsaSign error", e);
        }
    }


    /**
     * RSA签名
     * 
     * @param priKey RSA私钥
     * @param
     * @return 返回字符串
     * @throws Exception 异常
     */
    public static String StringrsaSign(String priKey, String str) throws Exception {
        if (StringUtils.isBlank(priKey) || str == null || str.length() == 0) {
            throw new Exception("RsaSignUtil.rsaSign error,params is blank");
        }


        try {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(priKey));
            KeyFactory fac = KeyFactory.getInstance("RSA");
            RSAPrivateKey privateKey = (RSAPrivateKey) fac.generatePrivate(keySpec);
            Signature sigEng = Signature.getInstance("SHA256WithRSA");
            sigEng.initSign(privateKey);
            sigEng.update(str.getBytes(encode));
            byte[] signature = sigEng.sign();
            return Base64.encodeBase64String(signature).replaceAll("\r|\n", "");
        } catch (Exception e) {
            throw new Exception("RsaSignUtil.rsaSign error", e);
        }
    }

    /**
     * RSA验签
     * 
     * @param pubKey RSA公钥
     * @param params 待验签信息
     * @return
     * @throws Exception 异常
     */
    public static boolean rsaVerify(String pubKey, Map<String, String> params)
            throws Exception {
        if (StringUtils.isBlank(pubKey) || params == null || params.size() == 0) {
            throw new Exception("RsaSignUtil:rsaVerify error,params is blank");
        }
        String sign = params.get("sign");

        if (StringUtils.isBlank(sign)) {
            throw new Exception("RsaSignUtil.rsaVerify error,sign is blank");
        }

        String src = paramConvertor(params);

        try {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.decodeBase64(pubKey));
            KeyFactory fac = KeyFactory.getInstance("RSA");
            RSAPublicKey rsaPubKey = (RSAPublicKey) fac.generatePublic(keySpec);
            Signature sigEng = Signature.getInstance("SHA256WithRSA");
            sigEng.initVerify(rsaPubKey);
            sigEng.update(src.getBytes(encode));
            byte[] signature = Base64.decodeBase64(sign);
            return sigEng.verify(signature);
        } catch (Exception e) {
            throw new Exception("RsaSignUtil.rsaVerify error", e);
        }
    }


    /**
     * map转a=b&c=d
     * 
     * @param paramMap
     * @return
     */
    private static String paramConvertor(Map<String, String> paramMap) {
        TreeMap<String, String> sortMap = new TreeMap<String, String>(paramMap);

        if (sortMap.containsKey("sign")) {
            sortMap.remove("sign");
        }
        StringBuilder sb = new StringBuilder();

        for (Map.Entry<String, String> entry : sortMap.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }


    /**
     * 获取密钥文件中的RSA公私钥 去掉RSA 密钥PKCS 文件格式中的“-----BEGIN PUBLIC KEY-----” “-----END
     * PUBLIC KEY-----”无用字符串
     * 
     * @param filePath
     * @return
     */
    public static String getRsaKeyFromPkcsFile(String filePath) throws Exception {
        if (StringUtils.isBlank(filePath)) {
            throw new Exception(
                "RsaSignUtil.getRsaKeyFromPkcsFile error,key file is not exist");
        }
        try {
            BufferedReader br = new BufferedReader(new FileReader(filePath));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                if (readLine.charAt(0) == '-') {
                    continue;
                } else {
                    sb.append(readLine);
                    sb.append('\r');
                }
            }
            br.close();
            return sb.toString();
        } catch (Exception e) {
            throw new Exception("RsaSignUtil.getRsaKeyFromPkcsFile error,key file is blank",e);
        }
    }

    /**
     * rsa 加密
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, File publicKeyPemFile) throws Exception {
        String publicKeyStr = getRealKey(publicKeyPemFile);
        PublicKey  publicKey =getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes(encode).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.getBytes(encode), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(encode), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        // 加密后的字符串
        System.out.println(Base64.encodeBase64(encryptedData)==Base64.encodeBase64(encryptedData));
        System.out.println("jiamiiiiii"+(Base64.decodeBase64(Base64.encodeBase64String(encryptedData))==Base64.encodeBase64(encryptedData)));
        return Base64.encodeBase64String(encryptedData);
    }
    /**
     * rsa 加密
     * @param plaintext 明文
     * @param
     * @return
     * @throws Exception
     */
    public static String encryptKey(String plaintext, File publicKeyPemFile) throws Exception {
        String publicKeyStr = getRealKey(publicKeyPemFile);
        PublicKey  publicKey =getPublicKey(publicKeyStr);
        Cipher cipher = Cipher.getInstance(ENCRYPT_ALG_RSA);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] result = cipher.doFinal(plaintext.getBytes(encode));
        System.out.println(Base64.encodeBase64(result).equals(Base64.encodeBase64(result)));


        return new String(Base64.encodeBase64(result));
    }
    /**
     * rsa 解密
     * @param
     * @param
     * @return
     * @throws Exception
     */
    public static String decryptKey(String data, File privateKeyPemFile) throws Exception {
        String privateKeyStr = getRealKey(privateKeyPemFile);
        PrivateKey privateKey =getPrivateKey(privateKeyStr);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = dataBytes.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(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        // 解密后的内容
        return new String(decryptedData, "UTF-8");

    }



    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * rsa 解密
     * @param ciphertext 密文
     * @param
     * @return
     * @throws Exception
     */
    public static String decrypt(String ciphertext, File privateKeyPemFile) throws Exception {

        PrivateKey privateKey =loadPrivateKeyFromPem(privateKeyPemFile);
        Cipher cipher = Cipher.getInstance(ENCRYPT_ALG_RSA);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
       System.out.println("aaa"+ciphertext);
        BASE64Decoder decoder = new BASE64Decoder();
        System.out.println(new String(decoder.decodeBuffer(ciphertext),"utf-8"));
        byte[] encryptBytes = decoder.decodeBuffer(ciphertext);
        System.out.println(encryptBytes);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);


        System.out.println(decryptBytes);

        return new String(decryptBytes);

    }





    /**
     * 从公钥pem文件中加载公钥PublicKey
     * @param publicKeyPemFile 公钥pem文件
     * @return PublicKey
     */
    private static PublicKey loadPublicKeyFromPem(File publicKeyPemFile) throws Exception {
        String publicKeyStr = getRealKey(publicKeyPemFile);

        BASE64Decoder decoder = new BASE64Decoder();

        byte[] keyBytes = decoder.decodeBuffer(publicKeyStr);

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALG_RSA);

        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        return publicKey;
    }

    /**
     * 从私钥pem文件中加载私钥PrivateKey
     * @param privateKeyPemFile 私钥pem文件
     * @return PrivateKey
     */
    private static PrivateKey loadPrivateKeyFromPem(File privateKeyPemFile) throws Exception {
        String privateKeyStr = getRealKey(privateKeyPemFile);

        BASE64Decoder decoder = new BASE64Decoder();

        byte[] keyBytes = decoder.decodeBuffer(privateKeyStr);

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALG_RSA);

        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        return privateKey;
    }

    /**
     * 从pem文件中抽取实际的key内容。即----- BEGIN xxx ----- 和 END xxx ----- 中间的内容
     * @param permFile pem文件
     * @return 实际的key内容
     * @throws Exception
     */
    private static String getRealKey(File permFile) throws Exception {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(permFile));
        StringBuilder sb = new StringBuilder();

        String line = bufferedReader.readLine();
        while (line != null) {
            // 去掉行 ----- BEGIN xxx----- 和 ----- END xxx-----
            if (!line.startsWith("-")) {
                sb.append(line);
            }

            line = bufferedReader.readLine();
        }

        bufferedReader.close();

        return sb.toString();
    }
    //把byte[]元素之间添加空格,并转化成字符串返回,
    public String byteToString(byte[] resouce){
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < resouce.length; i++) {
            if (i == resouce.length-1) {
                sb.append(Byte.toString(resouce[i]));
            }else{
                sb.append(Byte.toString(resouce[i]));
                sb.append(" ");
            }
        }
        return sb.toString();

    }

    //    把字符串按照空格进行拆分成数组,然后转化成byte[],返回
    public byte[] stringToByte(String resouce){
        String[] strArr = resouce.split(" ");
        int len = strArr.length;
        byte[] clone = new byte[len];
        for (int i = 0; i < len; i++) {
            clone[i] = Byte.parseByte(strArr[i]);
        }

        return clone;

    }

    /**
     * 根据公钥字符串加密方法
     *
     * @param source 源数据
     * @param publicKey 公钥字符串
     * @return
     * @throws Exception
     */
    public static String encryptRSAs(String source,File file ) throws Exception {
        String publicKey = getRealKey(file);
        /** 得到Cipher对象来实现对源数据的RSA加密 */
        Cipher cipher = Cipher.getInstance(ENCRYPT_ALG_RSA);
        cipher.init(Cipher.ENCRYPT_MODE, getPubKey(publicKey));
        byte[] b = source.getBytes("UTF-8");
        int inputLen = b.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(b, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(b, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        out.close();
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(out.toByteArray());
    }

    /**
     * 根据私钥字符串解密算法
     *
     * @param source 密文
     * @param privateKey 私钥字符串
     * @return
     * @throws Exception
     */
    public static String decryptRSAs(String source,File file) throws Exception {
        String privateKey=getRealKey(file);
        /** 得到Cipher对象对已用公钥加密的数据进行RSA解密 */
        Cipher cipher = Cipher.getInstance(ENCRYPT_ALG_RSA);
        cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKey));
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] b1 = decoder.decodeBuffer(source);
        int inputLen = b1.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(b1, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(b1, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        /** 执行解密操作 */
        out.close();
        return new String(out.toByteArray(),"UTF-8");
    }
    /**
     * 实例化公钥
     * @s 公钥
     * @return
     */
    public static PublicKey getPubKey(String s ) throws Exception {
        PublicKey publicKey = null;
        java.security.spec.X509EncodedKeySpec bobPubKeySpec = new java.security.spec.X509EncodedKeySpec(
                new BASE64Decoder().decodeBuffer(s));
        // RSA对称加密算法
        java.security.KeyFactory keyFactory;
        keyFactory = java.security.KeyFactory.getInstance("RSA");
        // 取公钥匙对象
        publicKey = keyFactory.generatePublic(bobPubKeySpec);

        return publicKey;
    }

    /**
     * 实例化私钥
     *
     * @s 私钥
     * @return
     */
    public static PrivateKey getPrivateKey(String s) throws Exception{
        PrivateKey privateKey = null;
        PKCS8EncodedKeySpec priPKCS8;
        priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(s));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        privateKey = keyf.generatePrivate(priPKCS8);
        return privateKey;
    }

/*

    public static String decrypt(String key, String salt, String content) throws Exception {
        // 解密
        PrivateKey ownPriKeyRSA = PrivateKeysMemCacheSingleton.getInstance().getKey(hnxtPriKeyPemPath);
        return AESUtils.decrypt(RSAUtils.decrypt(ownPriKeyRSA, RSA_ECB_ALGORITHM, key),
                RSAUtils.decrypt(ownPriKeyRSA, RSA_ECB_ALGORITHM, salt), AES_CFB_ALGORITHM, content);
    }
*/


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值