安卓Retrofit AES加密/解密POST请求和响应

11

我正在使用Retrofit 2.0

我想加密@body的例子,即User对象

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

然后解密响应。

最好的方法是什么?

1个回答

8

使用拦截器来加密请求体。

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 添加到 Retrofit 中:

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

关于拦截器的更多信息:https://github.com/square/okhttp/wiki/Interceptors


1
CodeMachine.encrypt(strOldBody) CodeMachine是什么? - Muhammad Haroon
@MuhammadHaroon 可能是答案提供者项目中的残留物。我已经修复了代码,使用类的 encrypt() 方法代替了它。 - Andrew T.
@AndrewT. 先生,请问您能告诉我如何在Android中使用Retrofit获取加密的AES响应吗? - Mohammad Zeeshan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接