Keystore 2.0: Add safe crypto wrapper
* Adds safe wrappers for AES_gcm_decrypt and AES_gcm_encrypt.
* Adds AES256 key generation.
* Adds ZVec, a simple fixed size owned vector type that locks
the backing memory in place with mlock and zeroes the buffer
before freeing it.
Test: keystore2_test
Bug: 173545997
Change-Id: Id7e30d50b024da1fa8aa58a07cd9bb7a861f81f0
diff --git a/keystore2/src/crypto/crypto.cpp b/keystore2/src/crypto/crypto.cpp
index 8c52e4c..173ed11 100644
--- a/keystore2/src/crypto/crypto.cpp
+++ b/keystore2/src/crypto/crypto.cpp
@@ -21,6 +21,7 @@
#include <log/log.h>
#include <openssl/aes.h>
#include <openssl/evp.h>
+#include <openssl/rand.h>
#include <vector>
@@ -60,6 +61,10 @@
return cipher;
}
+bool randomBytes(uint8_t* out, size_t len) {
+ return RAND_bytes(out, len);
+}
+
/*
* Encrypt 'len' data at 'in' with AES-GCM, using 128-bit or 256-bit key at 'key', 96-bit IV at
* 'iv' and write output to 'out' (which may be the same location as 'in') and 128-bit tag to
@@ -172,13 +177,13 @@
// Copied from system/security/keystore/user_state.cpp.
void generateKeyFromPassword(uint8_t* key, size_t key_len, const char* pw, size_t pw_len,
- uint8_t* salt) {
+ const uint8_t* salt) {
size_t saltSize;
if (salt != nullptr) {
saltSize = SALT_SIZE;
} else {
// Pre-gingerbread used this hardwired salt, readMasterKey will rewrite these when found
- salt = (uint8_t*)"keystore";
+ salt = reinterpret_cast<const uint8_t*>("keystore");
// sizeof = 9, not strlen = 8
saltSize = sizeof("keystore");
}