How to secure secret string in Android app?

前端 未结 1 692
忘了有多久
忘了有多久 2021-01-06 06:18

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

相关标签:
1条回答
  • 2021-01-06 06:22

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

    0 讨论(0)
提交回复
热议问题