Java8 RSA加解密

package com.teddy.cpayment.core.utils;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;

public class RSA2Utils {

    private static final int KEY_SIZE = 1024;
    private static final String SIGN_TYPE = "MD5withRSA";
    /**
     * RSA最大解密密文大小,单位字节
     */
    private static final int MAX_DECRYPT_BLOCK = KEY_SIZE >> 3;
    /**
     * RSA最大加密明文大小,最大长度=密钥长度-11(单位是字节,即byte)
     */
    private static final int MAX_ENCRYPT_BLOCK = MAX_DECRYPT_BLOCK - 11;

    public static void generateKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");

        keyPairGenerator.initialize(KEY_SIZE);

        // 生成密匙对
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 得到公钥
        Key publicKey = keyPair.getPublic();

        // 得到私钥
        Key privateKey = keyPair.getPrivate();

        String publicKeyStr = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        String privateKeyStr = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        System.out.println("pub:" + publicKeyStr);
        System.out.println("pri:" + privateKeyStr);
    }

    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return 私钥
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.getDecoder().decode(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }

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

    /**
     * RSA加密
     *
     * @param data 待加密数据
     * @param pubKey 公钥秘串
     * @return 加密的内容
     */
    public static String encrypt(String data, String pubKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(pubKey));
        int inputLen = data.getBytes().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(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
        return Base64.getEncoder().encodeToString(encryptedData);
    }

    /**
     * RSA解密
     *
     * @param data 待解密数据
     * @param priKey 私钥密串
     * @return 解密后数据
     */
    public static String decrypt(String data, String priKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, getPrivateKey(priKey));
        byte[] dataBytes = Base64.getDecoder().decode(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;
        }
        out.close();
        // 解密后的内容
        return out.toString(StandardCharsets.UTF_8);
    }

    /**
     * 签名
     *
     * @param data 待签名数据
     * @param priKey 私钥
     * @return 签名
     */
    public static String sign(String data, String priKey) throws Exception {
        Signature signature = Signature.getInstance(SIGN_TYPE);
        signature.initSign(getPrivateKey(priKey));
        signature.update(data.getBytes());
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param pubKey 公钥密串
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, String pubKey, String sign) throws Exception {
        Signature signature = Signature.getInstance(SIGN_TYPE);
        signature.initVerify(getPublicKey(pubKey));
        signature.update(srcData.getBytes());
        return signature.verify(Base64.getDecoder().decode(sign));
    }
}

你可能感兴趣的:(JAVA,java,servlet,jvm)