在 tozny/java-aes-crypto 中将密钥字符串转换为 SecretKeys 对象

Convert a key string to a SecretKeys object in tozny/java-aes-crypto

我正在使用 java-aes-crypto 加密 android 中的字符串。使用此代码生成密钥后

AesCbcWithIntegrity.SecretKeys keys = AesCbcWithIntegrity.generateKey();

我将它作为 String(.toString()) 保存在一个文件中,之后我试图从该文件中检索它并将它转换为同一个对象。我该怎么做?

通过link,可以看到您需要使用以下代码将加密的字符串转换为所需的字符串。

 //Use the constructor to re-create the CipherTextIvMac class from the string:
  CipherTextIvMac cipherTextIvMac = new CipherTextIvMac (cipherTextString);
  String plainText = AesCbcWithIntegrity.decryptString(cipherTextIvMac, **keys**);

keys 与加密时使用的密钥相同。 如您所见,您需要存储密钥才能对其进行解密。 link 还提供了存储密钥的预防措施

Once you've generated a random key, you naturally might want to store it. This may work for some use cases, but please be aware that if you store the key in the same place that you store the encrypted data, your solution is not cryptographically sound since the attacker can just get both the key and the encrypted text. Instead, you should use either the Keystore infrastructure or consider generating the key from a passphrase and using that to encrypt the user data.

If despite the above you still want to store the key, you can convert the keys to a string using the included functions and store them in preferences or SQLite.

AesCbcWithIntegrity class (link)中使用以下静态方法:

/**
 * An aes key derived from a base64 encoded key. This does not generate the
 * key. It's not random or a PBE key.
 *
 * @param keysStr a base64 encoded AES key / hmac key as base64(aesKey) : base64(hmacKey).
 * @return an AES and HMAC key set suitable for other functions.
 */
public static SecretKeys keys(String keysStr) throws InvalidKeyException {...}

它正确地将先前序列化的密钥解析为加密密钥和完整性密钥。