Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.util.Log;
import java.nio.charset.Charset;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class EncryptDecryptConverterFactory extends Converter.Factory {
private GsonConverterFactory factory;
public EncryptDecryptConverterFactory(GsonConverterFactory factory) {
this.factory = factory;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(final Type type, Annotation[] annotations, Retrofit retrofit) {
Converter<ResponseBody, ?> delegate = factory.responseBodyConverter(type, annotations, retrofit);
return new DecryptConverter<>(delegate, type);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
Converter<?, RequestBody> delegate = factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
return new EncryptConverter<>(delegate, type);
}
final static class DecryptConverter<T> implements Converter<ResponseBody, T> {
final Converter<ResponseBody, T> delegate;
final Type type;
public DecryptConverter(Converter<ResponseBody, T> delegate, Type type) {
this.delegate = delegate;
this.type = type;
}
@Override
public T convert(ResponseBody responseBody) throws IOException {
String input = responseBody.string();
Log.e("Converter", "@Decrypt input: " + input);
// for example it is from server
// String encryptedText = AES.getInstance().doEncrypt(input);
// Log.e("Converter", "Ex: Server Response in encrypted form: " + encryptedText);
// decrypt encrypted text
String decryptedText = AES.getInstance().doDecrypt(input);
Log.e("Converter", "Ex: Server Response in decrypted form: " + decryptedText);
return new Gson().fromJson(decryptedText, type);
//return delegate.convert(responseBody);
}
}
final static class EncryptConverter<T> implements Converter<T, RequestBody> {
final Converter<T, RequestBody> delegate;
final Type type;
public EncryptConverter(Converter<T, RequestBody> delegate, Type type) {
this.delegate = delegate;
this.type = type;
}
@Override
public RequestBody convert(T value) throws IOException {
String input = new Gson().toJson(value, type);
Log.e("Converter", "#Encrypt input: " + input);
// for example it is from server
String encryptedText = AES.getInstance().doEncrypt(input);
Log.e("Converter", "Ex: Server Request in encrypted form: " + encryptedText);
// decrypt encrypted text
// String decryptedText = AES.getInstance().doDecrypt(encryptedText);
// Log.e("Converter", "Ex: Server Request in decrypted form: " + decryptedText);
//return delegate.convert(value);
return RequestBody.create(okhttp3.MediaType.parse("text/plain"), encryptedText);
}
}
}
public class AES {
private final static String HEX = "0123456789abcdef";
private static final String TAG = AES.class.getSimpleName();
private static AES instance;
private final String AES = "AES";
private final String CIPHER_TRANSFORM = "AES/CBC/ZeroBytePadding";
private final Charset CHARSET = Charset.forName("UTF-8");
private String KEY = "fghLwXyUrYkL09He";
private String IV = "io83JJ5nHjKKgHtR";
public AES() {
}
/**
* get instance of AES
*
* @return
*/
public static AES getInstance() {
if (instance == null) {
instance = new AES();
}
return instance;
}
/**
* Encrypt normal text to cipher form
*
* @param input
* @return Normal text from Encrypted text
*/
public String doEncrypt(String input) {
String result = "";
if (input == null || input.equals("")) {
return result;
}
try {
byte[] keyByte = KEY.getBytes(CHARSET);
byte[] ivByte = IV.getBytes(CHARSET);
byte[] inputByte = input.getBytes(CHARSET);
SecretKeySpec key = new SecretKeySpec(keyByte, AES);
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(ivByte));
byte[] rawEnc = cipher.doFinal(inputByte);
result = toHex(rawEnc);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* print byte array value
*
* @param data
*/
private void printByte(byte[] data) {
StringBuffer strByte = new StringBuffer();
StringBuffer strNoByte = new StringBuffer();
for (int i = 0; i < data.length; i++) {
strByte.append((char) data[i] + "|");
strNoByte.append(data[i] + "|");
}
Log.e(TAG, "strByte: " + strByte.toString());
Log.e(TAG, "strNoByte: " + strNoByte.toString());
}
public int doDecrypt(int input) {
int result = 0;
try {
result = Integer.parseInt(doDecrypt(input + ""));
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* Decrypt Encrypted text
*
* @param input
* @return Normal text from Encrypted text
*/
public String doDecrypt(String input) {
String result = "";
if (input == null || input.equals("")) {
return result;
}
try {
byte[] keyByte = KEY.getBytes(CHARSET);
byte[] ivByte = IV.getBytes(CHARSET);
byte[] inputByte = toByte(input);
SecretKeySpec key = new SecretKeySpec(keyByte, AES);
Cipher cipher = Cipher.getInstance(CIPHER_TRANSFORM);
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivByte));
byte[] rawDec = cipher.doFinal(inputByte);
result = new String(rawDec);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* from hex string to byte array
*
* @param hexString string encoded in hex
* @return return byte array
* @throws Exception
*/
private byte[] toByte(String hexString) throws Exception {
int len = hexString.length() / 2;
byte[] result = new byte[len];
for (int i = 0; i < len; i++)
result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
16).byteValue();
return result;
}
/**
* from byte array to hex
*
* @param buf byte array buffer
* @return return hex
* @throws Exception
*/
private String toHex(byte[] buf) throws Exception {
if (buf == null)
return "";
StringBuffer result = new StringBuffer(2 * buf.length);
for (int i = 0; i < buf.length; i++) {
appendHex(result, buf[i]);
}
return result.toString();
}
/**
* append byte in string buffer
*
* @param sb String buffer
* @param b byte
* @throws Exception
*/
private void appendHex(StringBuffer sb, byte b) throws Exception {
sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment