使用CryptoJS中的AES实现加解密

最近为了解决项目中用户名、密码明文传输的问题,使用了AES在前台加密,然后在后台解密,稍微整理了一下,记录AES前台加解密和后台java加解密,以防忘记。

前台使用CryptoJS实现AES加解密的,所以要先下载组件,下载CryptoJS-v3.1.2版本之后,文件中包含components和rollups两个文件夹,components文件夹下是单个组件,rollups文件夹下是汇总,引用rollups下的aes.js文件即可。

下载地址:CryptoJS-v3.1.2

前台加解密:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>



AES加解密





	

加密后的数据:

解密后的数据:

后台加解密:

package com.yanzhengma.servlet;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class AESTest {

	public static void main(String args[]) throws Exception{
		String content = "test";
		String key = "abcdefghijklmn12";
		String iv = "abcdefghijklmn12";
		//加密
		byte[] encrypted = AES_CBC_Encrypt(content.getBytes(), key.getBytes(), iv.getBytes()); 
		//解密
		byte[] decrypted = AES_CBC_Decrypt(decryptBASE64("加密后的密文"), key.getBytes(), iv.getBytes());
		
		System.out.println("加密后:"+encryptBASE64(encrypted));
		System.out.println("解密后:"+byteToString(decrypted));
	}
	
	public static String byteToString(byte[] byte1){  
        return new String(byte1);  
    }
	
	public static byte[] AES_CBC_Encrypt(byte[] content, byte[] keyBytes, byte[] iv){
		try {
			SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE,key, new IvParameterSpec(iv));
			byte[] result = cipher.doFinal(content); 
			return result;
		} catch (Exception e) {
			System.out.println("exception:"+e.toString());
		}
		return null;
	}
	
	public static byte[] AES_CBC_Decrypt(byte[] content, byte[] keyBytes, byte[] iv){
		try {
			SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE,key, new IvParameterSpec(iv)); 
			byte[] result = cipher.doFinal(content);
			return result;
		} catch (Exception e) {
			System.out.println("exception:"+e.toString());
		}
		return null;
	}
	
	//字符串装换成base64
	public static byte[] decryptBASE64(String key) throws Exception {   
        return Base64.decodeBase64(key.getBytes());  
    }
	//base64装换成字符串
	public static String encryptBASE64(byte[] key) throws Exception {   
        return new String(Base64.encodeBase64(key));  
    } 
}


你可能感兴趣的:(JS)