Android、Java在做http請(qǐng)求的時(shí)候,都會(huì)做兩端加密驗(yàn)證,一般都會(huì)使用到AES加密,方法很簡(jiǎn)單!
加密解密需要傳入的秘鑰是你項(xiàng)目中自定義的秘鑰,用于加密。
先導(dǎo)入包
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
文本加密調(diào)用
/**
*文本加密方法
*@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 "";
? ? ? ? ? ? ? ? ?}
}
解密調(diào)用
/**
*文本解密方法
*@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進(jìn)制字符串-->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進(jìn)制字符串
*/
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();
}