AndroidRetrofit参数加密和解密SHA256
创始人
2024-10-09 18:31:38
0
  1. 客户端创建一个请求拦截器,在发送请求之前对参数进行加密处理。
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;
        }
    }
}
  1. 服务器端需要对参数进行解密处理,示例代码如下。
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;
        }
    }
}

使用时,在服务器端接收到请求参数后调用解密算法进行解密即可。

相关内容

热门资讯

热点推荐"手机游戏挂... 热点推荐"手机游戏挂机辅助软件"开挂(神器)辅助神器有挂攻略-可靠教程 >>您好:软件加薇13670...
必备教程"微信卡五星... 您好:这款微信卡五星辅助器游戏是可以开挂的,确实是有挂的,很多玩家在这款微信卡五星辅助器游戏中打牌都...
一分钟揭秘"下载微乐... 一分钟揭秘"下载微乐小程序自建房透视"开挂(神器)辅助神器新版有挂-微扑克教程1、下载安装好下载微乐...
重要通知"衡阳丫丫字... 重要通知"衡阳丫丫字牌靠谱吗"开挂(安装)辅助安装有挂分享-黑科技教程;无需打开直接搜索薇:1367...
传递经验"pokem... 传递经验"pokemmo脚本辅助下载"开挂(平台)辅助平台了解有挂-玩家教程《详细加薇1367043...
推荐十款"掌中乐游戏... 推荐十款"掌中乐游戏辅助器"开挂(下载)辅助下载有挂教程-辅助教程;无需打开直接搜索加薇136704...
透视透视"决战卡五星... 透视透视"决战卡五星看牌器"开挂(下载)辅助下载有挂解惑-透视教程>>您好:软件加薇13670430...
实测必看"传送屋激k... 实测必看"传送屋激k万能辅助器app"开挂(安装)辅助安装有挂总结-AI教程 【无需打开直接搜索加薇...
教程攻略"新圣游脚本... 新圣游脚本下载是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微信...
科技分享"钱塘十水三... 您好:钱塘十水三挂件这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌特...