Android、Java在做http请求的时候,都会做两端加密验证,一般都会使用到AES加密,方法很简单!
加密解密需要传入的秘钥是你项目中自定义的秘钥,用于加密。
先导入包
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
文本加密调用
/**
*文本加密方法
*@paramkeykey(密匙)
*/
public static String encryptionText(@NonNull String text, @NonNull String key) {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec =newSecretKeySpec(raw,"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[] encrypted = cipher.doFinal(text.getBytes());
returnbyte2hex(encrypted).toLowerCase();
} catch(Exception e) {
e.printStackTrace();
return "";
}
}
解密调用
/**
*文本解密方法
*@paramtext需要解密字符串
*@paramkeykey(密匙)
*/
public static String decryptText(@NonNull String text, @NonNull String key) {
try {
byte[] raw = key.getBytes("ASCII");
SecretKeySpec skeySpec =newSecretKeySpec(raw,"AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
byte[] encrypted1 =hex2byte(text);
try {
byte[] original = cipher.doFinal(encrypted1);
String originalString =newString(original);
returnoriginalString;
} catch (Exception e) {
e.printStackTrace();
return"";
}
} catch (Exception ex) {
ex.printStackTrace();
return"";
}
}
/**
* 16進制字符串-->byte[]
*/
public static byte[] hex2byte(@NonNull String strhex) {
int l = strhex.length();
if (l % 2 == 1 ) {
return null;
}
byte[] b = new byte[l /2];
for (int i = 0 ; i != l /2 ; i++) {
b[i] = (byte) Integer.parseInt(strhex.substring(i *2, i *2+2), 16);
}
returnb;
}
/**
* byte[]-->16進制字符串
*/
public static String byte2hex(@NonNull byte[] b) {
String hs ="";
String stmp ="";
for (int n = 0 ; n < b.length ; n++) {
stmp = (Integer.toHexString(b[n] &0XFF));
if(stmp.length() ==1) {
hs = hs +"0"+ stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}