blob: 86e067ebb1827099b9b44cf4e49fd6b73df32383 [file] [log] [blame]
Ethan Yonkerbd7492d2016-12-07 13:55:01 -06001/*
2 * Copyright (C) 2016 Team Win Recovery Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * This computes the "secret" used by Android as one of the parameters
19 * to decrypt File Based Encryption. The secret is prefixed with
20 * "Android FBE credential hash" padded with 0s to 128 bytes then the
21 * user's password is appended to the end of the 128 bytes. This string
22 * is then hashed with sha512 and the sha512 value is then converted to
23 * hex with upper-case characters.
24 */
25
26#include <stdio.h>
27#include <string>
28#include <stdlib.h>
29#include <openssl/sha.h>
30
31#define PASS_PADDING_SIZE 128
32#define SHA512_HEX_SIZE SHA512_DIGEST_LENGTH * 2
33
34std::string HashPassword(const std::string& Password) {
35 size_t size = PASS_PADDING_SIZE + Password.size();
36 unsigned char* buffer = (unsigned char*)calloc(1, size);
37 const char* prefix = "Android FBE credential hash";
38 memcpy((void*)buffer, (void*)prefix, strlen(prefix));
39 unsigned char* ptr = buffer + PASS_PADDING_SIZE;
40 memcpy((void*)ptr, Password.c_str(), Password.size());
41 unsigned char hash[SHA512_DIGEST_LENGTH];
42 SHA512_CTX sha512;
43 SHA512_Init(&sha512);
44 SHA512_Update(&sha512, buffer, size);
45 SHA512_Final(hash, &sha512);
46 int index = 0;
47 char hex_hash[SHA512_HEX_SIZE + 1];
48 for(index = 0; index < SHA512_DIGEST_LENGTH; index++)
49 sprintf(hex_hash + (index * 2), "%02X", hash[index]);
50 hex_hash[128] = 0;
51 std::string ret = hex_hash;
52 return ret;
53}