1 // Copyright 2017 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include <map>
16 #include <vector>
17 
18 #include <openssl/bio.h>
19 #include <openssl/evp.h>
20 #include <openssl/pem.h>
21 
22 #include "internal.h"
23 
24 
25 static const struct argument kArguments[] = {
26     {"-key", kRequiredArgument, "The private key, in PEM format, to sign with"},
27     {"-digest", kOptionalArgument, "The digest algorithm to use"},
28     {"", kOptionalArgument, ""},
29 };
30 
Sign(const std::vector<std::string> & args)31 bool Sign(const std::vector<std::string> &args) {
32   std::map<std::string, std::string> args_map;
33   if (!ParseKeyValueArguments(&args_map, args, kArguments)) {
34     PrintUsage(kArguments);
35     return false;
36   }
37 
38   // Load the private key.
39   bssl::UniquePtr<BIO> bio(BIO_new(BIO_s_file()));
40   if (!bio || !BIO_read_filename(bio.get(), args_map["-key"].c_str())) {
41     return false;
42   }
43   bssl::UniquePtr<EVP_PKEY> key(
44       PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));
45   if (!key) {
46     return false;
47   }
48 
49   const EVP_MD *md = nullptr;
50   if (args_map.count("-digest")) {
51     md = EVP_get_digestbyname(args_map["-digest"].c_str());
52     if (md == nullptr) {
53       fprintf(stderr, "Unknown digest algorithm: %s\n",
54               args_map["-digest"].c_str());
55       return false;
56     }
57   }
58 
59   bssl::ScopedEVP_MD_CTX ctx;
60   if (!EVP_DigestSignInit(ctx.get(), nullptr, md, nullptr, key.get())) {
61     return false;
62   }
63 
64   std::vector<uint8_t> data;
65   if (!ReadAll(&data, stdin)) {
66     fprintf(stderr, "Error reading input.\n");
67     return false;
68   }
69 
70   size_t sig_len = EVP_PKEY_size(key.get());
71   auto sig = std::make_unique<uint8_t[]>(sig_len);
72   if (!EVP_DigestSign(ctx.get(), sig.get(), &sig_len, data.data(),
73                       data.size())) {
74     return false;
75   }
76 
77   if (fwrite(sig.get(), 1, sig_len, stdout) != sig_len) {
78     fprintf(stderr, "Error writing signature.\n");
79     return false;
80   }
81 
82   return true;
83 }
84