1 /*
2 * Copyright (C) 2019 The Android Open Source 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 #include "adb/crypto/rsa_2048_key.h"
18
19 #include <android-base/logging.h>
20 #include <crypto_utils/android_pubkey.h>
21 #include <openssl/bn.h>
22 #include <openssl/rsa.h>
23 #include <sysdeps/env.h>
24
25 namespace adb {
26 namespace crypto {
27
CalculatePublicKey(std::string * out,RSA * private_key)28 bool CalculatePublicKey(std::string* out, RSA* private_key) {
29 uint8_t binary_key_data[ANDROID_PUBKEY_ENCODED_SIZE];
30 if (!android_pubkey_encode(private_key, binary_key_data, sizeof(binary_key_data))) {
31 LOG(ERROR) << "Failed to convert to public key";
32 return false;
33 }
34
35 size_t expected_length;
36 if (!EVP_EncodedLength(&expected_length, sizeof(binary_key_data))) {
37 LOG(ERROR) << "Public key too large to base64 encode";
38 return false;
39 }
40
41 out->resize(expected_length);
42 size_t actual_length = EVP_EncodeBlock(reinterpret_cast<uint8_t*>(out->data()), binary_key_data,
43 sizeof(binary_key_data));
44 out->resize(actual_length);
45 out->append(" ");
46 out->append(sysdeps::GetLoginNameUTF8());
47 out->append("@");
48 out->append(sysdeps::GetHostNameUTF8());
49 return true;
50 }
51
CreateRSA2048Key()52 std::optional<Key> CreateRSA2048Key() {
53 bssl::UniquePtr<EVP_PKEY> pkey(EVP_PKEY_new());
54 bssl::UniquePtr<BIGNUM> exponent(BN_new());
55 bssl::UniquePtr<RSA> rsa(RSA_new());
56 if (!pkey || !exponent || !rsa) {
57 LOG(ERROR) << "Failed to allocate key";
58 return std::nullopt;
59 }
60
61 BN_set_word(exponent.get(), RSA_F4);
62 RSA_generate_key_ex(rsa.get(), 2048, exponent.get(), nullptr);
63 EVP_PKEY_set1_RSA(pkey.get(), rsa.get());
64
65 return std::optional<Key>{Key(std::move(pkey), adb::proto::KeyType::RSA_2048)};
66 }
67
68 } // namespace crypto
69 } // namespace adb
70