美文网首页
存储密钥到AndroidKeyStore,并进行加密处理

存储密钥到AndroidKeyStore,并进行加密处理

作者: hongzhenw | 来源:发表于2022-03-09 18:09 被阅读0次

    AndroidKeyStore支持将已生成的密钥进行导入,支持AES和HMAC算法。

    以HMAC为例

    HmacSHA1、HmacSHA224、HmacSHA256、HmacSHA384、HmacSHA512都是可以的

    导入密钥:

    private void createKey() {
            try {
                // generate key
                KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA256);
                SecretKey secretKey = keyGenerator.generateKey();
                // save to android keystore
                SecretKeySpec signingKey = new SecretKeySpec(secretKey.getEncoded(), secretKey.getAlgorithm());
                KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
                ks.load(null);
                KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(signingKey);
                ks.setEntry("my_key", entry, new KeyProtection.Builder(KeyProperties.PURPOSE_SIGN).build());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    

    使用密钥进行加密处理:

    private void byHmac() {
            try {
                KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
                ks.load(null);
    
                // func 1
                //SecretKey secretKey = (SecretKey) ks.getKey("my_key", null);
    
                // func 2
                KeyStore.SecretKeyEntry secretKeyEntry = (KeyStore.SecretKeyEntry) ks.getEntry("my_key", null);
                if (secretKeyEntry == null) {
                    Toast.makeText(this, "key is null", Toast.LENGTH_SHORT).show();
                    return;
                }
                SecretKey secretKey = secretKeyEntry.getSecretKey();
                if (secretKey == null) {
                    Toast.makeText(this, "key is null", Toast.LENGTH_SHORT).show();
                    return;
                }
                Mac mac = Mac.getInstance(secretKey.getAlgorithm());
                mac.init(secretKey);
                byte[] bytes = mac.doFinal("data content".getBytes(StandardCharsets.UTF_8));
                Log.e("whz", Base64.encodeToString(bytes, Base64.DEFAULT));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

    加密三次,输出日志

    ev0gAEzj1Q342vGHwm0l12Twp9lhTY+0/WZknhZ44DY=
    ev0gAEzj1Q342vGHwm0l12Twp9lhTY+0/WZknhZ44DY=
    ev0gAEzj1Q342vGHwm0l12Twp9lhTY+0/WZknhZ44DY=
    

    P.S:AES 可存储成功,但取出的SecretKey.getEncoded()为null,猜测是AndroidKeyStore不支持导出?????

    相关文章

      网友评论

          本文标题:存储密钥到AndroidKeyStore,并进行加密处理

          本文链接:https://www.haomeiwen.com/subject/wtztdrtx.html