安卓将生成的AES密钥转换为字符串(基数64 /十六进制..)



问题描述:

我正在开发一个安卓应用程序,该应用程序将生成AES密钥并将其存储在密钥库中。

每当我需要向服务器发送数据时,我都会使用 AES 密钥加密数据,使用服务器公钥加密 AES 密钥并将加密的数据 + 加密密钥发送到服务器以解密满载。

在安卓中生成密钥的代码如下:

public void generateKey()
{
try {
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();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

当我需要加密数据时,我使用此函数获取密钥

private java.security.Key getSecretKey(Context context) throws Exception {
return keyStore.getKey(KEY_ALIAS, null);
}

使用此密钥,我能够加密数据。 但问题是尝试加密密钥以将其发送到服务器。

我试图将密钥作为字节 [] 进行加密,但使用该函数

key.getEncoded();

生成的字节数组始终为 null。

这里出了什么问题以及如何解决?

应用程序适用于安卓 23+

我不确定,但是您在进行加密之前没有保存密钥,请确保您之前在Android密钥库中拥有它。

这个 kotlin 示例会有所帮助:


@Throws(IOException::class, KeyStoreException::class, CertificateException::class, NoSuchAlgorithmException::class)
fun saveKeyPair(pair: KeyPair, storeAlias: String) {
val certificate = generateCertificate(pair)
val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore!!.load(null, null)
val x509CertificateObject = X509CertificateObject(certificate)
keyStore.setKeyEntry(storeAlias, pair!!.private, null, arrayOf<java.security.cert.Certificate?>(x509CertificateObject))
}

希望这能有所帮助。

相关内容

最新更新