2 * Copyright (C) 2013 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define _GNU_SOURCE /* needed for asprintf */
23 #include <sys/types.h>
26 #include <crypto_utils/android_pubkey.h>
28 #include <openssl/evp.h>
29 #include <openssl/objects.h>
30 #include <openssl/pem.h>
31 #include <openssl/rsa.h>
32 #include <openssl/sha.h>
34 static int write_public_keyfile(RSA *private_key, const char *private_key_path)
36 uint8_t key_data[ANDROID_PUBKEY_ENCODED_SIZE];
41 if (asprintf(&path, "%s.pub", private_key_path) < 0)
44 if (!android_pubkey_encode(private_key, key_data, sizeof(key_data)))
47 bfile = BIO_new_file(path, "w");
51 BIO_write(bfile, key_data, sizeof(key_data));
61 static int convert_x509(const char *pem_file, const char *key_file)
65 EVP_PKEY *pkey = NULL;
69 if (!pem_file || !key_file) {
73 f = fopen(pem_file, "r");
75 printf("Failed to open '%s'\n", pem_file);
79 cert = PEM_read_X509(f, &cert, NULL, NULL);
81 printf("Failed to read PEM certificate from file '%s'\n", pem_file);
85 pkey = X509_get_pubkey(cert);
87 printf("Failed to extract public key from certificate '%s'\n", pem_file);
91 rsa = EVP_PKEY_get1_RSA(pkey);
93 printf("Failed to get the RSA public key from '%s'\n", pem_file);
97 if (write_public_keyfile(rsa, key_file) < 0) {
98 printf("Failed to write public key\n");
121 static int generate_key(const char *file)
125 RSA* rsa = RSA_new();
126 BIGNUM* exponent = BN_new();
127 EVP_PKEY* pkey = EVP_PKEY_new();
129 if (!pkey || !exponent || !rsa) {
130 printf("Failed to allocate key\n");
134 BN_set_word(exponent, RSA_F4);
135 RSA_generate_key_ex(rsa, 2048, exponent, NULL);
136 EVP_PKEY_set1_RSA(pkey, rsa);
138 f = fopen(file, "w");
140 printf("Failed to open '%s'\n", file);
144 if (!PEM_write_PrivateKey(f, pkey, NULL, NULL, 0, NULL, NULL)) {
145 printf("Failed to write key\n");
149 if (write_public_keyfile(rsa, file) < 0) {
150 printf("Failed to write public key\n");
166 printf("Usage: generate_verity_key <path-to-key> | -convert <path-to-x509-pem> <path-to-key>\n");
169 int main(int argc, char *argv[]) {
171 return generate_key(argv[1]);
172 } else if (argc == 4 && !strcmp(argv[1], "-convert")) {
173 return convert_x509(argv[2], argv[3]);