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
6  * in compliance with the License. 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 <gtest/gtest.h>
18 
19 #include <resolv.h>
20 
21 #include <adb/crypto/rsa_2048_key.h>
22 #include <android-base/logging.h>
23 #include <android-base/strings.h>
24 #include <crypto_utils/android_pubkey.h>
25 #include <openssl/err.h>
26 #include <openssl/rsa.h>
27 #include <openssl/sha.h>
28 
29 namespace adb {
30 namespace crypto {
31 
32 TEST(RSA2048Key, Smoke) {
33     auto rsa_2048 = CreateRSA2048Key();
34     EXPECT_NE(rsa_2048, std::nullopt);
35     EXPECT_EQ(rsa_2048->GetKeyType(), adb::proto::KeyType::RSA_2048);
36     ASSERT_NE(rsa_2048->GetEvpPkey(), nullptr);
37 
38     // The public key string format is expected to be: "<pub_key> <host_name>"
39     std::string pub_key_plus_name;
40     auto* rsa = EVP_PKEY_get0_RSA(rsa_2048->GetEvpPkey());
41     ASSERT_TRUE(CalculatePublicKey(&pub_key_plus_name, rsa));
42     std::vector<std::string> split = android::base::Split(std::string(pub_key_plus_name), " \t");
43     EXPECT_EQ(split.size(), 2);
44 
45     LOG(INFO) << "pub_key=[" << pub_key_plus_name << "]";
46 
47     std::string pemString = Key::ToPEMString(rsa_2048->GetEvpPkey());
48     ASSERT_FALSE(pemString.empty());
49 
50     // Try to sign something and decode it.
51     const char token[SHA_DIGEST_LENGTH] = "abcdefghij123456789";
52     std::vector<uint8_t> sig(RSA_size(rsa));
53     unsigned sig_len;
54     EXPECT_EQ(RSA_sign(NID_sha1, reinterpret_cast<const uint8_t*>(token), sizeof(token), sig.data(),
55                        &sig_len, rsa),
56               1);
57     sig.resize(sig_len);
58 
59     {
60         uint8_t keybuf[ANDROID_PUBKEY_ENCODED_SIZE + 1];
61         const std::string& pubkey = split[0];
62         ASSERT_EQ(b64_pton(pubkey.c_str(), keybuf, sizeof(keybuf)), ANDROID_PUBKEY_ENCODED_SIZE);
63         RSA* key = nullptr;
64         ASSERT_TRUE(android_pubkey_decode(keybuf, ANDROID_PUBKEY_ENCODED_SIZE, &key));
65         EXPECT_EQ(RSA_verify(NID_sha1, reinterpret_cast<const uint8_t*>(token), sizeof(token),
66                              sig.data(), sig.size(), key),
67                   1);
68         RSA_free(key);
69     }
70 }
71 
72 }  // namespace crypto
73 }  // namespace adb
74