RSA加解密工具类整理

RSA加解密工具类整理

  •  2019 年 1 月 7 日
  •  520
  •  Java RSA 

RSA加解密工具类. 分段加/解密. 

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.Cipher;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RSAUtil {
    private static final Logger logger = LoggerFactory.getLogger(RSAUtil.class);
    /**
     * 1024  RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    /**
     * 1024  RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 字符串私钥转私钥对象      
     * @param privateKeyContent 私钥字符串      
     * @return
     */
    public static PrivateKey parsePrivateKey(String privateKeyContent) {
        try {
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyContent);
            PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(privateKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePrivate(keySpecPKCS8);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("转换私钥错误:", e);
        }
        return null;
    }

    /**
     * 字符串公钥转公钥对象      *      * @param publicKeyContent 公钥字符串      * @return
     */
    public static PublicKey parsePublicKey(String publicKeyContent) {
        try {
            byte[] publicKeyBytes = Base64.getDecoder().decode(publicKeyContent);
            X509EncodedKeySpec keySpecX509 = new X509EncodedKeySpec(publicKeyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return keyFactory.generatePublic(keySpecX509);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            logger.error("转换公钥错误:", e);
        }
        return null;
    }

    /**
     * RSA加密      
     * @param content 待签名内容      
     * @param key     公钥/私钥      
     * @return 加密字符串
     */
    public static String encrypt(String content, Key key) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            // 对数据分段加密            
            byte[] data = content.getBytes("utf-8");
            int inputLen = data.length;
            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();
            return Base64.getEncoder().encodeToString(encryptedData);
        } catch (Exception e) {
            logger.error("encrypt:", e);
        }
        return null;
    }

    /**
     * RSA解密      
     * @param content 待解密内容      
     * @param key     公钥/私钥      
     * @return 解密字符串
     */
    public static String decrypt(String content, Key key) {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] data = Base64.getDecoder().decode(content);
            int inputLen = data.length;
            int offSet = 0;
            byte[] cache;
            int i = 0;             
            // 对数据分段解密            
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            return new String(decryptedData, "utf-8");
        } catch (Exception e) {
            logger.error("decrypt:", e);
        }
        return null;
    }

    /**
     * RSA签名
     *
     * @param content    待签名数据
     * @param privateKey 秘钥
     * @return
     */
    public static String sign(String content, PrivateKey privateKey) {
        try {
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initSign(privateKey);
            signature.update(content.getBytes("utf-8"));
            byte[] result = signature.sign();
            return Base64.getEncoder().encodeToString(result);
        } catch (Exception e) {
            logger.error("sign:", e);
        }
        return null;
    }

    /**
     * RSA签名校验
     *
     * @param content   待校验内容
     * @param sign      签名
     * @param publicKey 公钥
     * @return
     */
    public static boolean verifySign(String content, String sign, PublicKey publicKey) {
        if (StringUtils.isEmpty(content) || StringUtils.isEmpty(sign)) {
            return false;
        }
        try {
            Signature signature = Signature.getInstance("SHA1withRSA");
            signature.initVerify(publicKey);
            signature.update(content.getBytes("utf-8"));
            return signature.verify(Base64.getDecoder().decode(sign));
        } catch (Exception e) {
            logger.error("verifySign:", e);
        }
        return false;
    }
}


扫一扫分享到微信

已有 条评论
写评论