CryptUtil

本文介绍了一个基于Java的AES加密和解密工具类,提供了加密和解密字符串的方法,使用AES算法进行数据保护。文章详细展示了如何生成密钥、进行加密和解密操作,并提供了完整的代码示例。

package com.pajk.synhisdgszyy.utils;

import javax.crypto.*; import javax.crypto.spec.SecretKeySpec; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom;

public class CryptUtil { /** * 加密 * * @param content * 需要加密的内容 * @param keyStr * 加密密钥 * * @return 加密后的内容 * @throws UnsupportedEncodingException * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws BadPaddingException * @throws IllegalBlockSizeException */ public static String encrypt(String content, String keyStr) throws Exception { SecretKey secretKey = getKey(keyStr); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

	// 创建密码器
	Cipher cipher = Cipher.getInstance("AES");
	byte[] byteContent = content.getBytes("utf-8");

	// 初始化加密
	cipher.init(Cipher.ENCRYPT_MODE, key);
	byte[] result = cipher.doFinal(byteContent);

	// 返回加密内容
	return parseByte2HexStr(result);
}

/**
 * 解密
 * 
 * @param content
 *            待解密内容
 * @param keyStr
 *            解密密钥
 * @return
 * @throws UnsupportedEncodingException
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 * 
 */
public static String decrypt(String content, String keyStr) throws Exception {
	SecretKey secretKey = getKey(keyStr);
	byte[] enCodeFormat = secretKey.getEncoded();
	SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");

	// 创建密码器
	Cipher cipher = Cipher.getInstance("AES");

	// 初始化解密
	cipher.init(Cipher.DECRYPT_MODE, key);
	byte[] result = cipher.doFinal(parseHexStr2Byte(content));

	// 返回解密内容
	return new String(result, "UTF-8");
}

/**
 * 将二进制转换成16进制
 * 
 * @param buf
 * @return
 */
private static String parseByte2HexStr(byte buf[]) {
	StringBuffer sb = new StringBuffer();
	for (int i = 0; i < buf.length; i++) {
		String hex = Integer.toHexString(buf[i] & 0xFF);
		if (hex.length() == 1) {
			hex = '0' + hex;
		}
		sb.append(hex.toUpperCase());
	}
	return sb.toString();
}

/**
 * 将16进制转换为二进制
 * 
 * @param hexStr
 * @return
 */
private static byte[] parseHexStr2Byte(String hexStr) {
	if (hexStr.length() < 1){
		return null;
	}
	byte[] result = new byte[hexStr.length() / 2];
	for (int i = 0; i < hexStr.length() / 2; i++) {
		int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
		int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
		result[i] = (byte) (high * 16 + low);
	}
	return result;
}

private static SecretKey getKey(String keyStr) {
	try {
		KeyGenerator generator = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(keyStr.getBytes());
		generator.init(128, secureRandom);
		return generator.generateKey();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}

public static void main(String[] args) throws Exception {
	// String key = "dasdsadsad32rwefrewrewrew";
	// String content = "中国平安%#&,平安中国d21321324&^@!^%#&@#@";
	//
	// System.out.println("===========>加密前:" + content);
	//
	// String c1 = encrypt(content, key);
	// System.out.println("===========>加密后:" + c1);
	//
	// String c2 = decrypt(c1, key);
	// System.out.println("===========>解密后:" + c2);
	System.out.println(encrypt("123123123", "123123123"));
}
复制代码

}

转载于:https://juejin.im/post/5cd51ba551882578f93410cd

你是是不是看不懂人话,我说的是你给的“/** * 验证企业微信服务器地址 */ @RequestMapping(value = "/toWx", method = RequestMethod.GET, produces = "text/plain;charset=utf-8") public String authGet( @RequestParam(name = "msg_signature") String signature, @RequestParam(name = "timestamp") String timestamp, @RequestParam(name = "nonce") String nonce, @RequestParam(name = "echostr") String echostr) { logger.info("收到验证请求:signature={}, timestamp={}, nonce={}, echostr={}", signature, timestamp, nonce, echostr); try { // 1. 获取配置并检查关键参数 WxCpConfigStorage config = wxCpService.getWxCpConfigStorage(); if (StringUtils.isAnyBlank(config.getToken(), config.getAesKey(), config.getCorpId())) { logger.error("企业微信配置不完整,请检查Token/AESKey/CorpId"); return "非法请求"; } // 2. 创建解密工具类 WxCpCryptUtil cryptUtil = new WxCpCryptUtil(config); // 3. 解密(SDK内部自动验证签名) String plainText = cryptUtil.decrypt(signature, timestamp, nonce, echostr); logger.info("验证成功,明文echostr: {}", plainText); return plainText; } catch (Exception e) { logger.error("验证失败,错误详情:", e); // 打印完整堆栈信息 return "非法请求"; } }”这个代码再执行的时候报错了,在“String plainText = cryptUtil.decrypt(signature, timestamp, nonce, echostr);”报“验证失败,错误详情: me.chanjar.weixin.common.error.WxRuntimeException: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; 前言中不允许有内容。”
04-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值