
服務暴露給未登錄移動端,需保證:
排除不可逆加密(MD5/SHA),同系統加解密無需非對稱。選擇 DES(JDK JCE 實現),可換 AES 等。工具類核心:
public class EncryptionDecryption {
private static final String DEFAULT_KEY = "helloDecrypt";
private Cipher encryptCipher, decryptCipher;
public EncryptionDecryption(String key) throws Exception {
Security.addProvider(new com.sun.crypto.provider.SunJCE());
Key k = new SecretKeySpec(padKey(key), "DES");
encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, k);
decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, k);
}
public String encrypt(String str) { return byteArr2HexStr(encryptCipher.doFinal(str.getBytes())); }
public String decrypt(String hex) { return new String(decryptCipher.doFinal(hexStr2ByteArr(hex))); }
// 輔助方法:byte[]↔HexString、Key 填充略
}
加密時拼接 param1,param2,yyyyMMddHHmm(分鐘級粒度,可調秒/毫秒)。解密後驗證:
private Boolean hasInvalidRequest(String encrypted) {
String[] parts = new EncryptionDecryption(PUBLIC_KEY).decrypt(encrypted).split(",");
String ts = parts[2]; // yyyyMMddHHmm
if (ts.length() != 12) return true;
int nowDay = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
int reqDay = Integer.parseInt(ts.substring(0, 8));
if (nowDay > reqDay) return true;
int nowMin = Integer.parseInt(new SimpleDateFormat("HHmm").format(new Date()));
int reqMin = Integer.parseInt(ts.substring(8));
return (nowMin - reqMin) > ConfigUtil.getInt("valid_request_minutes");
}
有效期放配置文件,靈活調整。
