对称加密-AES算法

AES即高级加密算法标准,AES算法作为新一代的数据加密标准,汇聚了安全性、高性能、高效率、易用和灵活等优点,设计有三个密钥长度(128、192、256位),比DES算法加密强度更高,更为安全。

import java.security.NoSuchAlgorithmException;

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

/**
 * 对称加密-aes
 * @author a
 *
 */
public class AESUtil {
	public static void main(String[] args) throws Exception {
		//910ffbf5c2b76bbf5ced93ba566f62a2
		SecretKey loadKeyAES = loadKeyAES("910ffbf5c2b76bbf5ced93ba566f62a2");
		byte[] encryptAES = encryptAES("123456".getBytes("utf8"), loadKeyAES);//加密后字符串:9f0457b479b630c2b9c4c4babcf314ec
		decryptAES(Byte2hex.hex2bytes("7db15434175d9abe2c4ee8cf431dfa6f"),loadKeyAES);//十六进制字符串转为二进制
		decryptAES(encryptAES,loadKeyAES);
	}
	
	//加密
	public static byte[] encryptAES(byte[] source,SecretKey key) throws Exception{
		Cipher cipher=Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, key);
		byte[] doFinal = cipher.doFinal(source);
		String encryptstr = Byte2hex.bytes2hex(doFinal);
		System.out.println("加密后字符串:"+encryptstr);
		return doFinal;
	}
	//解密密
		public static void decryptAES(byte[] source,SecretKey key) throws Exception{
			Cipher cipher=Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			byte[] doFinal = cipher.doFinal(source);
		
			System.out.println("解密后字符串:"+new String(doFinal, "utf8"));//二进制转为字符串
		}
	
	//生成AES密钥
	public static String genKeyAES() throws Exception{
		KeyGenerator keyGen=KeyGenerator.getInstance("AES");
		keyGen.init(128);
		SecretKey key = keyGen.generateKey();
		String base64str = Byte2hex.bytes2hex(key.getEncoded());
		System.out.println("生成密钥:"+base64str);
		return base64str;
	}
    //将密钥生成key
	public static SecretKey loadKeyAES(String Base64Str) throws Exception{
		byte[] bytes = Byte2hex.hex2bytes(Base64Str);
		SecretKey key=new  SecretKeySpec(bytes, "AES");
		return key;
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值