blob: 0c61817424cfdd0e85a13c5d22604ae527fae461 [file] [log] [blame]
Yingdi Yu202a2e92015-07-12 16:49:25 -07001/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2/**
3 * Copyright (c) 2013-2016 Regents of the University of California.
4 *
5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
6 *
7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
8 * terms of the GNU Lesser General Public License as published by the Free Software
9 * Foundation, either version 3 of the License, or (at your option) any later version.
10 *
11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
13 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
14 *
15 * You should have received copies of the GNU General Public License and GNU Lesser
16 * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
17 * <http://www.gnu.org/licenses/>.
18 *
19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
20 */
21
22#include "private-key.hpp"
23#include "buffer-source.hpp"
24#include "stream-source.hpp"
25#include "base64-encode.hpp"
26#include "base64-decode.hpp"
27#include "stream-sink.hpp"
28#include "../../encoding/buffer-stream.hpp"
29#include "../detail/openssl-helper.hpp"
30#include "../key-params.hpp"
31
32#include <string.h>
33
34#define ENSURE_PRIVATE_KEY_LOADED(key) \
35 do { \
36 if (key == nullptr) \
37 BOOST_THROW_EXCEPTION(Error("Private key has not been loaded yet")); \
38 } while (false)
39
40namespace ndn {
41namespace security {
42namespace transform {
43
44class PrivateKey::Impl
45{
46public:
47 Impl()
48 : key(nullptr)
49 {
50 }
51
52 ~Impl()
53 {
54 EVP_PKEY_free(key);
55 }
56
57public:
58 EVP_PKEY* key;
59};
60
61PrivateKey::PrivateKey()
62 : m_impl(new Impl)
63{
64}
65
66PrivateKey::~PrivateKey() = default;
67
68void
69PrivateKey::loadPkcs1(const uint8_t* buf, size_t size)
70{
71 detail::Bio mem(BIO_s_mem());
72 BIO_write(mem.get(), buf, size);
73
74 d2i_PrivateKey_bio(mem.get(), &m_impl->key);
75
76 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
77}
78
79void
80PrivateKey::loadPkcs1(std::istream& is)
81{
82 OBufferStream os;
83 streamSource(is) >> streamSink(os);
84 this->loadPkcs1(os.buf()->buf(), os.buf()->size());
85}
86
87void
88PrivateKey::loadPkcs1Base64(const uint8_t* buf, size_t size)
89{
90 OBufferStream os;
91 bufferSource(buf, size) >> base64Decode() >> streamSink(os);
92 this->loadPkcs1(os.buf()->buf(), os.buf()->size());
93}
94
95void
96PrivateKey::loadPkcs1Base64(std::istream& is)
97{
98 OBufferStream os;
99 streamSource(is) >> base64Decode() >> streamSink(os);
100 this->loadPkcs1(os.buf()->buf(), os.buf()->size());
101}
102
103void
104PrivateKey::loadPkcs8(const uint8_t* buf, size_t size, const char* pw, size_t pwLen)
105{
106 BOOST_ASSERT(std::strlen(pw) == pwLen);
107
108 detail::Bio mem(BIO_s_mem());
109 BIO_write(mem.get(), buf, size);
110
111 m_impl->key = d2i_PKCS8PrivateKey_bio(mem.get(), &m_impl->key, nullptr, const_cast<char*>(pw));
112
113 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
114}
115
116static inline int
117passwordCallback(char* buf, int size, int rwflag, void* u)
118{
119 auto cb = reinterpret_cast<PrivateKey::PasswordCallback*>(u);
120 return (*cb)(buf, size, rwflag);
121}
122
123void
124PrivateKey::loadPkcs8(const uint8_t* buf, size_t size, PasswordCallback pwCallback)
125{
126 OpenSSL_add_all_algorithms();
127 detail::Bio mem(BIO_s_mem());
128 BIO_write(mem.get(), buf, size);
129
130 if (pwCallback)
131 m_impl->key = d2i_PKCS8PrivateKey_bio(mem.get(), &m_impl->key, passwordCallback, &pwCallback);
132 else
133 m_impl->key = d2i_PKCS8PrivateKey_bio(mem.get(), &m_impl->key, nullptr, nullptr);
134
135 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
136}
137
138void
139PrivateKey::loadPkcs8(std::istream& is, const char* pw, size_t pwLen)
140{
141 OBufferStream os;
142 streamSource(is) >> streamSink(os);
143 this->loadPkcs8(os.buf()->buf(), os.buf()->size(), pw, pwLen);
144}
145
146void
147PrivateKey::loadPkcs8(std::istream& is, PasswordCallback pwCallback)
148{
149 OBufferStream os;
150 streamSource(is) >> streamSink(os);
151 this->loadPkcs8(os.buf()->buf(), os.buf()->size(), pwCallback);
152}
153
154void
155PrivateKey::loadPkcs8Base64(const uint8_t* buf, size_t size, const char* pw, size_t pwLen)
156{
157 OBufferStream os;
158 bufferSource(buf, size) >> base64Decode() >> streamSink(os);
159 this->loadPkcs8(os.buf()->buf(), os.buf()->size(), pw, pwLen);
160}
161
162void
163PrivateKey::loadPkcs8Base64(const uint8_t* buf, size_t size, PasswordCallback pwCallback)
164{
165 OBufferStream os;
166 bufferSource(buf, size) >> base64Decode() >> streamSink(os);
167 this->loadPkcs8(os.buf()->buf(), os.buf()->size(), pwCallback);
168}
169
170void
171PrivateKey::loadPkcs8Base64(std::istream& is, const char* pw, size_t pwLen)
172{
173 OBufferStream os;
174 streamSource(is) >> base64Decode() >> streamSink(os);
175 this->loadPkcs8(os.buf()->buf(), os.buf()->size(), pw, pwLen);
176}
177
178void
179PrivateKey::loadPkcs8Base64(std::istream& is, PasswordCallback pwCallback)
180{
181 OBufferStream os;
182 streamSource(is) >> base64Decode() >> streamSink(os);
183 this->loadPkcs8(os.buf()->buf(), os.buf()->size(), pwCallback);
184}
185
186void
187PrivateKey::savePkcs1(std::ostream& os) const
188{
189 bufferSource(*this->toPkcs1()) >> streamSink(os);
190}
191
192void
193PrivateKey::savePkcs1Base64(std::ostream& os) const
194{
195 bufferSource(*this->toPkcs1()) >> base64Encode() >> streamSink(os);
196}
197
198void
199PrivateKey::savePkcs8(std::ostream& os, const char* pw, size_t pwLen) const
200{
201 bufferSource(*this->toPkcs8(pw, pwLen)) >> streamSink(os);
202}
203
204void
205PrivateKey::savePkcs8(std::ostream& os, PasswordCallback pwCallback) const
206{
207 bufferSource(*this->toPkcs8(pwCallback)) >> streamSink(os);
208}
209
210void
211PrivateKey::savePkcs8Base64(std::ostream& os, const char* pw, size_t pwLen) const
212{
213 bufferSource(*this->toPkcs8(pw, pwLen)) >> base64Encode() >> streamSink(os);
214}
215
216void
217PrivateKey::savePkcs8Base64(std::ostream& os, PasswordCallback pwCallback) const
218{
219 bufferSource(*this->toPkcs8(pwCallback)) >> base64Encode() >> streamSink(os);
220}
221
222ConstBufferPtr
223PrivateKey::derivePublicKey() const
224{
225 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
226
227 uint8_t* pkcs8 = nullptr;
228 int len = i2d_PUBKEY(m_impl->key, &pkcs8);
229
230 if (len <= 0)
231 BOOST_THROW_EXCEPTION(Error("Failed to derive public key"));
232
233 auto result = make_shared<Buffer>(pkcs8, len);
234 OPENSSL_free(pkcs8);
235
236 return result;
237}
238
239ConstBufferPtr
240PrivateKey::decrypt(const uint8_t* cipherText, size_t cipherLen) const
241{
242 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
243
244 switch (EVP_PKEY_type(m_impl->key->type)) {
245 case EVP_PKEY_RSA:
246 return rsaDecrypt(cipherText, cipherLen);
247 default:
248 BOOST_THROW_EXCEPTION(Error("Decryption is not supported for this key type"));
249 }
250}
251
252void*
253PrivateKey::getEvpPkey() const
254{
255 return m_impl->key;
256}
257
258ConstBufferPtr
259PrivateKey::toPkcs1() const
260{
261 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
262
263 OpenSSL_add_all_algorithms();
264 detail::Bio mem(BIO_s_mem());
265 int ret = i2d_PrivateKey_bio(mem.get(), m_impl->key);
266 if (ret != 1)
267 BOOST_THROW_EXCEPTION(Error("Cannot convert key into PKCS1 format"));
268
269 int len8 = BIO_pending(mem.get());
270 auto buffer = make_shared<Buffer>(len8);
271 BIO_read(mem.get(), buffer->buf(), len8);
272
273 return buffer;
274}
275
276ConstBufferPtr
277PrivateKey::toPkcs8(const char* pw, size_t pwLen) const
278{
279 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
280
281 BOOST_ASSERT(std::strlen(pw) == pwLen);
282
283 OpenSSL_add_all_algorithms();
284 detail::Bio mem(BIO_s_mem());
285 int ret = i2d_PKCS8PrivateKey_bio(mem.get(), m_impl->key, EVP_des_cbc(),
286 const_cast<char*>(pw), pwLen, nullptr, nullptr);
287 if (ret != 1)
288 BOOST_THROW_EXCEPTION(Error("Cannot convert key into PKCS8 format"));
289
290 int len8 = BIO_pending(mem.get());
291 auto buffer = make_shared<Buffer>(len8);
292 BIO_read(mem.get(), buffer->buf(), len8);
293
294 return buffer;
295}
296
297ConstBufferPtr
298PrivateKey::toPkcs8(PasswordCallback pwCallback) const
299{
300 ENSURE_PRIVATE_KEY_LOADED(m_impl->key);
301
302 OpenSSL_add_all_algorithms();
303 detail::Bio mem(BIO_s_mem());
304 int ret = i2d_PKCS8PrivateKey_bio(mem.get(), m_impl->key, EVP_des_cbc(),
305 nullptr, 0,
306 passwordCallback, &pwCallback);
307 if (ret != 1)
308 BOOST_THROW_EXCEPTION(Error("Cannot convert key into PKCS8 format"));
309
310 int len8 = BIO_pending(mem.get());
311 auto buffer = make_shared<Buffer>(len8);
312 BIO_read(mem.get(), buffer->buf(), len8);
313
314 return buffer;
315}
316
317ConstBufferPtr
318PrivateKey::rsaDecrypt(const uint8_t* cipherText, size_t cipherLen) const
319{
320 detail::EvpPkeyCtx ctx(m_impl->key);
321
322 if (EVP_PKEY_decrypt_init(ctx.get()) <= 0)
323 BOOST_THROW_EXCEPTION(Error("Failed to initialize decryption context"));
324
325 if (EVP_PKEY_CTX_set_rsa_padding(ctx.get(), RSA_PKCS1_OAEP_PADDING) <= 0)
326 BOOST_THROW_EXCEPTION(Error("Failed to set padding"));
327
328 size_t outlen = 0;
329 // Determine buffer length
330 if (EVP_PKEY_decrypt(ctx.get(), nullptr, &outlen, cipherText, cipherLen) <= 0)
331 BOOST_THROW_EXCEPTION(Error("Failed to estimate output length"));
332
333 auto out = make_shared<Buffer>(outlen);
334
335 if (EVP_PKEY_decrypt(ctx.get(), out->buf(), &outlen, cipherText, cipherLen) <= 0)
336 BOOST_THROW_EXCEPTION(Error("Failed to decrypt cipher text"));
337
338 out->resize(outlen);
339 return out;
340}
341
342static unique_ptr<PrivateKey>
343generateRsaKey(uint32_t keySize)
344{
345 detail::EvpPkeyCtx kctx(EVP_PKEY_RSA);
346
347 int ret = EVP_PKEY_keygen_init(kctx.get());
348 if (ret != 1)
349 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate RSA key"));
350
351 ret = EVP_PKEY_CTX_set_rsa_keygen_bits(kctx.get(), keySize);
352 if (ret != 1)
353 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate RSA key"));
354
355 detail::EvpPkey key;
356 ret = EVP_PKEY_keygen(kctx.get(), &key);
357 if (ret != 1)
358 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate RSA key"));
359
360 detail::Bio mem(BIO_s_mem());
361 i2d_PrivateKey_bio(mem.get(), key.get());
362 int len = BIO_pending(mem.get());
363 Buffer buffer(len);
364 BIO_read(mem.get(), buffer.buf(), len);
365
366 auto privateKey = make_unique<PrivateKey>();
367 privateKey->loadPkcs1(buffer.buf(), buffer.size());
368
369 return privateKey;
370}
371
372static unique_ptr<PrivateKey>
373generateEcKey(uint32_t keySize)
374{
375 detail::EvpPkeyCtx ctx(EVP_PKEY_EC);
376
377 int ret = EVP_PKEY_paramgen_init(ctx.get());
378 if (ret != 1)
379 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate EC key"));
380
381 switch (keySize) {
382 case 256:
383 ret = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_X9_62_prime256v1);
384 break;
385 case 384:
386 ret = EVP_PKEY_CTX_set_ec_paramgen_curve_nid(ctx.get(), NID_secp384r1);
387 break;
388 default:
389 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate EC key"));
390 }
391 if (ret != 1)
392 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate EC key"));
393
394 detail::EvpPkey params;
395 ret = EVP_PKEY_paramgen(ctx.get(), &params);
396 if (ret != 1)
397 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate EC key"));
398
399 detail::EvpPkeyCtx kctx(params.get());
400 ret = EVP_PKEY_keygen_init(kctx.get());
401 if (ret != 1)
402 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate EC key"));
403
404 detail::EvpPkey key;
405 ret = EVP_PKEY_keygen(kctx.get(), &key);
406 if (ret != 1)
407 BOOST_THROW_EXCEPTION(PrivateKey::Error("Fail to generate EC key"));
408
409 detail::Bio mem(BIO_s_mem());
410 i2d_PrivateKey_bio(mem.get(), key.get());
411 int len = BIO_pending(mem.get());
412 Buffer buffer(len);
413 BIO_read(mem.get(), buffer.buf(), len);
414
415 auto privateKey = make_unique<PrivateKey>();
416 privateKey->loadPkcs1(buffer.buf(), buffer.size());
417
418 return privateKey;
419}
420
421unique_ptr<PrivateKey>
422generatePrivateKey(const KeyParams& keyParams)
423{
424 switch (keyParams.getKeyType()) {
425 case KeyType::RSA: {
426 const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(keyParams);
427 return generateRsaKey(rsaParams.getKeySize());
428 }
429 case KeyType::EC: {
430 const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(keyParams);
431 return generateEcKey(ecdsaParams.getKeySize());
432 }
433 default:
434 BOOST_THROW_EXCEPTION(std::invalid_argument("Unsupported asymmetric key type"));
435 }
436}
437
438} // namespace transform
439} // namespace security
440} // namespace ndn