ext4crypt: support synthetic keys v3 on May update

Re-implemented SP800Derive in C++, which is added as the new key
derivation function in Android 9.0 May update. From file
services/core/java/com/android/server/locksettings/SP800Derive.java in
frameworks/base.

This is required to get TWRP working on any Android device that has a
screen lock set up after the May update.

Change-Id: I5c1a51b110033f2b0b75d5e36fd8098c05e95179
diff --git a/crypto/ext4crypt/HashPassword.cpp b/crypto/ext4crypt/HashPassword.cpp
index 817c984..07ecb1f 100644
--- a/crypto/ext4crypt/HashPassword.cpp
+++ b/crypto/ext4crypt/HashPassword.cpp
@@ -27,11 +27,13 @@
 #include <string>
 #include <stdlib.h>
 #include <openssl/sha.h>
+#include <openssl/hmac.h>
 
 #include "HashPassword.h"
 
 #define PASS_PADDING_SIZE 128
 #define SHA512_HEX_SIZE SHA512_DIGEST_LENGTH * 2
+#define SHA256_HEX_SIZE SHA256_DIGEST_LENGTH * 2
 
 void* PersonalizedHashBinary(const char* prefix, const char* key, const size_t key_size) {
 	size_t size = PASS_PADDING_SIZE + key_size;
@@ -78,6 +80,37 @@
 	return PersonalizedHash(prefix, Password.c_str(), Password.size());
 }
 
+std::string PersonalizedHashSP800(const char* label, const char* context, const char* key, const size_t key_size) {
+	HMAC_CTX ctx;
+	HMAC_CTX_init(&ctx);
+	HMAC_Init_ex(&ctx, key, key_size, EVP_sha256(), NULL);
+	unsigned int counter = 1;
+	endianswap(&counter);
+	HMAC_Update(&ctx, (const unsigned char*)&counter, 4);
+	HMAC_Update(&ctx, (const unsigned char*)label, strlen(label));
+	const unsigned char divider = 0;
+	HMAC_Update(&ctx, &divider, 1);
+	HMAC_Update(&ctx, (const unsigned char*)context, strlen(context));
+	unsigned int contextDisambiguation = strlen(context) * 8;
+	endianswap(&contextDisambiguation);
+	HMAC_Update(&ctx, (const unsigned char*)&contextDisambiguation, 4);
+	unsigned int finalValue = 256;
+	endianswap(&finalValue);
+	HMAC_Update(&ctx, (const unsigned char*)&finalValue, 4);
+
+	unsigned char output[SHA256_DIGEST_LENGTH];
+	unsigned int out_size = 0;
+	HMAC_Final(&ctx, output, &out_size);
+
+	int index = 0;
+	char hex_hash[SHA256_HEX_SIZE + 1];
+	for(index = 0; index < SHA256_DIGEST_LENGTH; index++)
+		sprintf(hex_hash + (index * 2), "%02x", output[index]);
+	hex_hash[SHA256_HEX_SIZE] = 0;
+	std::string ret = hex_hash;
+	return ret;
+}
+
 std::string HashPassword(const std::string& Password) {
 	const char* prefix = FBE_PERSONALIZATION;
 	return PersonalizedHash(prefix, Password);