AES对称加密算法

加密解密,秘钥相同。


加密后得到的字节数组,不可以直接转成字符串,因为使用字符串转回字节数组的时候,字节数组发生变化。可以把字节数组使用算法转成十六进制字符串,解密时候先把十六进制字符串转成字节数组。

package codeUtil;

import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESCodeUtil {
	public static byte[] aesEncode(String msg,String password){
		byte[] res=null;
		try {
			KeyGenerator instance = KeyGenerator.getInstance("AES");
			instance.init(128, new SecureRandom(password.getBytes("utf-8")));
			SecretKey secrKey = instance.generateKey();
			byte[] encodFormat = secrKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(encodFormat, "AES");
			
			Cipher instance2 = Cipher.getInstance("AES");
			instance2.init(Cipher.ENCRYPT_MODE, key);
			res=instance2.doFinal(msg.getBytes("utf-8"));
		} catch (Exception e) {
			System.out.println("encode error");
		}
		return res;
	}
	
	public static byte[] aesDecode(byte[] msg,String password){
		byte[] res=null;
		try {
			KeyGenerator instance = KeyGenerator.getInstance("AES");
			instance.init(128, new SecureRandom(password.getBytes("utf-8")));
			SecretKey generateKey = instance.generateKey();
			byte[] encodedFormat = generateKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(encodedFormat, "AES");
			
			Cipher cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			res=cipher.doFinal(msg);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return res;
	}
	
	public static String byteToHexStr(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();
	}
	
	public static byte[] hexStrToBytes(String str){
		if(str.length()<1){
			return null;
		}
		byte[] res=new byte[str.length()/2];
		for(int i=0;i<res.length;i++){
			int high=Integer.parseInt(str.substring(i*2, i*2+1),16);
			int low=Integer.parseInt(str.substring(i*2+1, i*2+2),16);
			res[i]=(byte)(high*16+low);
		}
		return res;
	}
	
	public static void main(String[] args) throws UnsupportedEncodingException {
		String password="123";
		byte[] msg = aesEncode("abc", password);
		String str = byteToHexStr(msg);
		System.out.println(str);
		byte[] res=hexStrToBytes(str);
		byte[] aesDecode = aesDecode(res, password);
		System.out.println(new String(aesDecode,"utf-8"));
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值