如何保护 Android 应用程序中的秘密字符串?

Rom*_*rin 5 java security android cryptography

在我的 android 应用程序中,我使用 Microsoft 转换器,它需要两个字符串,clientId 和 clientSecret。目前,我对这两个字符串进行了硬编码。由于我发现classes.dex可以转jar,.class文件也可以转java文件,我觉得硬编码那些合理的字符串不是什么好事。

所以我的问题很简单:如何对恶意的人隐藏这些字符串?

谢谢

Bil*_*ote 1

预加密字符串并将其存储在资源文件中。用密钥解密它。这只是通过模糊来实现安全,但至少“秘密”不会是纯文本形式。

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", "");
    }
}
Run Code Online (Sandbox Code Playgroud)

另请注意,此示例要求您在项目中包含 Base64 类:)