MD5加密不可逆
手机号码,密码等用AES加密
public class AESUtil {
/**
* 默认的密匙(服务端接口失败时使用)
*/
public static final String SECRETKEY = "c98be79a4347bc97";
/**
* 偏移量
*/
private static final String IV = "93x0ue23c2c9h8km";
/**
* AES加密
*
* @param data 要加密的数据
* @param key 加密所使用的密钥
* @return 加密后的数据
* @throws GeneralSecurityException
*/
public static byte[] encrypt(byte[] data, byte[] key) throws GeneralSecurityException {
//根据给定的enCodeFormat字节数组构造一个用AES算法加密的密钥。
SecretKey secretKey = new SecretKeySpec(key, "AES");
// 创建密码器
Cipher cipher = Cipher.getInstance("AES");
// 以加密的方式用密钥初始化此 Cipher
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
//按byteContent单部分操作加密指定的byte, 返回加密过后的byteContent
return cipher.doFinal(data);
}
public static String encrypt(byte[] data, String key) throws GeneralSecurityException {
SecretKey secretKey = new SecretKeySpec(hexStringToBytes(key), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(data);
//返回加密后的字符串
return fromBytesToHex(bytes);
}
public static String encrypt(String content, String key) throws Exception{
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
// "算法/模式/填充"
Cipher cipher = Cipher.getInstance("AES/CBC/Pkcs5Padding");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encrypted = cipher.doFinal(content.getBytes("UTF-8"));
String encode = Base64.encodeToString(encrypted, Base64.NO_WRAP);
return encode;
}
public static String decrypt(String content, String key) throws Exception {
SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(), "AES");
// "算法/模式/填充"
Cipher cipher = Cipher.getInstance("AES/CBC/Pkcs5Padding");
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
byte[] encrypted = cipher.doFinal(Base64.decode(content, Base64.DEFAULT));
return new String(encrypted);
}
private static String fromBytesToHex(byte[] resultBytes) {
StringBuilder builder = new StringBuilder();
for (byte resultByte : resultBytes) {
if (Integer.toHexString(0xFF & resultByte).length() == 1) {
builder.append(0).append(Integer.toHexString(0xFF & resultByte));
} else {
builder.append(Integer.toHexString(0xFF & resultByte));
}
}
return builder.toString();
}
private static byte[] hexStringToBytes(String str) {
if (StringUtils.isNullOrEmpty(str)) {
return new byte[0];
}
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
}
return bytes;
}
}
网友评论