public class EncryptionInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
if (requestBody != null) {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
// 将 requestBody 转化为字符串并进行加密
String encryptedString = encrypt(buffer.readUtf8());
// 将加密后的参数放回 requestBody 中
RequestBody encryptedBody = RequestBody.create(requestBody.contentType(), encryptedString);
request = request.newBuilder().method(request.method(), encryptedBody).build();
}
return chain.proceed(request);
}
// 加密算法
private String encrypt(String str) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(str.getBytes("UTF-8"));
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
} catch (Exception e) {
return str;
}
}
}
public class DecryptionUtils {
// 解密算法
public static String decrypt(String encryptedParam) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hash = messageDigest.digest(encryptedParam.getBytes("UTF-8"));
StringBuilder hex = new StringBuilder(hash.length * 2);
for (byte b : hash) {
if ((b & 0xFF) < 0x10) hex.append("0");
hex.append(Integer.toHexString(b & 0xFF));
}
return hex.toString();
} catch (Exception e) {
return encryptedParam;
}
}
}
使用时,在服务器端接收到请求参数后调用解密算法进行解密即可。