File: opensslsigners.cc

package info (click to toggle)
pdns-recursor 4.8.8-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 9,620 kB
  • sloc: cpp: 95,714; javascript: 20,651; sh: 4,679; makefile: 652; xml: 37
file content (1241 lines) | stat: -rw-r--r-- 40,911 bytes parent folder | download | duplicates (2)
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
/*
 * This file is part of PowerDNS or dnsdist.
 * Copyright -- PowerDNS.COM B.V. and its contributors
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of version 2 of the GNU General Public License as
 * published by the Free Software Foundation.
 *
 * In addition, for the avoidance of any doubt, permission is granted to
 * link this program with OpenSSL and to (re)distribute the binaries
 * produced as the result of such linking.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <openssl/obj_mac.h>
#ifdef HAVE_LIBCRYPTO_ECDSA
#include <openssl/ecdsa.h>
#endif
#if defined(HAVE_LIBCRYPTO_ED25519) || defined(HAVE_LIBCRYPTO_ED448)
#include <openssl/evp.h>
#endif
#include <openssl/bn.h>
#include <openssl/sha.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/opensslv.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include "opensslsigners.hh"
#include "dnssecinfra.hh"
#include "dnsseckeeper.hh"

#if (OPENSSL_VERSION_NUMBER < 0x1010000fL || (defined LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2090100fL)
/* OpenSSL < 1.1.0 needs support for threading/locking in the calling application. */

#include "lock.hh"
static std::vector<std::mutex> openssllocks;

extern "C" {
static void openssl_pthreads_locking_callback(int mode, int type, const char *file, int line)
{
  if (mode & CRYPTO_LOCK) {
    openssllocks.at(type).lock();

  } else {
    openssllocks.at(type).unlock();
  }
}

static unsigned long openssl_pthreads_id_callback(void)
{
  return (unsigned long)pthread_self();
}
}

void openssl_thread_setup()
{
  openssllocks = std::vector<std::mutex>(CRYPTO_num_locks());
  CRYPTO_set_id_callback(&openssl_pthreads_id_callback);
  CRYPTO_set_locking_callback(&openssl_pthreads_locking_callback);
}

void openssl_thread_cleanup()
{
  CRYPTO_set_locking_callback(nullptr);
  openssllocks.clear();
}

#ifndef HAVE_RSA_GET0_KEY
/* those symbols are defined in LibreSSL 2.7.0+ */
/* compat helpers. These DO NOT do any of the checking that the libssl 1.1 functions do. */
static inline void RSA_get0_key(const RSA* rsakey, const BIGNUM** n, const BIGNUM** e, const BIGNUM** d) {
  *n = rsakey->n;
  *e = rsakey->e;
  *d = rsakey->d;
}

static inline int RSA_set0_key(RSA* rsakey, BIGNUM* n, BIGNUM* e, BIGNUM* d) {
  if (n) {
    BN_clear_free(rsakey->n);
    rsakey->n = n;
  }
  if (e) {
    BN_clear_free(rsakey->e);
    rsakey->e = e;
  }
  if (d) {
    BN_clear_free(rsakey->d);
    rsakey->d = d;
  }
  return 1;
}

static inline void RSA_get0_factors(const RSA* rsakey, const BIGNUM** p, const BIGNUM** q) {
  *p = rsakey->p;
  *q = rsakey->q;
}

static inline int RSA_set0_factors(RSA* rsakey, BIGNUM* p, BIGNUM* q) {
  BN_clear_free(rsakey->p);
  rsakey->p = p;
  BN_clear_free(rsakey->q);
  rsakey->q = q;
  return 1;
}

static inline void RSA_get0_crt_params(const RSA* rsakey, const BIGNUM** dmp1, const BIGNUM** dmq1, const BIGNUM** iqmp) {
  *dmp1 = rsakey->dmp1;
  *dmq1 = rsakey->dmq1;
  *iqmp = rsakey->iqmp;
}

static inline int RSA_set0_crt_params(RSA* rsakey, BIGNUM* dmp1, BIGNUM* dmq1, BIGNUM* iqmp) {
  BN_clear_free(rsakey->dmp1);
  rsakey->dmp1 = dmp1;
  BN_clear_free(rsakey->dmq1);
  rsakey->dmq1 = dmq1;
  BN_clear_free(rsakey->iqmp);
  rsakey->iqmp = iqmp;
  return 1;
}

#ifdef HAVE_LIBCRYPTO_ECDSA
static inline void ECDSA_SIG_get0(const ECDSA_SIG* signature, const BIGNUM** pr, const BIGNUM** ps) {
  *pr = signature->r;
  *ps = signature->s;
}

static inline int ECDSA_SIG_set0(ECDSA_SIG* signature, BIGNUM* pr, BIGNUM* ps) {
  BN_clear_free(signature->r);
  BN_clear_free(signature->s);
  signature->r = pr;
  signature->s = ps;
  return 1;
}
#endif /* HAVE_LIBCRYPTO_ECDSA */

#endif /* HAVE_RSA_GET0_KEY */

#else
void openssl_thread_setup() {}
void openssl_thread_cleanup() {}
#endif


/* seeding PRNG */

void openssl_seed()
{
  std::string entropy;
  entropy.reserve(1024);

  unsigned int r;
  for(int i=0; i<1024; i+=4) {
    r=dns_random(0xffffffff);
    entropy.append((const char*)&r, 4);
  }

  RAND_seed((const unsigned char*)entropy.c_str(), 1024);
}


class OpenSSLRSADNSCryptoKeyEngine : public DNSCryptoKeyEngine
{
public:
  explicit OpenSSLRSADNSCryptoKeyEngine(unsigned int algo): DNSCryptoKeyEngine(algo), d_key(std::unique_ptr<RSA, void(*)(RSA*)>(nullptr, RSA_free))
  {
    int ret = RAND_status();
    if (ret != 1) {
      throw runtime_error(getName()+" insufficient entropy");
    }
  }

  ~OpenSSLRSADNSCryptoKeyEngine()
  {
  }

  string getName() const override { return "OpenSSL RSA"; }
  int getBits() const override { return RSA_size(d_key.get()) << 3; }

  void create(unsigned int bits) override;

  /**
   * \brief Creates an RSA key engine from a PEM file.
   *
   * Receives an open file handle with PEM contents and creates an RSA key
   * engine.
   *
   * \param[in] drc Key record contents to be populated.
   *
   * \param[in] filename Only used for providing filename information in error
   * messages.
   *
   * \param[in] fp An open file handle to a file containing RSA PEM contents.
   *
   * \return An RSA key engine populated with the contents of the PEM file.
   */
  void createFromPEMFile(DNSKEYRecordContent& drc, const std::string& filename, std::FILE& fp) override;

  /**
   * \brief Writes this key's contents to a file.
   *
   * Receives an open file handle and writes this key's contents to the
   * file.
   *
   * \param[in] fp An open file handle for writing.
   *
   * \exception std::runtime_error In case of OpenSSL errors.
   */
  void convertToPEM(std::FILE& fp) const override;

  storvector_t convertToISCVector() const override;
  std::string hash(const std::string& hash) const override;
  std::string sign(const std::string& hash) const override;
  bool verify(const std::string& hash, const std::string& signature) const override;
  std::string getPubKeyHash() const override;
  std::string getPublicKeyString() const override;
  std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>parse(std::map<std::string, std::string>& stormap, const std::string& key) const;
  void fromISCMap(DNSKEYRecordContent& drc, std::map<std::string, std::string>& stormap) override;
  void fromPublicKeyString(const std::string& content) override;
  bool checkKey(vector<string> *errorMessages) const override;

  static std::unique_ptr<DNSCryptoKeyEngine> maker(unsigned int algorithm)
  {
    return make_unique<OpenSSLRSADNSCryptoKeyEngine>(algorithm);
  }

private:
  static int hashSizeToKind(size_t hashSize);

  std::unique_ptr<RSA, void(*)(RSA*)> d_key;
};


void OpenSSLRSADNSCryptoKeyEngine::create(unsigned int bits)
{
  // When changing the bitsizes, also edit them in ::checkKey
  if ((d_algorithm == DNSSECKeeper::RSASHA1 || d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1) && (bits < 512 || bits > 4096)) {
    /* RFC3110 */
    throw runtime_error(getName()+" RSASHA1 key generation failed for invalid bits size " + std::to_string(bits));
  }
  if (d_algorithm == DNSSECKeeper::RSASHA256 && (bits < 512 || bits > 4096)) {
    /* RFC5702 */
    throw runtime_error(getName()+" RSASHA256 key generation failed for invalid bits size " + std::to_string(bits));
  }
  if (d_algorithm == DNSSECKeeper::RSASHA512 && (bits < 1024 || bits > 4096)) {
    /* RFC5702 */
    throw runtime_error(getName()+" RSASHA512 key generation failed for invalid bits size " + std::to_string(bits));
  }

  auto e = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_new(), BN_clear_free);
  if (!e) {
    throw runtime_error(getName()+" key generation failed, unable to allocate e");
  }

  /* RSA_F4 is a public exponent value of 65537 */
  int res = BN_set_word(e.get(), RSA_F4);

  if (res == 0) {
    throw runtime_error(getName()+" key generation failed while setting e");
  }

  auto key = std::unique_ptr<RSA, void(*)(RSA*)>(RSA_new(), RSA_free);
  if (!key) {
    throw runtime_error(getName()+" allocation of key structure failed");
  }

  res = RSA_generate_key_ex(key.get(), bits, e.get(), nullptr);
  if (res == 0) {
    throw runtime_error(getName()+" key generation failed");
  }

  d_key = std::move(key);
}

void OpenSSLRSADNSCryptoKeyEngine::createFromPEMFile(DNSKEYRecordContent& drc, const std::string& filename, std::FILE& fp) {
  drc.d_algorithm = d_algorithm;
  d_key = std::unique_ptr<RSA, decltype(&RSA_free)>(PEM_read_RSAPrivateKey(&fp, nullptr, nullptr, nullptr), &RSA_free);
  if (d_key == nullptr) {
    throw runtime_error(getName() + ": Failed to read private key from PEM file `" + filename + "`");
  }
}

void OpenSSLRSADNSCryptoKeyEngine::convertToPEM(std::FILE& fp) const {
  auto ret = PEM_write_RSAPrivateKey(&fp, d_key.get(), nullptr, nullptr, 0, nullptr, nullptr);
  if (ret == 0) {
    throw runtime_error(getName() + ": Could not convert private key to PEM");
  }
}

DNSCryptoKeyEngine::storvector_t OpenSSLRSADNSCryptoKeyEngine::convertToISCVector() const
{
  storvector_t storvect;
  typedef vector<pair<string, const BIGNUM*> > outputs_t;
  outputs_t outputs;
  const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp;
  RSA_get0_key(d_key.get(), &n, &e, &d);
  RSA_get0_factors(d_key.get(), &p, &q);
  RSA_get0_crt_params(d_key.get(), &dmp1, &dmq1, &iqmp);
  outputs.emplace_back("Modulus", n);
  outputs.emplace_back("PublicExponent", e);
  outputs.emplace_back("PrivateExponent", d);
  outputs.emplace_back("Prime1", p);
  outputs.emplace_back("Prime2", q);
  outputs.emplace_back("Exponent1", dmp1);
  outputs.emplace_back("Exponent2", dmq1);
  outputs.emplace_back("Coefficient", iqmp);

  string algorithm=std::to_string(d_algorithm);
  switch(d_algorithm) {
    case DNSSECKeeper::RSASHA1:
    case DNSSECKeeper::RSASHA1NSEC3SHA1:
      algorithm += " (RSASHA1)";
      break;
    case DNSSECKeeper::RSASHA256:
      algorithm += " (RSASHA256)";
      break;
    case DNSSECKeeper::RSASHA512:
      algorithm += " (RSASHA512)";
      break;
    default:
      algorithm += " (?)";
  }
  storvect.emplace_back("Algorithm", algorithm);

  for(const outputs_t::value_type& value :  outputs) {
    std::string tmp;
    tmp.resize(BN_num_bytes(value.second));
    int len = BN_bn2bin(value.second, reinterpret_cast<unsigned char*>(&tmp.at(0)));
    if (len >= 0) {
      tmp.resize(len);
      storvect.emplace_back(value.first, tmp);
    }
  }

  return storvect;
}


std::string OpenSSLRSADNSCryptoKeyEngine::hash(const std::string& orig) const
{
  if (d_algorithm == DNSSECKeeper::RSASHA1 || d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1) {
    unsigned char l_hash[SHA_DIGEST_LENGTH];
    SHA1((unsigned char*) orig.c_str(), orig.length(), l_hash);
    return string((char*) l_hash, sizeof(l_hash));
  }
  else if (d_algorithm == DNSSECKeeper::RSASHA256) {
    unsigned char l_hash[SHA256_DIGEST_LENGTH];
    SHA256((unsigned char*) orig.c_str(), orig.length(), l_hash);
    return string((char*) l_hash, sizeof(l_hash));
  }
  else if (d_algorithm == DNSSECKeeper::RSASHA512) {
    unsigned char l_hash[SHA512_DIGEST_LENGTH];
    SHA512((unsigned char*) orig.c_str(), orig.length(), l_hash);
    return string((char*) l_hash, sizeof(l_hash));
  }

  throw runtime_error(getName()+" does not support hash operation for algorithm "+std::to_string(d_algorithm));
}

int OpenSSLRSADNSCryptoKeyEngine::hashSizeToKind(const size_t hashSize)
{
  switch(hashSize) {
    case SHA_DIGEST_LENGTH:
      return NID_sha1;
    case SHA256_DIGEST_LENGTH:
      return NID_sha256;
    case SHA384_DIGEST_LENGTH:
      return NID_sha384;
    case SHA512_DIGEST_LENGTH:
      return NID_sha512;
    default:
      throw runtime_error("OpenSSL RSA does not handle hash of size " + std::to_string(hashSize));
  }
}

std::string OpenSSLRSADNSCryptoKeyEngine::sign(const std::string& msg) const
{
  string l_hash = this->hash(msg);
  int hashKind = hashSizeToKind(l_hash.size());
  std::string signature;
  signature.resize(RSA_size(d_key.get()));
  unsigned int signatureLen = 0;

  int res = RSA_sign(hashKind, reinterpret_cast<unsigned char*>(&l_hash.at(0)), l_hash.length(), reinterpret_cast<unsigned char*>(&signature.at(0)), &signatureLen, d_key.get());
  if (res != 1) {
    throw runtime_error(getName()+" failed to generate signature");
  }

  signature.resize(signatureLen);
  return signature;
}


bool OpenSSLRSADNSCryptoKeyEngine::verify(const std::string& msg, const std::string& signature) const
{
  string l_hash = this->hash(msg);
  int hashKind = hashSizeToKind(l_hash.size());

  int ret = RSA_verify(hashKind, (const unsigned char*)l_hash.c_str(), l_hash.length(), (unsigned char*)signature.c_str(), signature.length(), d_key.get());

  return (ret == 1);
}


std::string OpenSSLRSADNSCryptoKeyEngine::getPubKeyHash() const
{
  const BIGNUM *n, *e, *d;
  RSA_get0_key(d_key.get(), &n, &e, &d);
  std::vector<unsigned char> tmp;
  tmp.resize(std::max(BN_num_bytes(e), BN_num_bytes(n)));
  unsigned char l_hash[SHA_DIGEST_LENGTH];
  SHA_CTX ctx;

  int res = SHA1_Init(&ctx);

  if (res != 1) {
    throw runtime_error(getName()+" failed to init hash context for generating the public key hash");
  }

  int len = BN_bn2bin(e, tmp.data());
  res = SHA1_Update(&ctx, tmp.data(), len);
  if (res != 1) {
    throw runtime_error(getName()+" failed to update hash context for generating the public key hash");
  }

  len = BN_bn2bin(n, tmp.data());
  res = SHA1_Update(&ctx, tmp.data(), len);
  if (res != 1) {
    throw runtime_error(getName()+" failed to update hash context for generating the public key hash");
  }

  res = SHA1_Final(l_hash, &ctx);
  if (res != 1) {
    throw runtime_error(getName()+" failed to finish hash context for generating the public key hash");
  }

  return string((char*)l_hash, sizeof(l_hash));
}


std::string OpenSSLRSADNSCryptoKeyEngine::getPublicKeyString() const
{
  const BIGNUM *n, *e, *d;
  RSA_get0_key(d_key.get(), &n, &e, &d);
  string keystring;
  std::string tmp;
  tmp.resize(std::max(BN_num_bytes(e), BN_num_bytes(n)));

  int len = BN_bn2bin(e, reinterpret_cast<unsigned char*>(&tmp.at(0)));
  if (len < 255) {
    keystring.assign(1, (char) (unsigned int) len);
  } else {
    keystring.assign(1, 0);
    uint16_t tempLen = len;
    tempLen = htons(tempLen);
    keystring.append((char*)&tempLen, 2);
  }
  keystring.append(&tmp.at(0), len);

  len = BN_bn2bin(n, reinterpret_cast<unsigned char*>(&tmp.at(0)));
  keystring.append(&tmp.at(0), len);

  return keystring;
}


std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>OpenSSLRSADNSCryptoKeyEngine::parse(std::map<std::string, std::string>& stormap, const std::string& key) const
{
  const std::string& v = stormap.at(key);
  auto n = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_bin2bn(reinterpret_cast<const unsigned char*>(v.data()), v.length(), nullptr), BN_clear_free);

  if (!n) {
    throw runtime_error(getName() + " parsing of " + key + " failed");
  }
  return n;
}

void OpenSSLRSADNSCryptoKeyEngine::fromISCMap(DNSKEYRecordContent& drc, std::map<std::string, std::string>& stormap)
{
  auto key = std::unique_ptr<RSA, void(*)(RSA*)>(RSA_new(), RSA_free);
  if (!key) {
    throw runtime_error(getName() + " allocation of key structure failed");
  }

  auto n = parse(stormap, "modulus");
  auto e = parse(stormap, "publicexponent");
  auto d = parse(stormap, "privateexponent");

  auto p = parse(stormap, "prime1");
  auto q = parse(stormap, "prime2");

  auto dmp1 = parse(stormap, "exponent1");
  auto dmq1 = parse(stormap, "exponent2");
  auto iqmp = parse(stormap, "coefficient");

  pdns::checked_stoi_into(drc.d_algorithm, stormap["algorithm"]);

  if (drc.d_algorithm != d_algorithm) {
    throw runtime_error(getName() + " tried to feed an algorithm " + std::to_string(drc.d_algorithm) + " to a " + std::to_string(d_algorithm) + " key");
  }
  // Everything OK, we're releasing ownership since the RSA_* functions want it
  RSA_set0_key(key.get(), n.release(), e.release(), d.release());
  RSA_set0_factors(key.get(), p.release(), q.release());
  RSA_set0_crt_params(key.get(), dmp1.release(), dmq1.release(), iqmp.release());

  d_key = std::move(key);
}

bool OpenSSLRSADNSCryptoKeyEngine::checkKey(vector<string> *errorMessages) const
{
  bool retval = true;
  // When changing the bitsizes, also edit them in ::create
  if ((d_algorithm == DNSSECKeeper::RSASHA1 || d_algorithm == DNSSECKeeper::RSASHA1NSEC3SHA1 || d_algorithm == DNSSECKeeper::RSASHA256) && (getBits() < 512 || getBits()> 4096)) {
    retval = false;
    if (errorMessages != nullptr) {
      errorMessages->push_back("key is " + std::to_string(getBits()) + " bytes, should be between 512 and 4096");
    }
  }
  if (d_algorithm == DNSSECKeeper::RSASHA512 && (getBits() < 1024 || getBits() > 4096)) {
    retval = false;
    if (errorMessages != nullptr) {
      errorMessages->push_back("key is " + std::to_string(getBits()) + " bytes, should be between 1024 and 4096");
    }
  }
  if (RSA_check_key(d_key.get()) != 1) {
    retval = false;
    if (errorMessages != nullptr) {
      auto errmsg = ERR_reason_error_string(ERR_get_error());
      if (errmsg == nullptr) {
        errmsg = "Unknown OpenSSL error";
      }
      errorMessages->push_back(errmsg);
    }
  }
  return retval;
}

void OpenSSLRSADNSCryptoKeyEngine::fromPublicKeyString(const std::string& input)
{
  string exponent, modulus;
  const size_t inputLen = input.length();
  const unsigned char* raw = (const unsigned char*)input.c_str();

  if (inputLen < 1) {
    throw runtime_error(getName()+" invalid input size for the public key");
  }

  if (raw[0] != 0) {
    const size_t exponentSize = raw[0];
    if (inputLen < (exponentSize + 2)) {
      throw runtime_error(getName()+" invalid input size for the public key");
    }
    exponent = input.substr(1, exponentSize);
    modulus = input.substr(exponentSize + 1);
  } else {
    if (inputLen < 3) {
      throw runtime_error(getName()+" invalid input size for the public key");
    }
    const size_t exponentSize = raw[1]*0xff + raw[2];
    if (inputLen < (exponentSize + 4)) {
      throw runtime_error(getName()+" invalid input size for the public key");
    }
    exponent = input.substr(3, exponentSize);
    modulus = input.substr(exponentSize + 3);
  }

  auto key = std::unique_ptr<RSA, void(*)(RSA*)>(RSA_new(), RSA_free);
  if (!key) {
    throw runtime_error(getName()+" allocation of key structure failed");
  }

  auto e = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_bin2bn((unsigned char*)exponent.c_str(), exponent.length(), nullptr), BN_clear_free);
  if (!e) {
    throw runtime_error(getName()+" error loading e value of public key");
  }
  auto n = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_bin2bn((unsigned char*)modulus.c_str(), modulus.length(), nullptr), BN_clear_free);
  if (!n) {
    throw runtime_error(getName()+" error loading n value of public key");
  }

  RSA_set0_key(key.get(), n.release(), e.release(), nullptr);
  d_key = std::move(key);
}

#ifdef HAVE_LIBCRYPTO_ECDSA
class OpenSSLECDSADNSCryptoKeyEngine : public DNSCryptoKeyEngine
{
public:
  explicit OpenSSLECDSADNSCryptoKeyEngine(unsigned int algo) : DNSCryptoKeyEngine(algo), d_eckey(std::unique_ptr<EC_KEY, void(*)(EC_KEY*)>(EC_KEY_new(), EC_KEY_free)), d_ecgroup(std::unique_ptr<EC_GROUP, void(*)(EC_GROUP*)>(nullptr, EC_GROUP_clear_free))
  {

    int ret = RAND_status();
    if (ret != 1) {
      throw runtime_error(getName()+" insufficient entropy");
    }

    if (!d_eckey) {
      throw runtime_error(getName()+" allocation of key structure failed");
    }

    if(d_algorithm == 13) {
      d_ecgroup = std::unique_ptr<EC_GROUP, void(*)(EC_GROUP*)>(EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1), EC_GROUP_clear_free);
      d_len = 32;
    } else if (d_algorithm == 14) {
      d_ecgroup = std::unique_ptr<EC_GROUP, void(*)(EC_GROUP*)>(EC_GROUP_new_by_curve_name(NID_secp384r1), EC_GROUP_clear_free);
      d_len = 48;
    } else {
      throw runtime_error(getName()+" unknown algorithm "+std::to_string(d_algorithm));
    }

    if (!d_ecgroup) {
      throw runtime_error(getName()+" allocation of group structure failed");
    }

    ret = EC_KEY_set_group(d_eckey.get(), d_ecgroup.get());
    if (ret != 1) {
      throw runtime_error(getName()+" setting key group failed");
    }
  }

  ~OpenSSLECDSADNSCryptoKeyEngine()
  {
  }

  string getName() const override { return "OpenSSL ECDSA"; }
  int getBits() const override { return d_len << 3; }

  void create(unsigned int bits) override;

  /**
   * \brief Creates an ECDSA key engine from a PEM file.
   *
   * Receives an open file handle with PEM contents and creates an ECDSA
   * key engine.
   *
   * \param[in] drc Key record contents to be populated.
   *
   * \param[in] filename Only used for providing filename information
   * in error messages.
   *
   * \param[in] fp An open file handle to a file containing ECDSA PEM
   * contents.
   *
   * \return An ECDSA key engine populated with the contents of the PEM
   * file.
   */
  void createFromPEMFile(DNSKEYRecordContent& drc, const std::string& filename, std::FILE& fp) override;

  /**
   * \brief Writes this key's contents to a file.
   *
   * Receives an open file handle and writes this key's contents to the
   * file.
   *
   * \param[in] fp An open file handle for writing.
   *
   * \exception std::runtime_error In case of OpenSSL errors.
   */
  void convertToPEM(std::FILE& fp) const override;

  storvector_t convertToISCVector() const override;
  std::string hash(const std::string& hash) const override;
  std::string sign(const std::string& hash) const override;
  bool verify(const std::string& hash, const std::string& signature) const override;
  std::string getPubKeyHash() const override;
  std::string getPublicKeyString() const override;
  void fromISCMap(DNSKEYRecordContent& drc, std::map<std::string, std::string>& stormap) override;
  void fromPublicKeyString(const std::string& content) override;
  bool checkKey(vector<string> *errorMessages) const override;

  static std::unique_ptr<DNSCryptoKeyEngine> maker(unsigned int algorithm)
  {
    return make_unique<OpenSSLECDSADNSCryptoKeyEngine>(algorithm);
  }

private:
  unsigned int d_len;

  std::unique_ptr<EC_KEY, void(*)(EC_KEY*)> d_eckey;
  std::unique_ptr<EC_GROUP, void(*)(EC_GROUP*)> d_ecgroup;
};


void OpenSSLECDSADNSCryptoKeyEngine::create(unsigned int bits)
{
  if (bits >> 3 != d_len) {
    throw runtime_error(getName()+" unknown key length of "+std::to_string(bits)+" bits requested");
  }

  int res = EC_KEY_generate_key(d_eckey.get());
  if (res == 0) {
    throw runtime_error(getName()+" key generation failed");
  }

  EC_KEY_set_asn1_flag(d_eckey.get(), OPENSSL_EC_NAMED_CURVE);
}

void OpenSSLECDSADNSCryptoKeyEngine::createFromPEMFile(DNSKEYRecordContent& drc, const string& filename, std::FILE& fp)
{
  drc.d_algorithm = d_algorithm;
  d_eckey = std::unique_ptr<EC_KEY, decltype(&EC_KEY_free)>(PEM_read_ECPrivateKey(&fp, nullptr, nullptr, nullptr), &EC_KEY_free);
  if (d_eckey == nullptr) {
    throw runtime_error(getName() + ": Failed to read private key from PEM file `" + filename + "`");
  }

  int ret = EC_KEY_set_group(d_eckey.get(), d_ecgroup.get());
  if (ret != 1) {
    throw runtime_error(getName() + " setting key group failed");
  }

  const BIGNUM* privateKeyBN = EC_KEY_get0_private_key(d_eckey.get());

  auto pub_key = std::unique_ptr<EC_POINT, void (*)(EC_POINT*)>(EC_POINT_new(d_ecgroup.get()), EC_POINT_free);
  if (!pub_key) {
    throw runtime_error(getName() + " allocation of public key point failed");
  }

  ret = EC_POINT_mul(d_ecgroup.get(), pub_key.get(), privateKeyBN, nullptr, nullptr, nullptr);
  if (ret != 1) {
    throw runtime_error(getName() + " computing public key from private failed");
  }

  ret = EC_KEY_set_public_key(d_eckey.get(), pub_key.get());
  if (ret != 1) {
    ERR_print_errors_fp(stderr);
    throw runtime_error(getName() + " setting public key failed");
  }

  EC_KEY_set_asn1_flag(d_eckey.get(), OPENSSL_EC_NAMED_CURVE);
}

void OpenSSLECDSADNSCryptoKeyEngine::convertToPEM(std::FILE& fp) const
{
  auto ret = PEM_write_ECPrivateKey(&fp, d_eckey.get(), nullptr, nullptr, 0, nullptr, nullptr);
  if (ret == 0) {
    throw runtime_error(getName() + ": Could not convert private key to PEM");
  }
}

DNSCryptoKeyEngine::storvector_t OpenSSLECDSADNSCryptoKeyEngine::convertToISCVector() const
{
  storvector_t storvect;
  string algorithm;

  if(d_algorithm == 13)
    algorithm = "13 (ECDSAP256SHA256)";
  else if(d_algorithm == 14)
    algorithm = "14 (ECDSAP384SHA384)";
  else
    algorithm = " ? (?)";

  storvect.emplace_back("Algorithm", algorithm);

  const BIGNUM *key = EC_KEY_get0_private_key(d_eckey.get());
  if (key == nullptr) {
    throw runtime_error(getName()+" private key not set");
  }

  std::string tmp;
  tmp.resize(BN_num_bytes(key));
  int len = BN_bn2bin(key, reinterpret_cast<unsigned char*>(&tmp.at(0)));

  string prefix;
  if (d_len - len)
    prefix.append(d_len - len, 0x00);

  storvect.emplace_back("PrivateKey", prefix + tmp);

  return storvect;
}


std::string OpenSSLECDSADNSCryptoKeyEngine::hash(const std::string& orig) const
{
  if(getBits() == 256) {
    unsigned char l_hash[SHA256_DIGEST_LENGTH];
    SHA256((unsigned char*) orig.c_str(), orig.length(), l_hash);
    return string((char*)l_hash, sizeof(l_hash));
  }
  else if(getBits() == 384) {
    unsigned char l_hash[SHA384_DIGEST_LENGTH];
    SHA384((unsigned char*) orig.c_str(), orig.length(), l_hash);
    return string((char*)l_hash, sizeof(l_hash));
  }

  throw runtime_error(getName()+" does not support a hash size of "+std::to_string(getBits())+" bits");
}


std::string OpenSSLECDSADNSCryptoKeyEngine::sign(const std::string& msg) const
{
  string l_hash = this->hash(msg);

  auto signature = std::unique_ptr<ECDSA_SIG, void(*)(ECDSA_SIG*)>(ECDSA_do_sign((unsigned char*) l_hash.c_str(), l_hash.length(), d_eckey.get()), ECDSA_SIG_free);
  if (!signature) {
    throw runtime_error(getName()+" failed to generate signature");
  }

  string ret;
  std::string tmp;
  tmp.resize(d_len);

  const BIGNUM *pr, *ps;
  ECDSA_SIG_get0(signature.get(), &pr, &ps);
  int len = BN_bn2bin(pr, reinterpret_cast<unsigned char*>(&tmp.at(0)));
  if (d_len - len)
    ret.append(d_len - len, 0x00);
  ret.append(&tmp.at(0), len);

  len = BN_bn2bin(ps, reinterpret_cast<unsigned char*>(&tmp.at(0)));
  if (d_len - len)
    ret.append(d_len - len, 0x00);
  ret.append(&tmp.at(0), len);

  return ret;
}


bool OpenSSLECDSADNSCryptoKeyEngine::verify(const std::string& msg, const std::string& signature) const
{
  if (signature.length() != (d_len * 2)) {
    throw runtime_error(getName()+" invalid signature size "+std::to_string(signature.length()));
  }

  string l_hash = this->hash(msg);

  auto sig = std::unique_ptr<ECDSA_SIG, void(*)(ECDSA_SIG*)>(ECDSA_SIG_new(), ECDSA_SIG_free);
  if (!sig) {
    throw runtime_error(getName()+" allocation of signature structure failed");
  }

  auto r = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_bin2bn((unsigned char*) signature.c_str(), d_len, nullptr), BN_clear_free);
  auto s = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_bin2bn((unsigned char*) signature.c_str() + d_len, d_len, nullptr), BN_clear_free);
  if (!r || !s) {
    throw runtime_error(getName()+" invalid signature");
  }

  ECDSA_SIG_set0(sig.get(), r.release(), s.release());
  int ret = ECDSA_do_verify((unsigned char*) l_hash.c_str(), l_hash.length(), sig.get(), d_eckey.get());

  if (ret == -1){
    throw runtime_error(getName()+" verify error");
  }

  return (ret == 1);
}


std::string OpenSSLECDSADNSCryptoKeyEngine::getPubKeyHash() const
{
  string pubKey = getPublicKeyString();
  unsigned char l_hash[SHA_DIGEST_LENGTH];
  SHA1((unsigned char*) pubKey.c_str(), pubKey.length(), l_hash);
  return string((char*) l_hash, sizeof(l_hash));
}


std::string OpenSSLECDSADNSCryptoKeyEngine::getPublicKeyString() const
{
  std::string binaryPoint;
  binaryPoint.resize((d_len * 2) + 1);

  int ret = EC_POINT_point2oct(d_ecgroup.get(), EC_KEY_get0_public_key(d_eckey.get()), POINT_CONVERSION_UNCOMPRESSED, reinterpret_cast<unsigned char*>(&binaryPoint.at(0)), binaryPoint.size(), nullptr);
  if (ret == 0) {
    throw runtime_error(getName()+" exporting point to binary failed");
  }

  /* we skip the first byte as the other backends use
     raw field elements, as opposed to the format described in
     SEC1: "2.3.3 Elliptic-Curve-Point-to-Octet-String Conversion" */
  binaryPoint.erase(0, 1);
  return binaryPoint;
}


void OpenSSLECDSADNSCryptoKeyEngine::fromISCMap(DNSKEYRecordContent& drc, std::map<std::string, std::string>& stormap)
{
  drc.d_algorithm = atoi(stormap["algorithm"].c_str());

  if (drc.d_algorithm != d_algorithm) {
    throw runtime_error(getName()+" tried to feed an algorithm "+std::to_string(drc.d_algorithm)+" to a "+std::to_string(d_algorithm)+" key");
  }

  string privateKey = stormap["privatekey"];

  auto prv_key = std::unique_ptr<BIGNUM, void(*)(BIGNUM*)>(BN_bin2bn((unsigned char*) privateKey.c_str(), privateKey.length(), nullptr), BN_clear_free);
  if (!prv_key) {
    throw runtime_error(getName()+" reading private key from binary failed");
  }

  int ret = EC_KEY_set_private_key(d_eckey.get(), prv_key.get());
  if (ret != 1) {
    throw runtime_error(getName()+" setting private key failed");
  }

  auto pub_key = std::unique_ptr<EC_POINT, void(*)(EC_POINT*)>(EC_POINT_new(d_ecgroup.get()), EC_POINT_free);
  if (!pub_key) {
    throw runtime_error(getName()+" allocation of public key point failed");
  }

  ret = EC_POINT_mul(d_ecgroup.get(), pub_key.get(), prv_key.get(), nullptr, nullptr, nullptr);
  if (ret != 1) {
    throw runtime_error(getName()+" computing public key from private failed");
  }

  ret = EC_KEY_set_public_key(d_eckey.get(), pub_key.get());
  if (ret != 1) {
    throw runtime_error(getName()+" setting public key failed");
  }

  EC_KEY_set_asn1_flag(d_eckey.get(), OPENSSL_EC_NAMED_CURVE);
}

bool OpenSSLECDSADNSCryptoKeyEngine::checkKey(vector<string> *errorMessages) const
{
  bool retval = true;
  if (EC_KEY_check_key(d_eckey.get()) != 1) {
    retval = false;
    if (errorMessages != nullptr) {
      auto errmsg = ERR_reason_error_string(ERR_get_error());
      if (errmsg == nullptr) {
        errmsg = "Unknown OpenSSL error";
      }
      errorMessages->push_back(errmsg);
    }
  }
  return retval;
}

void OpenSSLECDSADNSCryptoKeyEngine::fromPublicKeyString(const std::string& input)
{
  /* uncompressed point, from SEC1:
     "2.3.4 Octet-String-to-Elliptic-Curve-Point Conversion" */
  string ecdsaPoint= "\x04";
  ecdsaPoint.append(input);

  auto pub_key = std::unique_ptr<EC_POINT, void(*)(EC_POINT*)>(EC_POINT_new(d_ecgroup.get()), EC_POINT_free);
  if (!pub_key) {
    throw runtime_error(getName()+" allocation of point structure failed");
  }

  int ret = EC_POINT_oct2point(d_ecgroup.get(), pub_key.get(), (unsigned char*) ecdsaPoint.c_str(), ecdsaPoint.length(), nullptr);
  if (ret != 1) {
    throw runtime_error(getName()+" reading ECP point from binary failed");
  }

  ret = EC_KEY_set_private_key(d_eckey.get(), nullptr);
  if (ret == 1) {
    throw runtime_error(getName()+" setting private key failed");
  }

  ret = EC_KEY_set_public_key(d_eckey.get(), pub_key.get());
  if (ret != 1) {
    throw runtime_error(getName()+" setting public key failed");
  }
}
#endif

#ifdef HAVE_LIBCRYPTO_EDDSA
class OpenSSLEDDSADNSCryptoKeyEngine : public DNSCryptoKeyEngine
{
public:
  explicit OpenSSLEDDSADNSCryptoKeyEngine(unsigned int algo) : DNSCryptoKeyEngine(algo), d_edkey(std::unique_ptr<EVP_PKEY, void(*)(EVP_PKEY*)>(nullptr, EVP_PKEY_free))
  {

    int ret = RAND_status();
    if (ret != 1) {
      throw runtime_error(getName()+" insufficient entropy");
    }

#ifdef HAVE_LIBCRYPTO_ED25519
    if(d_algorithm == 15) {
      d_len = 32;
      d_id = NID_ED25519;
    }
#endif
#ifdef HAVE_LIBCRYPTO_ED448
    if (d_algorithm == 16) {
      d_len = 57;
      d_id = NID_ED448;
    }
#endif
    if (d_len == 0) {
      throw runtime_error(getName()+" unknown algorithm "+std::to_string(d_algorithm));
    }
  }

  ~OpenSSLEDDSADNSCryptoKeyEngine()
  {
  }

  string getName() const override { return "OpenSSL EDDSA"; }
  int getBits() const override { return d_len << 3; }

  void create(unsigned int bits) override;

  /**
   * \brief Creates an EDDSA key engine from a PEM file.
   *
   * Receives an open file handle with PEM contents and creates an EDDSA
   * key engine.
   *
   * \param[in] drc Key record contents to be populated.
   *
   * \param[in] filename Only used for providing filename information in
   * error messages.
   *
   * \param[in] fp An open file handle to a file containing EDDSA PEM
   * contents.
   *
   * \return An EDDSA key engine populated with the contents of the PEM
   * file.
   */
  void createFromPEMFile(DNSKEYRecordContent& drc, const std::string& filename, std::FILE& fp) override;

  /**
   * \brief Writes this key's contents to a file.
   *
   * Receives an open file handle and writes this key's contents to the
   * file.
   *
   * \param[in] fp An open file handle for writing.
   *
   * \exception std::runtime_error In case of OpenSSL errors.
   */
  void convertToPEM(std::FILE& fp) const override;

  storvector_t convertToISCVector() const override;
  std::string sign(const std::string& msg) const override;
  bool verify(const std::string& msg, const std::string& signature) const override;
  std::string getPubKeyHash() const override;
  std::string getPublicKeyString() const override;
  void fromISCMap(DNSKEYRecordContent& drc, std::map<std::string, std::string>& stormap) override;
  void fromPublicKeyString(const std::string& content) override;
  bool checkKey(vector<string> *errorMessages) const override;

  static std::unique_ptr<DNSCryptoKeyEngine> maker(unsigned int algorithm)
  {
    return make_unique<OpenSSLEDDSADNSCryptoKeyEngine>(algorithm);
  }

private:
  size_t d_len{0};
  int d_id{0};

  std::unique_ptr<EVP_PKEY, void(*)(EVP_PKEY*)> d_edkey;
};

bool OpenSSLEDDSADNSCryptoKeyEngine::checkKey(vector<string> *errorMessages) const
{
  return (d_edkey ? true : false);
}

void OpenSSLEDDSADNSCryptoKeyEngine::create(unsigned int bits)
{
  auto pctx = std::unique_ptr<EVP_PKEY_CTX, void(*)(EVP_PKEY_CTX*)>(EVP_PKEY_CTX_new_id(d_id, nullptr), EVP_PKEY_CTX_free);
  if (!pctx) {
    throw runtime_error(getName()+" context initialization failed");
  }
  if (EVP_PKEY_keygen_init(pctx.get()) < 1) {
    throw runtime_error(getName()+" keygen initialization failed");
  }
  EVP_PKEY* newKey = nullptr;
  if (EVP_PKEY_keygen(pctx.get(), &newKey) < 1) {
    throw runtime_error(getName()+" key generation failed");
  }
  d_edkey = std::unique_ptr<EVP_PKEY, void(*)(EVP_PKEY*)>(newKey, EVP_PKEY_free);
}

void OpenSSLEDDSADNSCryptoKeyEngine::createFromPEMFile(DNSKEYRecordContent& drc, const string& filename, std::FILE& fp)
{
  drc.d_algorithm = d_algorithm;
  d_edkey = std::unique_ptr<EVP_PKEY, decltype(&EVP_PKEY_free)>(PEM_read_PrivateKey(&fp, nullptr, nullptr, nullptr), &EVP_PKEY_free);
  if (d_edkey == nullptr) {
    throw runtime_error(getName() + ": Failed to read private key from PEM file `" + filename + "`");
  }
}

void OpenSSLEDDSADNSCryptoKeyEngine::convertToPEM(std::FILE& fp) const
{
  auto ret = PEM_write_PrivateKey(&fp, d_edkey.get(), nullptr, nullptr, 0, nullptr, nullptr);
  if (ret == 0) {
    throw runtime_error(getName() + ": Could not convert private key to PEM");
  }
}

DNSCryptoKeyEngine::storvector_t OpenSSLEDDSADNSCryptoKeyEngine::convertToISCVector() const
{
  storvector_t storvect;
  string algorithm;

#ifdef HAVE_LIBCRYPTO_ED25519
  if(d_algorithm == 15) {
    algorithm = "15 (ED25519)";
  }
#endif
#ifdef HAVE_LIBCRYPTO_ED448
  if(d_algorithm == 16) {
    algorithm = "16 (ED448)";
  }
#endif
  if (algorithm.empty()) {
    algorithm = " ? (?)";
  }

  storvect.emplace_back("Algorithm", algorithm);

  string buf;
  size_t len = d_len;
  buf.resize(len);
  if (EVP_PKEY_get_raw_private_key(d_edkey.get(), reinterpret_cast<unsigned char*>(&buf.at(0)), &len) < 1) {
    throw runtime_error(getName() + " Could not get private key from d_edkey");
  }
  storvect.emplace_back("PrivateKey", buf);
  return storvect;
}

std::string OpenSSLEDDSADNSCryptoKeyEngine::sign(const std::string& msg) const
{
  auto mdctx = std::unique_ptr<EVP_MD_CTX, void(*)(EVP_MD_CTX*)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
  if (!mdctx) {
    throw runtime_error(getName()+" MD context initialization failed");
  }
  if(EVP_DigestSignInit(mdctx.get(), nullptr, nullptr, nullptr, d_edkey.get()) < 1) {
    throw runtime_error(getName()+" unable to initialize signer");
  }

  string msgToSign = msg;

  size_t siglen = d_len * 2;
  string signature;
  signature.resize(siglen);

  if (EVP_DigestSign(mdctx.get(),
        reinterpret_cast<unsigned char*>(&signature.at(0)), &siglen,
        reinterpret_cast<unsigned char*>(&msgToSign.at(0)), msgToSign.length()) < 1) {
    throw runtime_error(getName()+" signing error");
  }

  return signature;
}

bool OpenSSLEDDSADNSCryptoKeyEngine::verify(const std::string& msg, const std::string& signature) const
{
  auto mdctx = std::unique_ptr<EVP_MD_CTX, void(*)(EVP_MD_CTX*)>(EVP_MD_CTX_new(), EVP_MD_CTX_free);
  if (!mdctx) {
    throw runtime_error(getName()+" MD context initialization failed");
  }
  if(EVP_DigestVerifyInit(mdctx.get(), nullptr, nullptr, nullptr, d_edkey.get()) < 1) {
    throw runtime_error(getName()+" unable to initialize signer");
  }

  string checkSignature = signature;
  string checkMsg = msg;

  auto r = EVP_DigestVerify(mdctx.get(),
      reinterpret_cast<unsigned char*>(&checkSignature.at(0)), checkSignature.length(),
      reinterpret_cast<unsigned char*>(&checkMsg.at(0)), checkMsg.length());
  if (r < 0) {
    throw runtime_error(getName()+" verification failure");
  }

  return (r == 1);
}

std::string OpenSSLEDDSADNSCryptoKeyEngine::getPubKeyHash() const
{
  return this->getPublicKeyString();
}

std::string OpenSSLEDDSADNSCryptoKeyEngine::getPublicKeyString() const
{
  string buf;
  size_t len = d_len;
  buf.resize(len);
  if (EVP_PKEY_get_raw_public_key(d_edkey.get(), reinterpret_cast<unsigned char*>(&buf.at(0)), &len) < 1) {
    throw std::runtime_error(getName() + " unable to get public key from key struct");
  }
  return buf;
}

void OpenSSLEDDSADNSCryptoKeyEngine::fromISCMap(DNSKEYRecordContent& drc, std::map<std::string, std::string>& stormap) {
  drc.d_algorithm = atoi(stormap["algorithm"].c_str());
  if (drc.d_algorithm != d_algorithm) {
    throw runtime_error(getName()+" tried to feed an algorithm "+std::to_string(drc.d_algorithm)+" to a "+std::to_string(d_algorithm)+" key");
  }

  d_edkey = std::unique_ptr<EVP_PKEY, void(*)(EVP_PKEY*)>(EVP_PKEY_new_raw_private_key(d_id, nullptr, reinterpret_cast<unsigned char*>(&stormap["privatekey"].at(0)), stormap["privatekey"].length()), EVP_PKEY_free);
  if (!d_edkey) {
    throw std::runtime_error(getName() + " could not create key structure from private key");
  }
}

void OpenSSLEDDSADNSCryptoKeyEngine::fromPublicKeyString(const std::string& content)
{
  if (content.length() != d_len) {
    throw runtime_error(getName() + " wrong public key length for algorithm " + std::to_string(d_algorithm));
  }

  const unsigned char* raw = reinterpret_cast<const unsigned char*>(content.c_str());

  d_edkey = std::unique_ptr<EVP_PKEY, void(*)(EVP_PKEY*)>(EVP_PKEY_new_raw_public_key(d_id, nullptr, raw, d_len), EVP_PKEY_free);
  if (!d_edkey) {
    throw runtime_error(getName()+" allocation of public key structure failed");
  }
}
#endif // HAVE_LIBCRYPTO_EDDSA

namespace {
  const struct LoaderStruct
  {
    LoaderStruct()
    {
      DNSCryptoKeyEngine::report(DNSSECKeeper::RSASHA1, &OpenSSLRSADNSCryptoKeyEngine::maker);
      DNSCryptoKeyEngine::report(DNSSECKeeper::RSASHA1NSEC3SHA1, &OpenSSLRSADNSCryptoKeyEngine::maker);
      DNSCryptoKeyEngine::report(DNSSECKeeper::RSASHA256, &OpenSSLRSADNSCryptoKeyEngine::maker);
      DNSCryptoKeyEngine::report(DNSSECKeeper::RSASHA512, &OpenSSLRSADNSCryptoKeyEngine::maker);
#ifdef HAVE_LIBCRYPTO_ECDSA
      DNSCryptoKeyEngine::report(DNSSECKeeper::ECDSA256, &OpenSSLECDSADNSCryptoKeyEngine::maker);
      DNSCryptoKeyEngine::report(DNSSECKeeper::ECDSA384, &OpenSSLECDSADNSCryptoKeyEngine::maker);
#endif
#ifdef HAVE_LIBCRYPTO_ED25519
      DNSCryptoKeyEngine::report(DNSSECKeeper::ED25519, &OpenSSLEDDSADNSCryptoKeyEngine::maker);
#endif
#ifdef HAVE_LIBCRYPTO_ED448
      DNSCryptoKeyEngine::report(DNSSECKeeper::ED448, &OpenSSLEDDSADNSCryptoKeyEngine::maker);
#endif
    }
  } loaderOpenSSL;
}