-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkey_utils.cc
368 lines (306 loc) · 12.4 KB
/
key_utils.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
// Copyright 2019 Ant Group Co., Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "yacl/crypto/key_utils.h"
#include <cstddef>
#include "yacl/crypto/ossl_wrappers.h"
#include "yacl/io/stream/file_io.h"
namespace yacl::crypto {
namespace {
constexpr unsigned kSecondsInDay = 24 * 60 * 60;
constexpr int kX509Version = 3;
constexpr std::array<std::string_view, 6> kX509SubjectFields = {
/* country */ "C",
/* state or province name */ "ST",
/* locality*/ "L",
/* organization */ "O",
/* organizational unit */ "OU",
/* common name */ "CN"};
inline void AddX509Extension(X509* cert, int nid, char* value) {
X509V3_CTX ctx;
/* This sets the 'context' of the extensions. */
/* No configuration database */
X509V3_set_ctx_nodb(&ctx);
// self signed
X509V3_set_ctx(&ctx, cert, cert, nullptr, nullptr, 0);
auto ex =
ossl::UniqueX509Ext(X509V3_EXT_nconf_nid(nullptr, &ctx, nid, value));
YACL_ENFORCE(ex != nullptr);
X509_add_ext(cert, ex.get(), -1);
}
// convert bio file to yacl::Buffer
inline Buffer BioToBuf(const ossl::UniqueBio& bio) {
int num_bytes = BIO_pending(bio.get());
YACL_ENFORCE_GT(num_bytes, 0, "BIO_pending failed.");
// read data from bio
Buffer out(num_bytes);
YACL_ENFORCE_EQ(BIO_read(bio.get(), out.data(), num_bytes), num_bytes,
"Read bio failed.");
return out;
}
inline Buffer LoadBufFromFile(const std::string& file_path) {
io::FileInputStream in(file_path);
Buffer buf(static_cast<int64_t>(in.GetLength()));
in.Read(buf.data(), buf.size());
return buf;
}
// this function steals the ownership of key buffer, this is an intended
// behaviour
inline void ExportBufToFile(Buffer&& buf, const std::string& file_path) {
io::FileOutputStream out(file_path);
out.Write(buf.data(), buf.size());
}
} // namespace
// -------------------
// Key Pair Generation
// -------------------
ossl::UniquePkey GenRsaKeyPair(unsigned rsa_keylen) {
/* EVP_RSA_gen() may be set deprecated by later version of OpenSSL */
EVP_PKEY* pkey = EVP_PKEY_new(); // placeholder
ossl::UniquePkeyCtx ctx(
EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, /* engine = default */ nullptr));
YACL_ENFORCE(ctx != nullptr);
OSSL_RET_1(EVP_PKEY_keygen_init(ctx.get()));
// set key length bits
OSSL_RET_1(EVP_PKEY_CTX_set_rsa_keygen_bits(ctx.get(), rsa_keylen));
// generate keys
OSSL_RET_1(EVP_PKEY_keygen(ctx.get(), &pkey));
return ossl::UniquePkey(pkey);
}
ossl::UniquePkey GenSm2KeyPair() {
EVP_PKEY* pkey = EVP_PKEY_new(); // placeholder
ossl::UniquePkeyCtx ctx(
EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, /* engine = default */ nullptr));
YACL_ENFORCE(ctx != nullptr);
OSSL_RET_1(EVP_PKEY_keygen_init(ctx.get()));
// in openssl version > 3.0, you should set algorithm object id explicitly
// constexpr std::string_view kDefaultSm2Id = {"1234567812345678"};
// EVP_PKEY_CTX_set1_id(ctx.get(), kDefaultSm2Id.data(),
// kDefaultSm2Id.size());
// generate keys
OSSL_RET_1(EVP_PKEY_keygen(ctx.get(), &pkey));
return ossl::UniquePkey(pkey);
}
std::pair<Buffer, Buffer> GenRsaKeyPairToPemBuf(unsigned rsa_keygen) {
auto pkey = GenRsaKeyPair(rsa_keygen);
Buffer pk_buf = ExportPublicKeyToPemBuf(pkey);
Buffer sk_buf = ExportSecretKeyToPemBuf(pkey);
return {pk_buf, sk_buf};
}
std::pair<Buffer, Buffer> GenSm2KeyPairToPemBuf() {
auto pkey = GenSm2KeyPair();
Buffer pk_buf = ExportPublicKeyToPemBuf(pkey);
Buffer sk_buf = ExportSecretKeyToPemBuf(pkey);
return {pk_buf, sk_buf};
}
// -------------------
// Load Any Format Key
// -------------------
// load pem from buffer
ossl::UniquePkey LoadKeyFromBuf(ByteContainerView buf) {
// load the buffer to bio
ossl::UniqueBio bio(BIO_new_mem_buf(buf.data(), buf.size()));
// create pkey
EVP_PKEY* pkey = nullptr;
// decoding, see
// https://www.openssl.org/docs/manmaster/man7/provider-decoder.html
auto decoder = ossl::UniqueDecoder(OSSL_DECODER_CTX_new_for_pkey(
/* EVP_PKEY */ &pkey,
/* pkey format */ nullptr, // any format
/* pkey structure */ nullptr, // any structure
/* pkey type */ nullptr, // any type
/* selection */ 0, // auto detect
/* OSSL_LIB_CTX */ nullptr, /* probquery */ nullptr));
YACL_ENFORCE(decoder != nullptr, "no decoder found");
OSSL_RET_1(OSSL_DECODER_from_bio(decoder.get(), bio.get()));
// OSSL_RET_1(OSSL_DECODER_from_bio(decoder.get(), bio.get()));
return ossl::UniquePkey(pkey);
}
ossl::UniquePkey LoadKeyFromFile(const std::string& file_path) {
return LoadKeyFromBuf(LoadBufFromFile(file_path));
}
// ------------------
// Export PEM Key
// ------------------
// export public key to pem
Buffer ExportPublicKeyToPemBuf(
/* public key */ const ossl::UniquePkey& pkey) {
ossl::UniqueBio bio(BIO_new(BIO_s_mem())); // create an empty bio
// export public key to bio
OSSL_RET_1(PEM_write_bio_PUBKEY(bio.get(), pkey.get()));
return BioToBuf(bio);
}
void ExportPublicKeyToPemFile(const ossl::UniquePkey& pkey,
const std::string& file_path) {
ExportBufToFile(ExportPublicKeyToPemBuf(pkey), file_path);
}
// export secret key to pem (different from publick key since they may not have
// the same structure)
Buffer ExportSecretKeyToPemBuf(
/* secret key */ const ossl::UniquePkey& pkey) {
ossl::UniqueBio bio(BIO_new(BIO_s_mem())); // create an empty bio
// export secret key to bio using PKCS#8 private key format, equivalent to
// PEM_write_bio_PKCS8PrivateKey()
OSSL_RET_1(PEM_write_bio_PKCS8PrivateKey(bio.get(), pkey.get(), nullptr,
nullptr, 0, nullptr, nullptr));
return BioToBuf(bio);
}
void ExportSecretKeyToPemBuf(const ossl::UniquePkey& pkey,
const std::string& file_path) {
ExportBufToFile(ExportSecretKeyToPemBuf(pkey), file_path);
}
// ------------------
// Export DER Key
// ------------------
// export public key to pem
Buffer ExportPublicKeyToDerBuf(
/* public key */ const ossl::UniquePkey& pkey) {
ossl::UniqueBio bio(BIO_new(BIO_s_mem())); // create an empty bio
// export pkey to bio
auto encoder = ossl::UniqueEncoder(OSSL_ENCODER_CTX_new_for_pkey(
pkey.get(),
/* selection: pk and params */ EVP_PKEY_PUBLIC_KEY,
/* format */ "DER",
/* RFC 5280: X.509 structure */ "SubjectPublicKeyInfo", nullptr));
YACL_ENFORCE(encoder != nullptr, "no encoder found");
OSSL_RET_1(OSSL_ENCODER_to_bio(encoder.get(), bio.get()));
return BioToBuf(bio);
}
void ExportPublicKeyToDerFile(const ossl::UniquePkey& pkey,
const std::string& file_path) {
ExportBufToFile(ExportPublicKeyToPemBuf(pkey), file_path);
}
// export secret key to pem (different from publick key since they may not have
// the same structure)
Buffer ExportSecretKeyToDerBuf(
/* secret key */ const ossl::UniquePkey& pkey) {
ossl::UniqueBio bio(BIO_new(BIO_s_mem())); // create an empty bio
// export pkey to bio
auto encoder = ossl::UniqueEncoder(OSSL_ENCODER_CTX_new_for_pkey(
pkey.get(),
/* selection: pk, sk and params */ EVP_PKEY_KEYPAIR,
/* format */ "DER",
/* RFC 5208: PKCS#8 structure */ "PrivateKeyInfo", nullptr));
YACL_ENFORCE(encoder != nullptr, "no encoder found");
OSSL_RET_1(OSSL_ENCODER_to_bio(encoder.get(), bio.get()));
return BioToBuf(bio);
}
void ExportSecretKeyToDerFile(const ossl::UniquePkey& pkey,
const std::string& file_path) {
ExportBufToFile(ExportSecretKeyToPemBuf(pkey), file_path);
}
// -------------------------------
// Gen/Load/Export X509 Certificate
// -------------------------------
ossl::UniqueX509 MakeX509Cert(
/* issuer's pk */ const ossl::UniquePkey& pk,
/* issuer's sk */ const ossl::UniquePkey& sk,
/* subjects info */
const std::unordered_map<std::string, std::string>& subjects,
/* time */ unsigned days, HashAlgorithm hash) {
YACL_ENFORCE(hash == HashAlgorithm::SHA256 || hash == HashAlgorithm::SM3);
// ++++++++++++++++++++++++++++++
// Generate X509 cert (version 3)
// ++++++++++++++++++++++++++++++
// * Certificate
// ** Version Number
// ** Serial Number
// ** Signature Algorithm ID <= auto filled
// ** Issuer Name
// ** Validity period
// ** Not Before
// ** Not After
// ** Subject name
// ** Subject Public Key Info <= auto filled
// ** Public Key Algorithm <= auto filled
// ** Subject Public Key
// ** Issuer ossl::Unique Identifier (optional)
// ** Subject ossl::Unique Identifier (optional)
// ** Extensions (optional)
// ** ...
// * Certificate Signature Algorithm
// * Certificate Signature
// ++++++++++++++++++++++++++++++
ossl::UniqueX509 x509(X509_new());
/* version */
OSSL_RET_1(X509_set_version(x509.get(), kX509Version));
/* Serial Number */
// YACL_ENFORCE(X509_set_serialNumber(x509.get(),
// ASN1_INTEGER_set_int64(FastRandU64()) == 1); // set random serial number
/* time */
X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
X509_gmtime_adj(X509_get_notAfter(x509.get()), days * kSecondsInDay);
/* setup subject strings */
// X509_get_subject_name() returns the subject name of certificate x. The
// returned value is an internal pointer which MUST NOT be freed.
// see: https://www.openssl.org/docs/man1.1.1/man3/X509_get_subject_name.html
X509_NAME* name = X509_get_subject_name(x509.get());
YACL_ENFORCE(name != nullptr);
for (const auto& field : kX509SubjectFields) {
auto it = subjects.find(std::string(field));
YACL_ENFORCE(it != subjects.end(), "Cannot find subject field {}.", field);
OSSL_RET_1(X509_NAME_add_entry_by_txt(
name, it->first.c_str(), MBSTRING_ASC,
reinterpret_cast<const unsigned char*>(it->second.c_str()), -1, -1, 0));
}
/* issuer = subject since this cert is self-signed */
OSSL_RET_1(X509_set_issuer_name(x509.get(), name));
/* fill cert with rsa public key */
X509_set_pubkey(x509.get(), pk.get());
AddX509Extension(x509.get(), NID_basic_constraints, (char*)"CA:TRUE");
AddX509Extension(x509.get(), NID_subject_key_identifier, (char*)"hash");
/* self signing with digest algorithm */
auto sign_bytes = X509_sign(x509.get(), sk.get(),
ossl::FetchEvpMd(ToString(hash)).get());
YACL_ENFORCE(sign_bytes > 0, "Perform self-signing failed.");
return x509;
}
// load x509 certificate from buffer
ossl::UniqueX509 LoadX509Cert(ByteContainerView buf) {
// load the buffer to bio
ossl::UniqueBio bio(BIO_new_mem_buf(buf.data(), buf.size()));
// bio to x509 [warning]: this may be made deprecated in the future version of
// OpenSSL, it is recommended to use OSSL_ENCODER and OSSL_DECODER instead.
auto cert = ossl::UniqueX509(
PEM_read_bio_X509(/* bio */ bio.get(), /* x509 ptr (optional) */ nullptr,
/* password */ nullptr, /* addition */ nullptr));
YACL_ENFORCE(cert != nullptr, "No X509 from cert generated.");
return cert;
}
ossl::UniqueX509 LoadX509CertFromFile(const std::string& file_path) {
return LoadX509Cert(LoadBufFromFile(file_path));
}
// load x509 pk from buffer
ossl::UniquePkey LoadX509CertPublicKeyFromBuf(ByteContainerView buf) {
auto x509 = LoadX509Cert(buf);
auto pkey = ossl::UniquePkey(X509_get_pubkey(x509.get()));
YACL_ENFORCE(pkey != nullptr,
"Error when reading public key in X509 certificate.");
return pkey; // public key only
}
ossl::UniquePkey LoadX509CertPublicKeyFromFile(
const std::string& file_path) {
return LoadX509CertPublicKeyFromBuf(LoadBufFromFile(file_path));
}
// export x509 certificate to buffer
Buffer ExportX509CertToBuf(const ossl::UniqueX509& x509) {
ossl::UniqueBio bio(BIO_new(BIO_s_mem())); // create an empty bio
// export certificate to bio
OSSL_RET_1(PEM_write_bio_X509(bio.get(), x509.get()));
return BioToBuf(bio);
}
void ExportX509CertToFile(const ossl::UniqueX509& x509,
const std::string& file_path) {
ExportBufToFile(ExportX509CertToBuf(x509), file_path);
}
} // namespace yacl::crypto