In my android app, I use Microsoft translator which requires two strings, clientId and clientSecret. At the moment, I hardcoded those two strings. Since I discovered classes.dex can be converted to jar, and then .class files can also be converted to .java files, I think that hardcoding those sensible strings is not a good thing.
So my question is simple: how to hide those strings from malicious people?
Thank you
Pre-encrypt a String and store it in a resource file. Decrypt it with a key. It's merely security through obscurity, but at least the "secrets" won't be in plain text.
public class KeyHelper {
/**
* Encrypt a string
*
* @param s
* The string to encrypt
* @param key
* The key to seed the encryption
* @return The encrypted string
*/
public static String encode(String s, String key) {
return base64Encode(xorWithKey(s.getBytes(), key.getBytes()));
}
/**
* Decrypt a string
*
* @param s
* The string to decrypt
* @param key
* The key used to encrypt the string
* @return The unencrypted string
*/
public static String decode(String s, String key) {
return new String(xorWithKey(base64Decode(s), key.getBytes()));
}
private static byte[] xorWithKey(byte[] a, byte[] key) {
byte[] out = new byte[a.length];
for (int i = 0; i < a.length; i++) {
out[i] = (byte) (a[i] ^ key[i % key.length]);
}
return out;
}
private static byte[] base64Decode(String s) {
try {
return Base64.decode(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String base64Encode(byte[] bytes) {
return Base64.encodeBytes(bytes).replaceAll("\\s", "");
}
}
Also note, that this example requires you to include Base64 class in your project :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With