java的加密和解密
程序员文章站
2022-03-12 22:25:54
...
package com.ysdq.cms.util;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
/**
* 加密
* @author sutong
* @date 2018-06-26 11:34:00
*/
public class AESUtil {
private static final String KEY = "#VmGRi";
private static final Key KEY_SPEC = new SecretKeySpec(KEY.getBytes(), "AES");
/**
* 加密
* @param str
* @return
*/
public static String encryt(String str) {
// 根据**,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
try {
Cipher c = Cipher.getInstance("AES");
c.init(Cipher.ENCRYPT_MODE, KEY_SPEC);
byte[] src = str.getBytes();
// 加密,结果保存进cipherByte
byte[] cipherByte = c.doFinal(src);
return Base64.encodeBase64String(cipherByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 解密
* @param deCodeStr
* @return
*/
public static String decrypt(String deCodeStr) {
// 根据**,对Cipher对象进行初始化,DECRYPT_MODE表示解密模式
try {
if (null == deCodeStr){
return null;
}
byte[] buff = Base64.decodeBase64(deCodeStr);
Cipher c;
c = Cipher.getInstance("AES");
c.init(Cipher.DECRYPT_MODE, KEY_SPEC);
byte[] cipherByte = c.doFinal(buff);
return new String(cipherByte);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}