Android KeyStore获取存储的密钥的原始字节/字符串 [英] Android KeyStore get raw bytes/string of stored key

查看:370
本文介绍了Android KeyStore获取存储的密钥的原始字节/字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以生成一个要存储在Android Keystore中的密钥,如下所示:

I can generate a key to be stored in the Android Keystore like so:

private static final String AndroidKeyStore = "AndroidKeyStore";
private static final String AES_MODE = "AES/GCM/NoPadding";
keyStore = KeyStore.getInstance(AndroidKeyStore);
keyStore.load(null);

if (!keyStore.containsAlias(KEY_ALIAS)) {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);
    keyGenerator.init(
            new KeyGenParameterSpec.Builder(KEY_ALIAS,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)                   .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .setRandomizedEncryptionRequired(false) 
                    .build());
    keyGenerator.generateKey();
}

类似地,我可以这样检索它:

Similarly, I can retrieve it like so:

keyStore.getKey(KEY_ALIAS, null);

我知道getKey()函数返回一个Key对象,但是我还没有找到显示密钥本身的方法.它似乎没有toString()或getBytes()或类似的东西.

I know that the getKey() function returns a Key object, but I haven't found a way to reveal the key itself. It does not seem to have a toString() or getBytes() or something like that.

如何获取密钥的字节,或者至少打印出密钥的字符串版本?甚至有可能吗?

How can I get the bytes of the key, or at least print out the string version of it? Is it even possible?

推荐答案

"AndroidKeyStore"经过专门设计,以使其不可能或至少非常困难.在此处,有一个更完整的讨论,但总结如下:

The "AndroidKeyStore" is specifically designed to make this impossible or at least very difficult. There is a more complete discussion here, but in summary:

Android Keystore系统可保护密钥材料免遭未经授权的使用. 首先,Android Keystore可以减轻对密钥材料的未经授权的使用 通过防止提取密钥在Android设备外部 来自应用程序流程和来自Android设备的材料 整个.

Android Keystore system protects key material from unauthorized use. Firstly, Android Keystore mitigates unauthorized use of key material outside of the Android device by preventing extraction of the key material from application processes and from the Android device as a whole.

继续执行示例中的以下几行代码:

Continuing along the lines of your example, the following additional lines of code:

Key key = keyStore.getKey(KEY_ALIAS, null);
String algorithm = key.getAlgorithm();
String format = key.getFormat();
byte[] encoded = key.getEncoded();

应该使key是对Key对象的有效非空引用,algorithm应该返回"AES",但是format应该和encoded一样是null.

should cause key to be a valid non-null reference to Key object, algorithm should return "AES", but format should be null as should encoded.

这篇关于Android KeyStore获取存储的密钥的原始字节/字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆