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

Posted

技术标签:

【中文标题】如何保护 Android 应用程序中的秘密字符串?【英文标题】:How to secure secret string in Android app? 【发布时间】:2013-03-25 21:50:58 【问题描述】:

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

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

谢谢

【问题讨论】:

类似:***.com/questions/12465328/… 查看这个答案***.com/questions/4427238/… 【参考方案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", "");
    

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

【讨论】:

谢谢!!我将在本周末尝试您的解决方案,并让您知道它是否有效。为什么建议我将字符串存储在资源文件中? 只是进一步的抽象。我将它们存储在字符串文件中,并且我通常将密钥设置为字符串文件中已经存在的其他内容——请注意,我制作的东西看起来很合适,但实际上并没有被使用,所以我不会冒险更改它错误:) -1 这不安全。这是不可能的,你不需要它。见cwe.mitre.org/data/definitions/602.html Base64类的代码?,示例需要 没有。 Base64 类可以从 Internet 上免费下载,我相信 Android 现在已经内置了一个版本。

以上是关于如何保护 Android 应用程序中的秘密字符串?的主要内容,如果未能解决你的问题,请参考以下文章

如何通过哈希比较限制 API 密钥的使用

如何使用 API 密钥和秘密保护 Spring Boot API

如何保护服务器-服务器应用程序中的通信?

如何在不使用 github 中的秘密的情况下安全地签署 Android apk?

如何保护 Android apk 包中的 rapidapi 密钥

如何保护 Android 应用程序中的 Azure 翻译 API 密钥