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

2022-03-09  本文已影响0人  hongzhenw

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不支持导出?????

上一篇下一篇

猜你喜欢

热点阅读