Storing a hmac key in Android keystore

后端 未结 1 1352
醉酒成梦
醉酒成梦 2021-02-11 01:41

I am using the below code to create a hmac key and returning it as a string.

KeyGenerator keyGen = null;
    try {
        keyGen = KeyGenerator.getInstance(\"Hm         


        
相关标签:
1条回答
  • 2021-02-11 02:05

    The Android key store was created to allow you to use asymmetric keys and symmetric keys outside your application code. As specified in the training material:

    Key material never enters the application process. When an application performs cryptographic operations using an Android Keystore key, behind the scenes plaintext, ciphertext, and messages to be signed or verified are fed to a system process which carries out the cryptographic operations. If the app's process is compromised, the attacker may be able to use the app's keys but will not be able to extract their key material (for example, to be used outside of the Android device).

    So the idea of generating the key inside the application code - and thus outside the key store - is not a good idea. How to generate a secret key inside the key store is defined for HMAC keys in the API for the KeyGenParameterSpec class:

    KeyGenerator keyGenerator = KeyGenerator.getInstance(
             KeyProperties.KEY_ALGORITHM_HMAC_SHA256, "AndroidKeyStore");
    keyGenerator.initialize(
             new KeyGenParameterSpec.Builder("key2", KeyProperties.PURPOSE_SIGN).build());
    SecretKey key = keyGenerator.generateKey();
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(key);
    ...
    
    // The key can also be obtained from the Android Keystore any time as follows:
    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    keyStore.load(null);
    key = (SecretKey) keyStore.getKey("key2", null);
    

    Other key types can be found in the KeyProperties class

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