博客信息

APP接口数据加密方案

发布时间:『 2016-09-23 17:37』  博客类别:Java  阅读(1940) 评论(0)

1,使用3DES加密解密

/**
* 24位秘钥
**/
private static final int DES_LENGTH = 24;
	/**
	 * Description: 加密
	 * 
	 * @param content
	 * @param desKey
	 * @return
	 */
	public static String encrypt(String content, String desKey) {
		String str = null;
		try {
			if(StringUtil.isEmpty(desKey) || DES_LENGTH != desKey.length()) {
				log.error("3des key's length must be 24");
				return "";
			}
			if(StringUtil.isEmpty(content)) {
				return "";
			}
			SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede");
			Cipher cipher = Cipher.getInstance("DESede");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encryptBytes = cipher.doFinal(content.getBytes("utf-8"));
			str = new BASE64Encoder().encode(encryptBytes);

		}catch (Exception e) {
			log.error("加密失败!", e);
		}
		return str;
	}
	/**
	 * Description: 解密
	 * 
	 * @param content
	 * @param desKey
	 * @return
	 */
	public static String decrypt(String content, String desKey) {
		try {
			if(StringUtil.isEmpty(desKey) || DES_LENGTH != desKey.length()) {
				log.error("3des key's length must be 24");
				return "";
			}
			if(StringUtil.isEmpty(content)) {
				return "";
			}

			byte[] decryptBytes = null;
			decryptBytes = new BASE64Decoder().decodeBuffer(content);
			// decryptBytes = new
			// BASE64Decoder().decodeBuffer(decryptBytes.toString());
			SecretKeySpec key = new SecretKeySpec(desKey.getBytes("utf-8"), "DESede");
			Cipher cipher = Cipher.getInstance("DESede");
			cipher.init(Cipher.DECRYPT_MODE, key);

			return new String(cipher.doFinal(decryptBytes), "utf-8");
		}catch (Exception e) {
			log.error("解密失败!", e);
		}
		return null;
	}

2,使用SHA256对关键信息进行签名

	/**
	 * 
	 * 签名处理
	 * 
	 * @param key
	 * @param content
	 * @param signType
	 * @return
	 */

	public static String sign(String key, String content, String signType) {

		String digestResult = null;
		if(SHA_256_HEX.equalsIgnoreCase(signType)) {
			digestResult = DigestUtils.sha256Hex(key + content);
		}

		return digestResult;
	}

DigestUtils为org.apache.commons.codec.digest包下的工具类。

关键字:   无
评论信息
暂无评论
发表评论
验证码: 
Powered by IMZHANGJIE.CN Copyright © 2015-2025 粤ICP备14056181号