1 /* Copyright (c) 2017, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
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 std::unique_ptr<uint8_t[]> sig(new 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