我想将从给定的字节数组生成的密钥导入到Android Keystore。但是提出了一些例外。
在这种情况下,有人知道如何导入密钥吗?
我尝试了以下代码:
try {
byte[] keyBytes = new byte {0x31,0x32,0x33};
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
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();
}
例外如下:
W/System.err: java.security.KeyStoreException: Failed to import secret key. Keystore error code: -6
W/System.err: at android.security.keystore.AndroidKeyStoreSpi.setSecretKeyEntry(AndroidKeyStoreSpi.java:742)
W/System.err: at
android.security.keystore.AndroidKeyStoreSpi.engineSetEntry(AndroidKeyStoreSpi.java:1060)
W/System.err: at
java.security.KeyStore.setEntry(KeyStore.java:1596)
答案 0 :(得分:0)
我通过确保密钥库支持字节数组的长度来解决此问题。
下面是我目前可以修改的代码
try {
//32bytes (256bit)
byte[] keyBytes = "0123456789ABCDEF0123456789ABCDEF".getBytes();
SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");
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();
}