RSA前端加密后端解密避免出现明文密码

时间:2019-11-05
本文章向大家介绍RSA前端加密后端解密避免出现明文密码,主要包括RSA前端加密后端解密避免出现明文密码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

话不多说,直接开撸

public class RSAUtils {
	private static String PUB_KEY = "xxxxxx";
	private static String PRIV_KEY ="xxxxxx";
	public static Map<Integer, String> genKeyPair() {
		Map<Integer, String> keyMap = new HashMap<Integer, String>(); // 用于封装随机产生的公钥与私钥
		try {
			// KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
			KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");

			// 初始化密钥对生成器,密钥大小为96-1024位
			keyPairGen.initialize(1024, new SecureRandom());

			// 生成一个密钥对,保存在keyPair中
			KeyPair keyPair = keyPairGen.generateKeyPair();
			RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 得到私钥
			RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 得到公钥

			// 得到公钥字符串
			String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
			// 得到私钥字符串
			String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
			// 将公钥和私钥保存到Map
			keyMap.put(0, publicKeyString); // 0表示公钥
			keyMap.put(1, privateKeyString); // 1表示私钥
		} catch (Exception e) {
			return null;
		}

		return keyMap;
	}

	/**
	 * RSA公钥加密
	 * 
	 * @param str
	 *            需要加密的字符串
	 * @param publicKey
	 *            公钥
	 * @return 公钥加密后的内容
	 */
	public static String encrypt(String str) {
		String outStr = null;
		try {
			// base64编码的公钥
			byte[] decoded = Base64.decodeBase64(PUB_KEY);
			RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
					.generatePublic(new X509EncodedKeySpec(decoded));
			// RSA加密
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, pubKey);
			outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
		} catch (Exception e) {
		}
		return outStr;
	}

	/**
	 * RSA私钥解密
	 * 
	 * @param str
	 *            加密字符串
	 * @param privateKey
	 *            私钥
	 * @return 私钥解密后的内容
	 */
	public static String decrypt(String str) {
		String outStr = null;
		try {
			// 64位解码加密后的字符串
			byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
			// base64编码的私钥
			byte[] decoded = Base64.decodeBase64(PRIV_KEY);
			RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
					.generatePrivate(new PKCS8EncodedKeySpec(decoded));
			// RSA解密
			Cipher cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.DECRYPT_MODE, priKey);
			outStr = new String(cipher.doFinal(inputByte));
		} catch (Exception e) {
		}
		return outStr;
	}

}

这个类有一个生成公钥和私钥的方法,还有一个公钥加密和私钥解密的方法.我们将公钥放在前端用来加密,私钥放在后端用来解密.

前端需要引入jsencrypt.min.js

下载地址:  http://travistidwell.com/jsencrypt/

加密方法:

就可以实现前端加密后端解密了

原文地址:https://www.cnblogs.com/wnhbx/p/11797906.html