实名认证中AES128加密/解密
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESUtil {
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();
}
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;
}
public static String Encrypt(String msg, String password) {
try {
byte[] sSrc = msg.getBytes("UTF-8");
byte[] sKey = AESUtil.parseHexStr2Byte(password);
SecretKeySpec skeySpec = new SecretKeySpec(sKey, "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] iv = cipher.getIV();
byte[] encryptData = cipher.doFinal(sSrc);
byte[] message = new byte[12 + sSrc.length + 16];
System.arraycopy(iv, 0, message, 0, 12);
System.arraycopy(encryptData, 0, message, 12, encryptData.length);
return Base64.getEncoder().encodeToString(message);
} catch (Exception ex) {
return null;
}
}
public static String Decrypt(String serect, String password) {
try {
byte[] sSrc = Base64.getDecoder().decode(serect);
byte[] sKey = AESUtil.parseHexStr2Byte(password);
GCMParameterSpec iv = new GCMParameterSpec(128, sSrc, 0, 12);
Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
SecretKey key2 = new SecretKeySpec(sKey, "AES");
cipher.init(Cipher.DECRYPT_MODE, key2, iv);
byte[] decryptData = cipher.doFinal(sSrc, 12, sSrc.length - 12);
return new String(decryptData);
} catch (Exception ex) {
return null;
}
}
}