Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Retrofit AES encrypt/decrypt POST and Response

I am using Retrofit 2.0

I want to encrypt my @body example the User Object

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

and then decrypt the response .

what is the best way to do it ?

like image 244
user987760 Avatar asked Mar 31 '16 07:03

user987760


1 Answers

Use Interceptors to encrypt the body.

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
    }
}

Then add the Interceptor to the Retrofit:

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

More about Interceptors: https://github.com/square/okhttp/wiki/Interceptors

like image 172
Paparika Avatar answered Sep 23 '22 08:09

Paparika