Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to secure secret string in Android app?

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

like image 240
Romain Pellerin Avatar asked Nov 13 '22 08:11

Romain Pellerin


1 Answers

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 :)

like image 52
Bill Mote Avatar answered Nov 14 '22 22:11

Bill Mote