【发布时间】:2015-11-28 20:54:05
【问题描述】:
我正在使用下面的代码创建一个 hmac 密钥并将其作为字符串返回。
KeyGenerator keyGen = null;
try {
keyGen = KeyGenerator.getInstance("HmacSHA256");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
SecretKey key = keyGen.generateKey();
byte[] encoded = key.getEncoded();
String s=Base64.encodeToString(encoded, Base64.DEFAULT);
Log.i("Hmac key before encrypt",s);
try {
KeyStore keystore = KeyStore.getInstance("AndroidKeyStore");
keystore.load(null, null);
KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry("temp", null);
RSAPublicKey publicKey = (RSAPublicKey) privateKeyEntry.getCertificate().getPublicKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherBytes = cipher.doFinal(encoded);
return Base64.encodeToString(cipherBytes,Base64.DEFAULT);
} catch (UnrecoverableEntryException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
如何将其存储在 android 密钥库中?我试过使用下面的代码:
KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
keyStore.load(null);
KeyStore.ProtectionParameter param = new KeyStore.PasswordProtection("test".toCharArray());
keyStore.setEntry("key1",hmacKey,param);
无论 hmacKey 采用什么格式,我都会收到错误消息:String/Bytes 或 javax.crypto.SecretKey。以下是错误:
如果传递 Key hmacKey:
Wrong 2nd argument type. Found: 'java.security.Key', required: 'java.security.KeyStore.Entry'
在我传递字符串或字节数组的情况下也是如此。
如果我将参数类型转换为java.security.KeyStore.Entry,它仍然不起作用。
这是正确的做法吗?任何人都可以提供有关如何使用别名将 HMAC 密钥存储在密钥库中的指针。如何将hmack密钥转换为java.security.KeyStore.Entry格式?
【问题讨论】:
-
抱歉含糊不清。编辑了问题
-
你不能只存储上面生成的
key吗?我在这个问题中看到了很多绒毛。这似乎不是 MCSE。 -
不,不能这样存储。我目前正在使用共享首选项来存储此密钥。不确定那里的安全方面是否存在,这就是我想将它存储在密钥库中的原因。代码的第一部分工作得很好,我可以创建一个 hmack 密钥并返回它。它是我试图将其存储在 android 密钥库中的部分,其别名导致问题。
标签: java android cryptography keystore hmac