非对称加密实现

114 阅读4分钟

前言

非对称加密可以用来生成签名/验签、加解密数据

SM2

import cn.hutool.core.util.HexUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.SM2;
import java.security.KeyPair;

public class Test {
    public static void main(String[] args) {
        String data = "我是一段测试,Hello World !";

        KeyPair pair = SecureUtil.generateKeyPair("SM2");
        byte[] privateKey = pair.getPrivate().getEncoded();
        byte[] publicKey = pair.getPublic().getEncoded();

        // 生成签名
        SM2 sm2 = SmUtil.sm2(privateKey, publicKey);
        String sign = sm2.signHex(HexUtil.encodeHexStr(data));  // 数据转成十六进制再签名
        System.out.println("生成的签名:" + sign); // 生成的签名是十六进制

        // 验签(将十六进制转码后的数据与签名比较)
        boolean flag = sm2.verifyHex(HexUtil.encodeHexStr(data), sign); 
        System.out.println("验签结果:" + flag);

        // 加密解密数据
        String enData = sm2.encryptBase64(data, KeyType.PublicKey);
        System.out.println("enData:" + enData);
        String decryData = sm2.decryptStr(enData, KeyType.PrivateKey);
        System.out.println("decryData:" +decryData);
    }
    
}

RSA

import java.util.HashMap;
import java.util.Map;
import java.io.ByteArrayOutputStream;
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.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;

import com.alibaba.fastjson.JSONObject;

/**
 * RSA加解密及签名处理
 */
public final class NbankRSAUtil {
    
	/**
	 * RSA编码
	 */
	private static final String CHARSET = "UTF-8";

	/**
	 * 生成公私密钥对 (默认1024)
	 */
	public static Map<String, String> generateKey() {
		return generateKey(1024);
	}

	/**
	 * 生成公私密钥对
	 * @param keySize 秘钥长度 推荐1024
	 */
	public static Map<String, String> generateKey(int keySize) {
		try {
			KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
			kpg.initialize(keySize);
			KeyPair kp = kpg.genKeyPair();
			PublicKey pbkey = kp.getPublic();
			PrivateKey prkey = kp.getPrivate();
			String publicKey = Base64.getEncoder().encodeToString(pbkey.getEncoded());
			String privateKey = Base64.getEncoder().encodeToString(prkey.getEncoded());
	        Map<String, String> keyPairMap = new HashMap<String, String>();
	        keyPairMap.put("publicKey", publicKey);
	        keyPairMap.put("privateKey", privateKey);
	        return keyPairMap;
		} catch (Exception e) {
			throw new RuntimeException("生成公私密钥对失败!");
		}
	}

	/**
	 * 获取公钥
	 * @Description 将base64编码后的公钥字符串转成PublicKey实例
	 * @param publicKey
	 * @return obj
	 * @throws Exception
	 */
	public static PublicKey getPublicKey(String publicKey) throws Exception {
		byte[] keyBytes = Base64.getDecoder().decode(publicKey.getBytes(CHARSET));
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePublic(keySpec);
	}

	/**
	 * 获取私钥
	 * @Description 将base64编码后的私钥字符串转成PrivateKey实例
	 * @param privateKey
	 * @return obj
	 * @throws Exception
	 */
	public static PrivateKey getPrivateKey(String privateKey) throws Exception {
		byte[] keyBytes = Base64.getDecoder().decode(privateKey.getBytes(CHARSET));
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		return keyFactory.generatePrivate(keySpec);
	}

	/**
	 * 公钥加密 (默认1024)
	 * @param content 加密内容原文
	 * @param publicKey 加密使用的公钥
	 * @return String
	 * @throws Exception
	 */
	public static String encrypt(String content, String publicKey) throws Exception {
		return encrypt(content, publicKey, 1024);
	}

	/**
	 * 公钥加密
	 * @param content 加密内容原文
	 * @param publicKey 加密使用的公钥
	 * @param keySize 加密使用的公钥长度
	 * @return String
	 * @throws Exception
	 */
	public static String encrypt(String content, String publicKey, int keySize) throws Exception {
		byte[] contentByte = content.getBytes(CHARSET);
		PublicKey pubKey = NbankRSAUtil.getPublicKey(publicKey);
		byte[] resultByte = NbankRSAUtil.encrypt(contentByte, pubKey, keySize);
		String resultStr = Base64.getEncoder().encodeToString(resultByte);
		return resultStr;
	}

	/**
	 * 公钥加密
	 * @param content 加密原文
	 * @param publicKey 加密使用的公钥
	 * @param keySize 加密使用的公钥长度
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] content, PublicKey publicKey, int keySize) throws Exception {
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int inputLen = content.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		int maxEncryptBlock = keySize/8-11; // 单次最大加密长度
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > maxEncryptBlock) {
				cache = cipher.doFinal(content, offSet, maxEncryptBlock);
			} else {
				cache = cipher.doFinal(content, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * maxEncryptBlock;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	/**
	 * 私钥解密 (默认1024)
	 * @Description 私钥解密
	 * @param content 解密内容
	 * @param privateKey 解密私钥
	 * @return String
	 * @throws Exception
	 */
	public static String decrypt(String content, String privateKey) throws Exception {
		return decrypt(content, privateKey, 1024);
	}

	/**
	 * 私钥解密
	 * @Description 私钥解密
	 * @param content 解密内容
	 * @param privateKey 解密私钥
	 * @param keySize 加密使用的私钥长度
	 * @return String
	 * @throws Exception
	 */
	public static String decrypt(String content, String privateKey, int keySize) throws Exception {
		PrivateKey priKey = getPrivateKey(privateKey); // 获取私钥
		byte[] encryptByte = Base64.getDecoder().decode(content);
		byte[] rawByte = NbankRSAUtil.decrypt(encryptByte, priKey, keySize);
		return new String(rawByte);
	}

	/**
	 * 私钥解密
	 * @Description 私钥解密
	 * @param content 需要解密的密文
	 * @param privateKey 解密使用的私钥
	 * @param keySize 加密使用的私钥长度
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] content, PrivateKey privateKey, int keySize) throws Exception {
		Cipher cipher = Cipher.getInstance("RSA");
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		int inputLen = content.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		int maxDecryptBlock = keySize/8; // 单次最大解密长度
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > maxDecryptBlock) {
				cache = cipher.doFinal(content, offSet, maxDecryptBlock);
			} else {
				cache = cipher.doFinal(content, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * maxDecryptBlock;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}

	/**
	 * 私钥加签
	 * @param content 原文
	 * @param privateKey 私钥
	 * @return 签名值
	 */
	public static String signByPrivateKey(String content, String privateKey) {
		try {
			PrivateKey priKey = NbankRSAUtil.getPrivateKey(privateKey);
			Signature signature = Signature.getInstance("SHA256withRSA");// MD5withRSA
			signature.initSign(priKey);
			signature.update(content.getBytes(CHARSET));
			byte[] sign = signature.sign();
			String signStr = Base64.getEncoder().encodeToString(sign);
			return signStr;
		} catch (Exception e) {
			logger.error("签名失败:", e);
		}
		return null;
	}

	/**
	 * 公钥验签
	 * @param content 原文
	 * @param publicKey 公钥
	 * @param sign 签名
	 * @return 验签是否通过
	 */
	public static boolean verifySignByPublicKey(String content, String publicKey, String sign) {
		try {
			PublicKey pubKey = NbankRSAUtil.getPublicKey(publicKey);
			Signature signature = Signature.getInstance("SHA256withRSA");// MD5withRSA
			signature.initVerify(pubKey);
			signature.update(content.getBytes(CHARSET));
			return signature.verify(Base64.getDecoder().decode(sign));
		} catch (Exception e) {
			log.warn("验签失败:content:【{}】,sign:【{}】", content, sign, e);
		}
		return false;
	}

	public static void main(String[] args) throws Exception {

		Map<String, String> map = generateKey();
		String publicKey = map.get("publicKey");
		String privateKey = map.get("privateKey");

        // 要加密的json数据
		JSONObject params = new JSONObject();
		params.put("mobile", "19118653304");
		String content = params.toJSONString();

        // 数据加解密
		String encryptContent = encrypt(content, publicKey);
		System.out.println("加密后:"+encryptContent);
		String decryptContent = decrypt(encryptContent, privateKey);
		System.out.println("解密后:"+decryptContent);
		
        // 加签验签
//		String singContent = signByPrivateKey(content, privateKey);
//		System.out.println("加签后:" + singContent);
//		System.out.println("验签结果:"+verifySignByPublicKey(content, publicKey, singContent));
	}
}