JS前端加密、JAVA后端解密详解

最近有一个加解密的需求,其实没有什么难度,但是实践过程中踩了很多坑,把踩坑过程分享出来。
1、前端JS加密

aesMinEncrypt: function(key, iv, word){
    var _word = CryptoJS.enc.Utf8.parse(word),
        _key = CryptoJS.enc.Utf8.parse(key),
		_iv = CryptoJS.enc.Utf8.parse(iv);
    var encrypted = CryptoJS.AES.encrypt(_word, _key, {
				iv: _iv,
                mode: CryptoJS.mode.CBC,
                padding: CryptoJS.pad.Pkcs7
        });
    return encrypted.toString();
}

key:十六位作为密钥(前后端必须一致)
iv:十六位作为密钥偏移量(前后端必须一致)
算法:AES/CBC/PKCS7Padding
注意点:JAVA本身不支持PKCS7,只支持PKCS5,但是通过实验,两者即使不一样,也可以进行解密

2、后端JAVA解密

话不多说,上代码

package com.ihaier;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;

public class jiemi {
	
	//密钥 (需要前端和后端保持一致)十六位作为密钥
	private static final String KEY = "ihaierForTodoKey";

	//密钥偏移量 (需要前端和后端保持一致)十六位作为密钥偏移量
	private static final String IV = "ihaierForTodo_Iv";
	
	//算法
	private static final String ALGORITHMSTR = "AES/CBC/PKCS5Padding";
	
	//SSO的TOKEN
	private static final String token = "4AaWABnPB5/1Z2EIEXwSfigudpiM4kzLkmIrKQPmS9w=";
	/** 
	 * base 64 decode 
	 * @param base64Code 待解码的base 64 code 
	 * @return 解码后的byte[] 
	 * @throws Exception 
	 */
	public static byte[] base64Decode(String base64Code) throws Exception{
		return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
	}
	
	/** 
	 * AES解密 
	 * @param encryptBytes 待解密的byte[] 
	 * @return 解密后的String 
	 * @throws Exception 
	 */  
	public static String aesDecryptByBytes(byte[] encryptBytes) throws Exception {

		Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
		
		byte[] temp = IV.getBytes("UTF-8");
		IvParameterSpec iv = new IvParameterSpec(temp);
		
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY.getBytes(), "AES"), iv);
		byte[] decryptBytes = cipher.doFinal(encryptBytes);
		
		System.out.print(new String(decryptBytes));
		return new String(decryptBytes);
	}

	/** 
	 * 将base 64 code AES解密 
	 * @param encryptStr 待解密的base 64 code
	 * @return 解密后的string
	 * @throws Exception
	 */ 
	public static String aesDecrypt(String encryptStr) throws Exception {  
		return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr));  
	}

	public static void main(String[] args) throws Exception {
		aesDecrypt(token);
	}
}

密钥和密钥便宜量必须和前端一致
算法可以采用PKCS5(JAVA本身不支持PKCS7),如果想使用PKCS7,需要额外引入jar包。

  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值