如何保护秘密字符串中的Andr​​oid应用程序?字符串、应用程序、秘密、Andr

2023-09-07 09:01:05 作者:我手指冰冷你愿意牵么

在我的Andr​​oid应用程序,我用这需要两个字符串,客户端ID和clientSecret微软翻译。在那一刻,我很难codeD这两个字符串。因为我发现classes.dex可以转化为罐子,然后.class文件也可以被转换为.java文件,我认为,这些硬编码字符串懂事是不是一件好事。

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?

感谢您

推荐答案

pre-加密字符串,并将其存储在一个资源文件。用钥匙进行解密。这仅仅是通过隐藏的安全,但至少在秘密不会是明文。

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", "");
    }
}

另外请注意,这个例子需要你包括Base64类项目:)

Also note, that this example requires you to include Base64 class in your project :)