【问题标题】:Android Retrofit AES encrypt/decrypt POST and ResponseAndroid Retrofit AES 加密/解密 POST 和响应
【发布时间】:2016-03-31 07:59:37
【问题描述】:

我正在使用 Retrofit 2.0

我想加密我的@body 示例用户对象

@POST("users/new")
Call<User> createUser(@Body User newUser);

然后解密响应。

最好的方法是什么?

【问题讨论】:

    标签: android encryption aes retrofit retrofit2


    【解决方案1】:

    使用Interceptors 加密正文。

    public class EncryptionInterceptor implements Interceptor {
    
        private static final String TAG = EncryptionInterceptor.class.getSimpleName();
        private static final boolean DEBUG = true;
    
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            RequestBody oldBody = request.body();
            Buffer buffer = new Buffer();
            oldBody.writeTo(buffer);
            String strOldBody = buffer.readUtf8();
    
            MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
            String strNewBody = encrypt(strOldBody);
            RequestBody body = RequestBody.create(mediaType, strNewBody);
            request = request.newBuilder().header("Content-Type", body.contentType().toString()).header("Content-Length", String.valueOf(body.contentLength())).method(request.method(), body).build();
    
            return chain.proceed(request);
        }
    
        private static String encrypt(String text) {
            //your code
        }
    }
    

    然后将Interceptor 添加到改造中:

    client = new OkHttpClient.Builder().addNetworkInterceptor(new EncryptionInterceptor()).build();
    retrofit = new Retrofit.Builder().client(client).build();
    

    更多关于Interceptors:https://github.com/square/okhttp/wiki/Interceptors

    【讨论】:

    • CodeMachine.encrypt(strOldBody) 什么是 CodeMachine?
    • @MuhammadHaroon 可能是回答者项目的残余。我已将代码修复为使用类的 encrypt() 方法。
    • @AndrewT。先生,您能告诉我如何使用改造在 android 中获得加密的 AES 响应。
    猜你喜欢
    • 1970-01-01
    • 2016-09-22
    • 2015-01-20
    • 2014-01-05
    • 2019-01-06
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多