Skip to main content

CryptUtil.java

CryptUtil.java

CryptUtil.java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class CryptUtil {

private static String toHex(byte[] bytes) {
StringBuilder buffer = new StringBuilder(bytes.length * 2);
String str;
for (Byte b : bytes) {
str = Integer.toHexString(b);
int len = str.length();
if (len == 8) {
buffer.append(str.substring(6));
} else if (len == 2) {
buffer.append(str);
} else {
buffer.append("0").append(str);
}
}
return buffer.toString();
}

private static byte[] fromHex(String text) {
byte[] arr = new byte[text.length() / 2];
for (int i = 0; i < text.length(); i += 2) {
arr[i / 2] = (byte) Integer.parseInt(text.substring(i, i + 2), 16);
}
return arr;
}

public static String encrypt(String text, String key) {
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return toHex(cipher.doFinal(text.getBytes()));
} catch (Exception e) {
return null;
}
}

public static String decrypt(String text, String key) {
try {
Cipher cipher = Cipher.getInstance("AES");
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
return new String(cipher.doFinal(fromHex(text)));
} catch (Exception e) {
return null;
}
}
}