import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* @Author mxy
* @Desc 加密\解密工具类
* 密钥(密码)长度只能为16, 24, 32 位长度
* 加密过程: 加密-Base64编码
* 解密过程: Base64解码-解密
*/
public class encryptUtils {
/** 加密模式 */
private static final String TRANS_FORMATION = "AES/ECB/PKCS5Padding";
/** 加密算法 */
private static final String ALGORITHM = "AES";
/** 字符编解码 */
private static final String CHARSET_NAME = "UTF-8";
/**
* MD5加密
*
* @param data
* @return
*/
public static String encryptByMD5(String data) {
String reMd5 = new String();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer();
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
reMd5 = buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return reMd5.toUpperCase();
}
/**
* AES 加密
*
* @param value 原始字符串
* @return base64 编码后的加密字符串
* @throws Exception 编码异常
*/
public static String encryptByAES(String password, String value) throws Exception {
SecretKeySpec aesKey = new SecretKeySpec(password.getBytes(Charset.forName(CHARSET_NAME)), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANS_FORMATION);
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(value.getBytes(Charset.forName(CHARSET_NAME)));
return Base64.getEncoder().encodeToString(encrypted);
}
/**
* AES 解密
*
* @param value base64 编码后的加密字符串
* @return base64 解码后的原始字符串
* @throws Exception 解码异常
*/
public static String decryptByAES(String password, String value) throws Exception {
byte[] decode = Base64.getDecoder().decode(value.getBytes(StandardCharsets.UTF_8));
SecretKeySpec aesKey = new SecretKeySpec(password.getBytes(Charset.forName(CHARSET_NAME)), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANS_FORMATION);
cipher.init(Cipher.DECRYPT_MODE, aesKey);
return new String(cipher.doFinal(decode));
}
}
MD5、AES 算法加密、解密
于 2022-07-12 14:51:54 首次发布