Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle decryption of JSON payload

I have a JSON payload being returned from a server but its encrypted.

Lets say the retrofit call looks like this:

@GET("/user/{id}/userprofile")  
void listUserProfile(@Path("id") int id, Callback<UserProfile> cb);  

So how can i tell retrofit to first decrypt the payload and then afterwards use gson to convert the json to POJO (in this case UserProfile object) ? i am using okHttp for http client.

like image 995
j2emanue Avatar asked Sep 18 '15 16:09

j2emanue


1 Answers

Probably writing an application Interceptor for your OkHttp client that will decrypt the body will do the trick:

public class DecryptedPayloadInterceptor implements Interceptor {

    private final DecryptionStrategy mDecryptionStrategy;

    public interface DecryptionStrategy {
        String decrypt(InputStream stream);
    }

    public DecryptedPayloadInterceptor(DecryptionStrategy mDecryptionStrategy) {
        this.mDecryptionStrategy = mDecryptionStrategy;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        if (response.isSuccessful()) {
            Response.Builder newResponse = response.newBuilder();
            String contentType = response.header("Content-Type");
            if (TextUtils.isEmpty(contentType)) contentType = "application/json";
            InputStream cryptedStream = response.body().byteStream();
            String decrypted = null;
            if (mDecryptionStrategy != null) {
                decrypted = mDecryptionStrategy.decrypt(cryptedStream);
            } else {
                throw new IllegalArgumentException("No decryption strategy!");
            }
            newResponse.body(ResponseBody.create(MediaType.parse(contentType), decrypted));
            return newResponse.build();
        }
        return response;
    }
}

If you are not using OkHttp, I'll gracefully remove the answer.

like image 59
Nikola Despotoski Avatar answered Oct 14 '22 13:10

Nikola Despotoski