在开发中,为了安全性考虑,我们常常会用到加密,加密的格式很多,今天我就来简单写写AES、MD5加密。
AES加密:下面是工具类
public class AESUtils {
private static final String KEY = "C366E901E330225EFA581B6376A97F1D";
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* 转换密钥
*
* @param key
* @return
* @throws Exception
*/
public static SecretKeySpec initKey(String key) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(new SecureRandom(key.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec k = new SecretKeySpec(enCodeFormat, "AES");
return k;
}
/**
* 解密
*
* @param data
* @return
* @throws Exception
*/
public static String decrypt(String data) throws Exception {
SecretKeySpec k = initKey(KEY);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, k);
return new String(cipher.doFinal(parseHexStr2Byte(data)));
}
/**
* 加密
*
* @param data
* @return
* @throws Exception
*/
public static String encrypt(String data) throws Exception {
SecretKey k = initKey(KEY);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, k);
return parseByte2HexStr(cipher.doFinal(data.getBytes()));
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String parseByte2HexStr(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();
}
/**
* 将16进制转换为二进制
*
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
}
MD5加密:下面是工具类
public class MD5Utils {
public static final String KEY = "C366E901E330225EFA581B6376A97F1D";
/**
* <p>
* Title: 转32位 MD5
* </p>
* <p>
* Description: TODO(这里用一句话描述这个方法的作用)
* </p>
* <p>
* author: gaobitian
* <p>
* date: 2016年5月6日 下午4:04:34
* </p>
*
* @param inStr
* @return String
*/
public static String MD5(String inStr) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = (inStr+","+KEY).toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
}
里边的key值因人而异
希望能帮助到大家。。。。