com.loocme.security.encrypt.AesUtil Maven / Gradle / Ivy
package com.loocme.security.encrypt;
import lombok.extern.slf4j.Slf4j;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
* @author liuchi
*/
@Slf4j
public class AesUtil
{
private static final String ENCODING = "utf-8";
private static final int KEYBIT = 128;
/**
* 解密
*/
public static String decryptAngelpay(String message, String password)
{
try
{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(KEYBIT, new SecureRandom(password.getBytes(ENCODING)));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] retByte = cipher.doFinal(message.getBytes(ENCODING));
return new String(retByte, ENCODING);
}
catch (Exception e)
{
log.error("", e);
return null;
}
}
/**
* 加密
*/
public static String encryptAngelpay(String message, String password)
{
try
{
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(KEYBIT, new SecureRandom(password.getBytes(ENCODING)));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
// 初始化
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptbyte = cipher.doFinal(message.getBytes(ENCODING));
return new String(Base64.encode(encryptbyte));
}
catch (Exception e)
{
log.error("", e);
return null;
}
}
public static void main(String[] args)
{
System.out.println(encryptAngelpay("test", "12345678"));
System.out.println(DesUtil.encryptAngelpay("test", "12345678"));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy