summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorErwin Jansen <jansene@google.com>2024-03-29 08:51:19 -0700
committerErwin Jansen <jansene@google.com>2024-03-29 08:57:23 -0700
commitc6a35781ff39a8caeea8391808eef1b530480e74 (patch)
tree4c72affeac633a335633127ba21ffa737c4a2871
parent16feb111dcd29be36c4c478da7710ae4fda2d100 (diff)
downloadgoldfish-c6a35781ff39a8caeea8391808eef1b530480e74.tar.gz
Bring in adb key generation library from emu-master-dev
This brings in a set of functions to manipulate adb public and private keys. Test: All unit tests are green Change-Id: Ifdbaf7428e4f428ed36e50ede0d79e713dcb2aeb
-rw-r--r--adb/secrets/BUILD.bazel39
-rw-r--r--adb/secrets/include/android/emulation/control/adb/adbkey.h58
-rw-r--r--adb/secrets/src/android/emulation/control/adb/adbkey.cpp347
-rw-r--r--adb/secrets/test/adbkey_unittest.cpp231
4 files changed, 675 insertions, 0 deletions
diff --git a/adb/secrets/BUILD.bazel b/adb/secrets/BUILD.bazel
new file mode 100644
index 0000000..86100c1
--- /dev/null
+++ b/adb/secrets/BUILD.bazel
@@ -0,0 +1,39 @@
+cc_library(
+ name = "secrets",
+ srcs = glob([
+ "src/**/*.cpp",
+ ]),
+ hdrs = glob([
+ "include/**/*.h",
+ ]),
+ includes = [
+ "include",
+ "src",
+ ],
+ visibility = ["//visibility:public"],
+ deps = [
+ "//external/boringssl:ssl",
+ "//hardware/generic/goldfish/android/files",
+ "//hardware/generic/goldfish/files",
+ "//hardware/generic/goldfish/system",
+ "//hardware/google/aemu/base:aemu-base",
+ "@com_google_absl//absl/strings",
+ "@com_google_absl//absl/strings:str_format",
+ ],
+)
+
+cc_test(
+ name = "secrets_unnitests",
+ srcs = glob(
+ [
+ "test/**/*.cpp",
+ "test/**/*.h",
+ ],
+ exclude = ["test/**/Win32"],
+ ),
+ deps = [
+ ":secrets",
+ "//hardware/generic/goldfish/system:test-headers",
+ "@com_google_googletest//:gtest_main",
+ ],
+)
diff --git a/adb/secrets/include/android/emulation/control/adb/adbkey.h b/adb/secrets/include/android/emulation/control/adb/adbkey.h
new file mode 100644
index 0000000..c5a2e4a
--- /dev/null
+++ b/adb/secrets/include/android/emulation/control/adb/adbkey.h
@@ -0,0 +1,58 @@
+// Copyright 2019 The Android Open Source Project
+//
+// This software is licensed under the terms of the GNU General Public
+// License version 2, as published by the Free Software Foundation, and
+// may be copied, distributed, and modified under those terms.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+#pragma once
+
+#include <cstdint>
+#include <filesystem>
+#include <openssl/rsa.h>
+#include <string>
+
+// Size of an RSA modulus such as an encrypted block or a signature.
+constexpr const int ANDROID_PUBKEY_MODULUS_SIZE = 2048 / 8;
+// Adb authentication
+constexpr const int TOKEN_SIZE = 20;
+
+// Size of an encoded RSA key.
+constexpr const int ANDROID_PUBKEY_ENCODED_SIZE =
+ (3 * sizeof(uint32_t) + 2 * ANDROID_PUBKEY_MODULUS_SIZE);
+constexpr const char *kPrivateKeyFileName = "adbkey";
+constexpr const char *kPublicKeyFileName = "adbkey.pub";
+
+// Tries to find |adbKeyFileName|, returning "" if not found.
+// Will search the default key directories.
+std::filesystem::path
+getAdbKeyPath(const std::filesystem::path &adbKeyFileName);
+
+// Tries to find the "adbkey.pub" file, returning "" if not found
+std::filesystem::path getPublicAdbKeyPath();
+
+// Tries to find the "adbkey" file, returning "" if not found
+std::filesystem::path getPrivateAdbKeyPath();
+
+bool adb_auth_keygen(const std::filesystem::path &filename);
+
+// Creates a public key given the private key.
+// |path| Path to the adb private key.
+// |out| string receiving the public key.
+bool pubkey_from_privkey(const std::filesystem::path &path, std::string *out);
+
+/* Encodes |key| in the Android RSA public key binary format and stores the
+ * bytes in |key_buffer|. |key_buffer| should be of size at least
+ * |ANDROID_PUBKEY_ENCODED_SIZE|.
+ *
+ * Returns true if successful, false on error.
+ */
+bool android_pubkey_encode(const RSA *key, uint8_t *key_buffer, size_t size);
+bool android_pubkey_decode(const uint8_t *key_buffer, size_t size, RSA **key);
+bool sign_auth_token(const uint8_t *token, int token_size, uint8_t *sig,
+ int &siglen);
+bool calculate_public_key(std::string *out, RSA *private_key);
diff --git a/adb/secrets/src/android/emulation/control/adb/adbkey.cpp b/adb/secrets/src/android/emulation/control/adb/adbkey.cpp
new file mode 100644
index 0000000..2f0f1ff
--- /dev/null
+++ b/adb/secrets/src/android/emulation/control/adb/adbkey.cpp
@@ -0,0 +1,347 @@
+// Copyright 2019 The Android Open Source Project
+//
+// This software is licensed under the terms of the GNU General Public
+// License version 2, as published by the Free Software Foundation, and
+// may be copied, distributed, and modified under those terms.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+#include "android/emulation/control/adb/adbkey.h"
+
+#include <openssl/base.h>
+#include <openssl/base64.h> // for EVP_EncodeBlock, EVP_Encod...
+#include <openssl/bn.h>
+#include <openssl/evp.h>
+#include <openssl/nid.h>
+#include <openssl/pem.h>
+#include <openssl/rsa.h>
+
+#include <cstdio>
+#include <filesystem>
+#include <memory>
+#include <string.h>
+#include <string>
+#include <sys/types.h>
+#include <vector>
+
+#include "aemu/base/Log.h"
+#include "aemu/base/files/PathUtils.h"
+#include "android/base/file/file_io.h"
+#include "android/base/system/System.h"
+#include "android/goldfish/ConfigDirs.h"
+#include "android/utils/path.h"
+
+namespace fs = std::filesystem;
+/* set >0 for very verbose debugging */
+#define DEBUG 0
+
+#define D(...) (void)0
+#define DD(...) (void)0
+#if DEBUG >= 1
+#undef D
+#define D(fmt, ...) \
+ fprintf(stderr, "adbkey: %s:%d| " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
+#endif
+#if DEBUG >= 2
+#undef DD
+#define DD(fmt, ...) \
+ fprintf(stderr, "adbkey: %s:%d| " fmt "\n", __func__, __LINE__, ##__VA_ARGS__)
+#endif
+
+using android::base::System;
+
+// Better safe than sorry.
+static_assert(ANDROID_PUBKEY_MODULUS_SIZE % 4 == 0,
+ "RSA modulus size must be multiple of the word size!");
+
+// Size of the RSA modulus in words.
+constexpr const int ANDROID_PUBKEY_MODULUS_SIZE_WORDS =
+ ANDROID_PUBKEY_MODULUS_SIZE / 4;
+
+namespace {
+std::string get_user_info() {
+ std::string hostname = System::get()->getEnvironmentVariable("HOSTNAME");
+ if (hostname.empty()) {
+ hostname = "unknown";
+ }
+
+ std::string username;
+ if (getenv("LOGNAME")) {
+ username = getenv("LOGNAME");
+ }
+ if (username.empty()) {
+ hostname = "unknown";
+ }
+ return " " + username + "@" + hostname;
+}
+
+} // namespace
+
+// From ${AOSP}/system/core/adb/client/auth.cpp
+bool calculate_public_key(std::string *out, RSA *private_key) {
+ uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE];
+ if (!android_pubkey_encode(private_key, binary_key_data,
+ sizeof(binary_key_data))) {
+ LOG(ERROR) << "Failed to convert to public key";
+ return false;
+ }
+
+ size_t expected_length;
+ if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
+ LOG(ERROR) << "Public key too large to base64 encode";
+ return false;
+ }
+
+ out->resize(expected_length);
+ size_t actual_length = EVP_EncodeBlock(
+ (uint8_t *)out->data(), binary_key_data, sizeof(binary_key_data));
+ out->resize(actual_length);
+ out->append(get_user_info());
+ return true;
+}
+
+static std::shared_ptr<RSA> read_key_file(const std::string &file) {
+ std::unique_ptr<FILE, decltype(&fclose)> fp(android_fopen(file.c_str(), "r"),
+ fclose);
+ if (!fp) {
+ LOG(ERROR) << "Failed to open rsa file: " << file;
+ return nullptr;
+ }
+
+ RSA *key = RSA_new();
+ if (!PEM_read_RSAPrivateKey(fp.get(), &key, nullptr, nullptr)) {
+ LOG(ERROR) << "Failed to read rsa key";
+ RSA_free(key);
+ return nullptr;
+ }
+
+ return std::shared_ptr<RSA>(key, RSA_free);
+}
+
+static bool generate_key(const std::string &file) {
+
+ mode_t old_mask;
+ FILE *f = nullptr;
+ bool ret = false;
+
+ EVP_PKEY *pkey = EVP_PKEY_new();
+ BIGNUM *exponent = BN_new();
+ RSA *rsa = RSA_new();
+ if (!pkey || !exponent || !rsa) {
+ dwarning("Failed to allocate key");
+ goto out;
+ }
+
+ BN_set_word(exponent, RSA_F4);
+ RSA_generate_key_ex(rsa, 2048, exponent, nullptr);
+ EVP_PKEY_set1_RSA(pkey, rsa);
+
+ f = android_fopen(file.c_str(), "w");
+ if (!f) {
+ dwarning("Failed to open %s", file.c_str());
+ goto out;
+ }
+
+ if (!PEM_write_PrivateKey(f, pkey, nullptr, nullptr, 0, nullptr, nullptr)) {
+ dwarning("Failed to write key");
+ goto out;
+ }
+
+ fclose(f);
+ f = nullptr;
+ android_chmod(file.c_str(), 0777);
+
+ ret = true;
+
+out:
+ if (f) {
+ fclose(f);
+ }
+ EVP_PKEY_free(pkey);
+ RSA_free(rsa);
+ BN_free(exponent);
+ return ret;
+}
+
+bool adb_auth_keygen(const fs::path &filename) { return generate_key(filename); }
+
+bool pubkey_from_privkey(const fs::path &path, std::string *out) {
+ std::shared_ptr<RSA> privkey = read_key_file(path);
+ if (!privkey) {
+ return false;
+ }
+ return calculate_public_key(out, privkey.get());
+}
+
+// Get adbkey path, return "" if failed
+// adbKeyFileName could be "adbkey" or "adbkey.pub"
+fs::path getAdbKeyPath(const fs::path& adbKeyFileName) {
+ fs::path adbKeyPath = android::goldfish::ConfigDirs::getUserDirectory() / adbKeyFileName;
+ if (path_is_regular(adbKeyPath.c_str()) &&
+ path_can_read(adbKeyPath.c_str())) {
+ return adbKeyPath;
+ }
+ D("cannot read adb key file: %s", adbKeyPath.c_str());
+ D("trying again by copying from home dir");
+
+ auto home = System::get()->getHomeDirectory();
+ if (home.empty()) {
+ home = System::get()->getTempDir();
+ if (home.empty()) {
+ home = "/tmp";
+ }
+ }
+ D("Looking in %s", home.c_str());
+
+ auto guessedSrcAdbKeyPub = home / ".android" / adbKeyFileName;
+ path_copy_file(adbKeyPath.c_str(), guessedSrcAdbKeyPub.c_str());
+
+ if (path_is_regular(adbKeyPath.c_str()) &&
+ path_can_read(adbKeyPath.c_str())) {
+ return adbKeyPath;
+ }
+ D("cannot read adb key file (failed): %s", adbKeyPath.c_str());
+ return "";
+}
+
+fs::path getPublicAdbKeyPath() { return getAdbKeyPath(kPublicKeyFileName); }
+
+fs::path getPrivateAdbKeyPath() {
+ return getAdbKeyPath(kPrivateKeyFileName);
+}
+
+// This file implements encoding and decoding logic for Android's custom RSA
+// public key binary format. Public keys are stored as a sequence of
+// little-endian 32 bit words. Note that Android only supports little-endian
+// processors, so we don't do any byte order conversions when parsing the binary
+// struct.
+typedef struct RSAPublicKey {
+ // Modulus length. This must be ANDROID_PUBKEY_MODULUS_SIZE.
+ uint32_t modulus_size_words;
+
+ // Precomputed montgomery parameter: -1 / n[0] mod 2^32
+ uint32_t n0inv;
+
+ // RSA modulus as a little-endian array.
+ uint8_t modulus[ANDROID_PUBKEY_MODULUS_SIZE];
+
+ // Montgomery parameter R^2 as a little-endian array of little-endian words.
+ uint8_t rr[ANDROID_PUBKEY_MODULUS_SIZE];
+
+ // RSA modulus: 3 or 65537
+ uint32_t exponent;
+} RSAPublicKey;
+
+bool android_pubkey_decode(const uint8_t *key_buffer, size_t size, RSA **key) {
+ // Check |size| is large enough and the modulus size is correct.
+ if (size < sizeof(RSAPublicKey)) {
+ LOG(ERROR) << "WARNING: adbkey decode failed.";
+ return false;
+ }
+ RSAPublicKey key_struct;
+ memcpy(&key_struct, key_buffer, sizeof(key_struct));
+
+ if (key_struct.modulus_size_words != ANDROID_PUBKEY_MODULUS_SIZE_WORDS) {
+ LOG(ERROR) << "WARNING: adbkey decode failed.";
+ return false;
+ }
+
+ // Read the modulus and exponent.
+ bssl::UniquePtr<BIGNUM> n(
+ BN_le2bn(key_struct.modulus, ANDROID_PUBKEY_MODULUS_SIZE, nullptr));
+ bssl::UniquePtr<BIGNUM> e(BN_new());
+ if (!n || !e || !BN_set_word(e.get(), key_struct.exponent)) {
+ LOG(ERROR) << "WARNING: adbkey decode failed.";
+ return false;
+ }
+
+ // TODO(davidben): After we're sure the BoringSSL update has stuck, switch
+ // this to RSA_new_public_key, which is a bit less tedious. For now, use the
+ // older APIs to avoid a build break if it gets temporarily reverted.
+ bssl::UniquePtr<RSA> new_key(RSA_new());
+ if (!new_key ||
+ !RSA_set0_key(new_key.get(), n.get(), e.get(), /*d=*/nullptr)) {
+ LOG(ERROR) << "WARNING: adbkey decode failed.";
+ return false;
+ }
+ // RSA_set0_key takes ownership on success.
+ (void) n.release();
+ (void) e.release();
+
+ *key = new_key.release();
+ return true;
+}
+
+bool android_pubkey_encode(const RSA *key, uint8_t *key_buffer, size_t size) {
+ if (sizeof(RSAPublicKey) > size ||
+ RSA_size(key) != ANDROID_PUBKEY_MODULUS_SIZE) {
+ return false;
+ }
+
+ // Store the modulus size.
+ RSAPublicKey key_struct;
+ key_struct.modulus_size_words = ANDROID_PUBKEY_MODULUS_SIZE_WORDS;
+
+ // Compute and store n0inv = -1 / N[0] mod 2^32.
+ bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new());
+ bssl::UniquePtr<BIGNUM> r32(BN_new());
+ bssl::UniquePtr<BIGNUM> n0inv(BN_new());
+ if (!ctx || !r32 || !n0inv || !BN_set_bit(r32.get(), 32) ||
+ !BN_mod(n0inv.get(), RSA_get0_n(key), r32.get(), ctx.get()) ||
+ !BN_mod_inverse(n0inv.get(), n0inv.get(), r32.get(), ctx.get()) ||
+ !BN_sub(n0inv.get(), r32.get(), n0inv.get())) {
+ return false;
+ }
+ key_struct.n0inv = (uint32_t)BN_get_word(n0inv.get());
+
+ // Store the modulus.
+ if (!BN_bn2le_padded(key_struct.modulus, ANDROID_PUBKEY_MODULUS_SIZE,
+ RSA_get0_n(key))) {
+ return false;
+ }
+
+ // Compute and store rr = (2^(rsa_size)) ^ 2 mod N.
+ bssl::UniquePtr<BIGNUM> rr(BN_new());
+ if (!rr || !BN_set_bit(rr.get(), ANDROID_PUBKEY_MODULUS_SIZE * 8) ||
+ !BN_mod_sqr(rr.get(), rr.get(), RSA_get0_n(key), ctx.get()) ||
+ !BN_bn2le_padded(key_struct.rr, ANDROID_PUBKEY_MODULUS_SIZE, rr.get())) {
+ return false;
+ }
+
+ // Store the exponent.
+ key_struct.exponent = (uint32_t)BN_get_word(RSA_get0_e(key));
+ memcpy(key_buffer, &key_struct, sizeof(key_struct));
+ return true;
+}
+
+static bool sign_token(RSA *key_rsa, const uint8_t *token, int token_size,
+ uint8_t *sig, int &len) {
+ if (token_size != TOKEN_SIZE) {
+ DD("Unexpected token size %d\n", token_size);
+ }
+
+ if (!RSA_sign(NID_sha1, token, (size_t)token_size, sig, (unsigned int *)&len,
+ key_rsa)) {
+ return false;
+ }
+
+ DD("successfully signed with siglen %d\n", (int)len);
+ return true;
+}
+
+bool sign_auth_token(const uint8_t *token, int token_size, uint8_t *sig,
+ int &siglen) {
+ const std::string key_path = getAdbKeyPath(kPrivateKeyFileName);
+ if (key_path.empty()) {
+ LOG(ERROR) << "No private key found, unable to sign token";
+ }
+ auto rsa = read_key_file(key_path);
+ if (!rsa) {
+ LOG(ERROR) << "No RSA key available.";
+ return false;
+ }
+ return sign_token(rsa.get(), token, token_size, sig, siglen);
+}
diff --git a/adb/secrets/test/adbkey_unittest.cpp b/adb/secrets/test/adbkey_unittest.cpp
new file mode 100644
index 0000000..382eea7
--- /dev/null
+++ b/adb/secrets/test/adbkey_unittest.cpp
@@ -0,0 +1,231 @@
+// Copyright 2020 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+#include "android/emulation/control/adb/adbkey.h"
+#include <gtest/gtest.h>
+#include <openssl/obj_mac.h>
+#include <openssl/rsa.h>
+#include <memory>
+#include <fstream>
+#include <string>
+#include <vector>
+#include "android/base/testing/TestSystem.h"
+#include "android/base/testing/TestTempDir.h"
+
+namespace android {
+namespace base {
+
+// Secret token that gets verified.
+const uint8_t challenge_token[20] = {0xE8, 0x99, 0xE1, 0xFF, 0x95, 0x9B, 0x8F,
+ 0x6B, 0x54, 0xBE, 0xCE, 0xC5, 0x42, 0xF1,
+ 0x93, 0x7D, 0x3, 0x99, 0xA2, 0x32};
+
+// Private key that can be used to answer challenge token above.
+std::string privkey = R"##(-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCxc0jUMYZ5fJSo
+7t0MEfGDV9GPhdvOfgKv3GRaqnPuTD04SCXPwu7iJ9y6rS/Rk1CsW9HI+LcQvu5h
+AsbpzDW88Sg5kSWfbEWP7EgPfdcfWdOfaRFZ/0J/sRejvCnekmnPF75irEYPI/sx
+jL2xIJ1kTOywOCBB3l/xkPPSLPt2159Lm3v+pMdinq6rp8RQ7XK9pj4dv4tb778+
+mLtp4p6FhOH6rU/q4848v4CM1/YVXZZaMKmos4PfvFLknzCmd3xN2o1MusP2OSxb
+NkXXpCTsJLufcb3ItBgLyEri/eOQcYzpV84vTHwqr121stDpjVAR3H4AaelHZqOF
+JKY5NVJTAgMBAAECggEASD7BdfK75xY7iBPH1zQu+eR1I1PCS+2ttl+qU+d1z50m
+h5WIH3Ajxduo2C/OeirZ+3JelM396klxz/lLdsB3WHdugxF/GcsA/zmZlQUM4my1
+5f7m25c7QbWeBEGFYmKFxZTLJG0zENL7YA8G4+h9a+qNqqkPKQIaWcVEH1vE/Xra
+hNwD6wYyj01aVAdSDKgu6EtIpmVDlgDFE33JQnHM9r3c6o6QdNQTlhGyQ+SX2rCx
+y3a0pW4MlGas1RtWDwOHt6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TempRoot();
+ mTestDir->makeSubDir(".android");
+ mTestSystem.setHomeDirectory(mTestDir->path());
+ }
+
+ ~AdbKeyTest() {}
+
+protected:
+ TestSystem mTestSystem{"/"};
+ TestTempDir* mTestDir;
+ const char* tstKey = "adbsamplekey";
+};
+
+TEST_F(AdbKeyTest, key_does_not_exist) {
+ EXPECT_EQ("", getAdbKeyPath("thisshouldnotexist.boo"));
+}
+
+TEST_F(AdbKeyTest, find_keys_in_default_path) {
+ mTestDir->makeSubFile(".android/adbkey");
+ mTestDir->makeSubFile(".android/adbkey.pub");
+ EXPECT_NE("", getPrivateAdbKeyPath());
+ EXPECT_NE("", getPublicAdbKeyPath());
+}
+
+TEST_F(AdbKeyTest, generate_writes_a_key) {
+ std::string keyFile = mTestDir->path() / ".android" / tstKey;
+ EXPECT_EQ("", getAdbKeyPath(tstKey));
+ EXPECT_TRUE(adb_auth_keygen(keyFile.c_str()));
+ EXPECT_NE("", getAdbKeyPath(tstKey));
+}
+
+TEST_F(AdbKeyTest, can_create_pub_from_generated_priv) {
+ std::string pubkey;
+ std::string keyFile = mTestDir->path() / ".android" / tstKey;
+ EXPECT_TRUE(adb_auth_keygen(keyFile.c_str()));
+ EXPECT_TRUE(pubkey_from_privkey(keyFile, &pubkey));
+ EXPECT_NE("", pubkey);
+}
+
+TEST_F(AdbKeyTest, can_sign_token) {
+ std::string pubkey;
+ std::string keyFile = mTestDir->path() / ".android" / kPrivateKeyFileName;
+ std::ofstream out(keyFile);
+ out << privkey << std::endl;
+ out.close();
+
+
+ EXPECT_TRUE(pubkey_from_privkey(keyFile, &pubkey));
+ EXPECT_NE("", pubkey);
+
+ int siglen = 256;
+ std::vector<uint8_t> signed_token{};
+ signed_token.resize(siglen);
+ EXPECT_TRUE(sign_auth_token(challenge_token, sizeof(challenge_token),
+ signed_token.data(), siglen));
+
+ EXPECT_NE("", std::string((char*)signed_token.data(), siglen));
+}
+
+// Test digest to verify.
+const uint8_t kDigest[] = {
+ 0x31, 0x5f, 0x5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, 0xc5, 0x2b,
+ 0x7b, 0xe0, 0xb1, 0xf6, 0x2a, 0xd5, 0x61, 0xba, 0x1e, 0x1e, 0x3a, 0xf0,
+ 0x55, 0xbc, 0x8c, 0x44, 0x41, 0xfc, 0xb8, 0x8c, 0x76, 0xbf, 0x80, 0x58,
+ 0x82, 0x35, 0x4b, 0x0c, 0xfd, 0xef, 0xd5, 0x70, 0xd1, 0x64, 0xcb, 0x46,
+ 0x58, 0x37, 0xbc, 0xa9, 0x7d, 0xd4, 0x70, 0xac, 0xce, 0xec, 0xca, 0x48,
+ 0xcb, 0x0a, 0x40, 0x77, 0x04, 0x59, 0xca, 0x9c, 0x7d, 0x1a, 0x0b, 0xf0,
+ 0xb5, 0xdd, 0xde, 0x71, 0x18, 0xb8, 0xef, 0x90, 0x2a, 0x09, 0x42, 0x39,
+ 0x74, 0xff, 0x45, 0xa1, 0x39, 0x17, 0x50, 0x89, 0xa6, 0x5f, 0xbc, 0x9c,
+ 0x0c, 0x9b, 0x47, 0x25, 0x79, 0x3e, 0xe3, 0xaa, 0xaf, 0xbe, 0x73, 0x6b,
+ 0xcb, 0xe7, 0x35, 0xc1, 0x27, 0x09, 0xcd, 0xeb, 0xd7, 0xcf, 0x63, 0x83,
+ 0x64, 0x8c, 0x45, 0x1c, 0x1d, 0x58, 0xcc, 0xd2, 0xf8, 0x2b, 0x4c, 0x4e,
+ 0x14, 0x89, 0x2d, 0x70,
+};
+
+struct AndroidPubkeyTest : public ::testing::Test {
+ void SetUp() override {
+ RSA* new_key = nullptr;
+ android_pubkey_decode(kKey2048, sizeof(kKey2048), &new_key);
+ key_.reset(new_key);
+ }
+
+ std::unique_ptr<RSA, void (*)(RSA*)> key_ = {nullptr, RSA_free};
+};
+
+TEST_F(AndroidPubkeyTest, Decode) {
+ // Make sure the decoded key successfully verifies a valid signature.
+ EXPECT_TRUE(RSA_verify(NID_sha256, kDigest, sizeof(kDigest), kSignature2048,
+ sizeof(kSignature2048), key_.get()));
+}
+
+TEST_F(AndroidPubkeyTest, Encode) {
+ //uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
+ uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
+ ASSERT_TRUE(android_pubkey_encode(key_.get(), key_data, sizeof(key_data)));
+ ASSERT_EQ(0, memcmp(kKey2048, key_data, sizeof(kKey2048)));
+}
+
+} // namespace base
+} // namespace android