GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — ncrypto/include/ncrypto.h at main · nodejs/ncrypto Expand file tree/ Copy pathncrypto.hMore file actions 2053 lines (1704 loc) · 64.3 KB / Copy pathncrypto.hFile metadata and controls2053 lines (1704 loc) · 64.3 KB 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 #pragma once #include <openssl/bio.h> #include <openssl/bn.h> #include <openssl/dh.h> #include <openssl/dsa.h> #include <openssl/ec.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/kdf.h> #include <openssl/rsa.h> #include <openssl/ssl.h> #include <openssl/x509.h> #ifdef OPENSSL_IS_BORINGSSL #include <openssl/aead.h> #endif #include <cstddef> #include <functional> #include <list> #include <memory> #include <optional> #include <string> #include <string_view> #if NCRYPTO_DEVELOPMENT_CHECKS #include <iostream> #endif #if defined(NCRYPTO_ENGINE_COMPAT) && NCRYPTO_ENGINE_COMPAT && \ !defined(OPENSSL_NO_ENGINE) #include <openssl/engine.h> #endif // NCRYPTO_ENGINE_COMPAT && !OPENSSL_NO_ENGINE #ifndef OPENSSL_VERSION_PREREQ #define OPENSSL_VERSION_PREREQ(maj, min) \ (OPENSSL_VERSION_NUMBER >= (((maj) << 28) | ((min) << 20))) #endif // BoringSSL declares the EVP_*_do_all* APIs, but their implementation may // live in libdecrepit. This matches standalone ncrypto's build flag. #ifndef NCRYPTO_BSSL_LIBDECREPIT_MISSING #define NCRYPTO_BSSL_LIBDECREPIT_MISSING 0 #endif #if defined(OPENSSL_IS_BORINGSSL) && NCRYPTO_BSSL_LIBDECREPIT_MISSING #define NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK 1 #else #define NCRYPTO_USE_BORINGSSL_EVP_DO_ALL_FALLBACK 0 #endif // Backend split: // - OpenSSL >= 3 uses provider APIs and hides deprecated low-level objects. // - BoringSSL has its own API-compatible branch. // - OpenSSL < 3 remains the legacy fallback branch. #if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 0) #define NCRYPTO_USE_OPENSSL3_PROVIDER 1 #else #define NCRYPTO_USE_OPENSSL3_PROVIDER 0 #endif #ifdef OPENSSL_IS_BORINGSSL #define NCRYPTO_USE_BORINGSSL 1 #else #define NCRYPTO_USE_BORINGSSL 0 #endif #if !NCRYPTO_USE_OPENSSL3_PROVIDER && !NCRYPTO_USE_BORINGSSL #define NCRYPTO_USE_LEGACY_OPENSSL 1 #else #define NCRYPTO_USE_LEGACY_OPENSSL 0 #endif #if NCRYPTO_USE_BORINGSSL || NCRYPTO_USE_LEGACY_OPENSSL #define NCRYPTO_USE_LEGACY_KEY_TYPES 1 #else #define NCRYPTO_USE_LEGACY_KEY_TYPES 0 #endif #if NCRYPTO_USE_OPENSSL3_PROVIDER #include <openssl/core_names.h> #include <openssl/encoder.h> #include <openssl/param_build.h> #endif // The FIPS-related functions are only available // when the OpenSSL itself was compiled with FIPS support. #if defined(OPENSSL_FIPS) && !OPENSSL_VERSION_PREREQ(3, 0) #include <openssl/fips.h> #endif // OPENSSL_FIPS #if OPENSSL_VERSION_PREREQ(3, 0) #define OPENSSL_WITH_AES_OCB 1 #else #define OPENSSL_WITH_AES_OCB 0 #endif #if !defined(OPENSSL_NO_ARGON2) && OPENSSL_VERSION_PREREQ(3, 2) #define OPENSSL_WITH_ARGON2 1 #else #define OPENSSL_WITH_ARGON2 0 #endif #if OPENSSL_VERSION_PREREQ(3, 0) || defined(OPENSSL_IS_BORINGSSL) #define OPENSSL_WITH_KEM 1 #else #define OPENSSL_WITH_KEM 0 #endif #if OPENSSL_VERSION_PREREQ(3, 0) #define OPENSSL_WITH_EVP_MAC 1 #else #define OPENSSL_WITH_EVP_MAC 0 #endif #if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 0) #define OPENSSL_WITH_AES_SIV 1 #else #define OPENSSL_WITH_AES_SIV 0 #endif #if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 2) #define OPENSSL_WITH_AES_GCM_SIV 1 #else #define OPENSSL_WITH_AES_GCM_SIV 0 #endif #if defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_PREREQ(3, 2) #define OPENSSL_WITH_SIGNATURE_CONTEXT_STRING 1 #else #define OPENSSL_WITH_SIGNATURE_CONTEXT_STRING 0 #endif #if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 2) #define OPENSSL_WITH_OPENSSL_DHKEM 1 #else #define OPENSSL_WITH_OPENSSL_DHKEM 0 #endif #if OPENSSL_WITH_KEM && !defined(OPENSSL_IS_BORINGSSL) && \ !OPENSSL_VERSION_PREREQ(3, 5) #define OPENSSL_WITH_KEM_OPERATION_PARAM 1 #else #define OPENSSL_WITH_KEM_OPERATION_PARAM 0 #endif // Post-quantum cryptography support. Keep these explicit so code can // distinguish provider API shape from the available algorithm set. #if !defined(OPENSSL_IS_BORINGSSL) && OPENSSL_VERSION_PREREQ(3, 5) #define OPENSSL_WITH_OPENSSL_PQC 1 #else #define OPENSSL_WITH_OPENSSL_PQC 0 #endif #ifdef OPENSSL_IS_BORINGSSL #define OPENSSL_WITH_BORINGSSL_PQC 1 #else #define OPENSSL_WITH_BORINGSSL_PQC 0 #endif #define OPENSSL_WITH_PQC \ (OPENSSL_WITH_OPENSSL_PQC || OPENSSL_WITH_BORINGSSL_PQC) #define OPENSSL_WITH_PQC_ML_KEM_512 OPENSSL_WITH_OPENSSL_PQC #define OPENSSL_WITH_PQC_SLH_DSA OPENSSL_WITH_OPENSSL_PQC #if OPENSSL_WITH_OPENSSL_PQC #define EVP_PKEY_ML_KEM_512 NID_ML_KEM_512 #define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768 #define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024 #elif OPENSSL_WITH_BORINGSSL_PQC #define EVP_PKEY_ML_KEM_768 NID_ML_KEM_768 #define EVP_PKEY_ML_KEM_1024 NID_ML_KEM_1024 #endif #if OPENSSL_VERSION_PREREQ(3, 0) #define OSSL3_CONST const #else #define OSSL3_CONST #endif #ifdef __GNUC__ #define NCRYPTO_MUST_USE_RESULT __attribute__((warn_unused_result)) #else #define NCRYPTO_MUST_USE_RESULT #endif #ifdef OPENSSL_IS_BORINGSSL // Boringssl has opted to use size_t for some size related // APIs while Openssl is still using ints using OPENSSL_SIZE_T = size_t; #else using OPENSSL_SIZE_T = int; #endif #ifdef OPENSSL_IS_BORINGSSL #ifdef NCRYPTO_BSSL_NEEDS_DH_PRIMES #include "dh-primes.h" #endif // NCRYPTO_BSSL_NEEDS_DH_PRIMES #endif // OPENSSL_IS_BORINGSSL namespace ncrypto { // ============================================================================ // Utility macros inline bool EqualNoCase(const std::string_view a, const std::string_view b) { if (a.size() != b.size()) return false; return std::equal(a.begin(), a.end(), b.begin(), b.end(), [](char a, char b) { return std::tolower(a) == std::tolower(b); }); } #if NCRYPTO_DEVELOPMENT_CHECKS #define NCRYPTO_STR(x) #x #define NCRYPTO_REQUIRE(EXPR) \ { \ if (!(EXPR)) { \ abort(); \ } \ } #define NCRYPTO_FAIL(MESSAGE) \ do { \ std::cerr << "FAIL: " << (MESSAGE) << std::endl; \ abort(); \ } while (0); #define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) \ do { \ if (LHS != RHS) { \ std::cerr << "Mismatch: '" << LHS << "' - '" << RHS << "'" << std::endl; \ NCRYPTO_FAIL(MESSAGE); \ } \ } while (0); #define NCRYPTO_ASSERT_TRUE(COND) \ do { \ if (!(COND)) { \ std::cerr << "Assert at line " << __LINE__ << " of file " << __FILE__ \ << std::endl; \ NCRYPTO_FAIL(NCRYPTO_STR(COND)); \ } \ } while (0); #else #define NCRYPTO_FAIL(MESSAGE) #define NCRYPTO_ASSERT_EQUAL(LHS, RHS, MESSAGE) #define NCRYPTO_ASSERT_TRUE(COND) #endif #define NCRYPTO_DISALLOW_COPY(Name) \ Name(const Name&) = delete; \ Name& operator=(const Name&) = delete; #define NCRYPTO_DISALLOW_MOVE(Name) \ Name(Name&&) = delete; \ Name& operator=(Name&&) = delete; #define NCRYPTO_DISALLOW_COPY_AND_MOVE(Name) \ NCRYPTO_DISALLOW_COPY(Name) \ NCRYPTO_DISALLOW_MOVE(Name) #define NCRYPTO_DISALLOW_NEW_DELETE() \ void* operator new(size_t) = delete; \ void operator delete(void*) = delete; [[noreturn]] inline void unreachable() { #ifdef __GNUC__ __builtin_unreachable(); #elif defined(_MSC_VER) __assume(false); #else #endif } static constexpr int kX509NameFlagsMultiline = ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_UTF8_CONVERT | XN_FLAG_SEP_MULTILINE | XN_FLAG_FN_SN; // ============================================================================ // Error handling utilities // Capture the current OpenSSL Error Stack. The stack will be ordered such // that the error currently at the top of the stack is at the end of the // list and the error at the bottom of the stack is at the beginning. class CryptoErrorList final { public: enum class Option { NONE, CAPTURE_ON_CONSTRUCT }; CryptoErrorList(Option option = Option::CAPTURE_ON_CONSTRUCT); void capture(); // Add an error message to the end of the stack. void add(std::string message); inline const std::string& peek_back() const { return errors_.back(); } inline size_t size() const { return errors_.size(); } inline bool empty() const { return errors_.empty(); } inline auto begin() const noexcept { return errors_.begin(); } inline auto end() const noexcept { return errors_.end(); } inline auto rbegin() const noexcept { return errors_.rbegin(); } inline auto rend() const noexcept { return errors_.rend(); } std::optional<std::string> pop_back(); std::optional<std::string> pop_front(); private: std::list<std::string> errors_; }; // Forcibly clears the error stack on destruction. This stops stale errors // from popping up later in the lifecycle of crypto operations where they // would cause spurious failures. It is a rather blunt method, though, and // ERR_clear_error() isn't necessarily cheap. // // If created with a pointer to a CryptoErrorList, the current OpenSSL error // stack will be captured before clearing the error. class ClearErrorOnReturn final { public: ClearErrorOnReturn(CryptoErrorList* errors = nullptr); ~ClearErrorOnReturn(); NCRYPTO_DISALLOW_COPY_AND_MOVE(ClearErrorOnReturn) NCRYPTO_DISALLOW_NEW_DELETE() unsigned long peekError(); // NOLINT(runtime/int) private: CryptoErrorList* errors_; }; // Pop errors from OpenSSL's error stack that were added between when this // was constructed and destructed. // // If created with a pointer to a CryptoErrorList, the current OpenSSL error // stack will be captured before resetting the error to the mark. class MarkPopErrorOnReturn final { public: MarkPopErrorOnReturn(CryptoErrorList* errors = nullptr); ~MarkPopErrorOnReturn(); NCRYPTO_DISALLOW_COPY_AND_MOVE(MarkPopErrorOnReturn) NCRYPTO_DISALLOW_NEW_DELETE() unsigned long peekError(); // NOLINT(runtime/int) private: CryptoErrorList* errors_; }; // TODO(@jasnell): Eventually replace with std::expected when we are able to // bump up to c++23. template <typename T, typename E> struct Result final { const bool has_value; T value; std::optional<E> error = std::nullopt; // NOLINTNEXTLINE(runtime/int) -- matches ERR_peek_error() std::optional<unsigned long> openssl_error = std::nullopt; Result(T&& value) : has_value(true), value(std::move(value)) {} // NOLINTNEXTLINE(runtime/int) -- matches ERR_peek_error() Result(E&& error, std::optional<unsigned long> openssl_error = std::nullopt) : has_value(false), error(std::move(error)), openssl_error(std::move(openssl_error)) {} inline operator bool() const { return has_value; } }; // ============================================================================ // Various smart pointer aliases for OpenSSL types. template <typename T, void (*function)(T*)> struct FunctionDeleter { void operator()(T* pointer) const { function(pointer); } typedef std::unique_ptr<T, FunctionDeleter> Pointer; }; template <typename T, void (*function)(T*)> using DeleteFnPtr = typename FunctionDeleter<T, function>::Pointer; using PKCS8Pointer = DeleteFnPtr<PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_free>; #if NCRYPTO_USE_LEGACY_KEY_TYPES using RSAPointer = DeleteFnPtr<RSA, RSA_free>; #endif using SSLSessionPointer = DeleteFnPtr<SSL_SESSION, SSL_SESSION_free>; class BIOPointer; class BignumPointer; class CipherCtxPointer; class DataPointer; class DHPointer; class ECKeyPointer; class EVPKeyPointer; class EVPMacCtxPointer; class EVPMacPointer; class EVPMDCtxPointer; class SSLCtxPointer; class SSLPointer; class X509View; class X509Pointer; class ECDSASigPointer; class ECGroupPointer; class ECPointPointer; class ECKeyPointer; class Dsa; class Rsa; class Ec; struct StackOfXASN1Deleter { void operator()(STACK_OF(ASN1_OBJECT) * p) const { sk_ASN1_OBJECT_pop_free(p, ASN1_OBJECT_free); } }; using StackOfASN1 = std::unique_ptr<STACK_OF(ASN1_OBJECT), StackOfXASN1Deleter>; // An unowned, unmanaged pointer to a buffer of data. template <typename T> struct Buffer { T* data = nullptr; size_t len = 0; }; class Digest final { public: static constexpr size_t MAX_SIZE = EVP_MAX_MD_SIZE; Digest() = default; Digest(const EVP_MD* md) : md_(md) {} Digest(const Digest&) = default; Digest& operator=(const Digest&) = default; inline Digest& operator=(const EVP_MD* md) { md_ = md; return *this; } NCRYPTO_DISALLOW_MOVE(Digest) size_t size() const; inline const EVP_MD* get() const { return md_; } inline operator const EVP_MD*() const { return md_; } inline operator bool() const { return md_ != nullptr; } static const Digest MD5; static const Digest SHA1; static const Digest SHA256; static const Digest SHA384; static const Digest SHA512; static const Digest FromName(const char* name); private: const EVP_MD* md_ = nullptr; }; // Computes a fixed-length digest. DataPointer hashDigest(const Buffer<const unsigned char>& data, const EVP_MD* md); // Computes a variable-length digest for XOF algorithms (e.g. SHAKE128). DataPointer xofHashDigest(const Buffer<const unsigned char>& data, const EVP_MD* md, size_t length); class Cipher final { public: static constexpr size_t MAX_KEY_LENGTH = EVP_MAX_KEY_LENGTH; static constexpr size_t MAX_IV_LENGTH = EVP_MAX_IV_LENGTH; #ifdef EVP_MAX_AEAD_TAG_LENGTH static constexpr size_t MAX_AUTH_TAG_LENGTH = EVP_MAX_AEAD_TAG_LENGTH; #else static constexpr size_t MAX_AUTH_TAG_LENGTH = 16; #endif static_assert(EVP_GCM_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH #ifndef OPENSSL_IS_BORINGSSL && EVP_CCM_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH && EVP_CHACHAPOLY_TLS_TAG_LEN <= MAX_AUTH_TAG_LENGTH #endif ); Cipher() = default; Cipher(const EVP_CIPHER* cipher) : cipher_(cipher) {} Cipher(const Cipher& other); Cipher& operator=(const Cipher& other); inline Cipher& operator=(const EVP_CIPHER* cipher) { #if OPENSSL_WITH_AES_SIV || OPENSSL_WITH_AES_GCM_SIV fetched_cipher_.reset(); #endif cipher_ = cipher; return *this; } NCRYPTO_DISALLOW_MOVE(Cipher) inline const EVP_CIPHER* get() const { return cipher_; } inline operator const EVP_CIPHER*() const { return cipher_; } inline operator bool() const { return cipher_ != nullptr; } int getNid() const; int getMode() const; int getIvLength() const; int getKeyLength() const; int getBlockSize() const; std::string_view getModeLabel() const; const char* getName() const; bool isGcmMode() const; bool isWrapMode() const; bool isCtrMode() const; bool isCcmMode() const; bool isOcbMode() const; bool isSivMode() const; bool isGcmSivMode() const; bool isStreamMode() const; bool isChaCha20Poly1305() const; bool isSupportedAuthenticatedMode() const; int bytesToKey(const Digest& digest, const Buffer<const unsigned char>& input, unsigned char* key, unsigned char* iv) const; static const Cipher FromName(const char* name); static const Cipher FromNid(int nid); static const Cipher FromCtx(const CipherCtxPointer& ctx); using CipherNameCallback = std::function<void(const char* name)>; // Iterates the known ciphers if the underlying implementation // is able to do so. static void ForEach(CipherNameCallback callback); // Utilities to get various ciphers by type. If the underlying // implementation does not support the requested cipher, then // the result will be an empty Cipher object whose bool operator // will return false. static const Cipher EMPTY; static const Cipher AES_128_CBC; static const Cipher AES_192_CBC; static const Cipher AES_256_CBC; static const Cipher AES_128_CTR; static const Cipher AES_192_CTR; static const Cipher AES_256_CTR; static const Cipher AES_128_GCM; static const Cipher AES_192_GCM; static const Cipher AES_256_GCM; static const Cipher AES_128_KW; static const Cipher AES_192_KW; static const Cipher AES_256_KW; static const Cipher AES_128_OCB; static const Cipher AES_192_OCB; static const Cipher AES_256_OCB; static const Cipher CHACHA20_POLY1305; struct CipherParams { int padding; Digest digest; Digest mgf1_digest; const Buffer<const void> label; }; static DataPointer encrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); static DataPointer decrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); static DataPointer sign(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); static DataPointer recover(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); static constexpr bool IsValidGCMTagLength(unsigned int tag_len) { return tag_len == 4 || tag_len == 8 || (tag_len >= 12 && tag_len <= 16); } private: const EVP_CIPHER* cipher_ = nullptr; #if OPENSSL_WITH_AES_SIV || OPENSSL_WITH_AES_GCM_SIV explicit Cipher(DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free> cipher); DeleteFnPtr<EVP_CIPHER, EVP_CIPHER_free> fetched_cipher_; #endif }; // ============================================================================ // DSA class Dsa final { public: Dsa(); #if NCRYPTO_USE_OPENSSL3_PROVIDER explicit Dsa(const EVP_PKEY* pkey); #else Dsa(OSSL3_CONST DSA* dsa); #endif NCRYPTO_DISALLOW_COPY_AND_MOVE(Dsa) #if NCRYPTO_USE_OPENSSL3_PROVIDER inline operator bool() const { return dsa_; } #else inline operator bool() const { return dsa_ != nullptr; } #endif #if NCRYPTO_USE_LEGACY_KEY_TYPES inline operator OSSL3_CONST DSA*() const { return dsa_; } #endif const BIGNUM* getP() const; const BIGNUM* getQ() const; size_t getModulusLength() const; size_t getDivisorLength() const; private: #if NCRYPTO_USE_OPENSSL3_PROVIDER bool dsa_ = false; DeleteFnPtr<BIGNUM, BN_free> p_; DeleteFnPtr<BIGNUM, BN_free> q_; #else OSSL3_CONST DSA* dsa_; #endif }; // ============================================================================ // RSA class Rsa final { public: Rsa(); #if NCRYPTO_USE_OPENSSL3_PROVIDER explicit Rsa(const EVP_PKEY* pkey); #else Rsa(OSSL3_CONST RSA* rsa); #endif NCRYPTO_DISALLOW_COPY_AND_MOVE(Rsa) #if NCRYPTO_USE_OPENSSL3_PROVIDER inline operator bool() const { return rsa_; } #else inline operator bool() const { return rsa_ != nullptr; } #endif #if NCRYPTO_USE_LEGACY_KEY_TYPES inline operator OSSL3_CONST RSA*() const { return rsa_; } #endif struct PublicKey { const BIGNUM* n; const BIGNUM* e; const BIGNUM* d; }; struct PrivateKey { const BIGNUM* p; const BIGNUM* q; const BIGNUM* dp; const BIGNUM* dq; const BIGNUM* qi; }; struct PssParams { std::string_view digest = "sha1"; std::optional<std::string_view> mgf1_digest = "sha1"; int64_t salt_length = 20; }; const PublicKey getPublicKey() const; const PrivateKey getPrivateKey() const; const std::optional<PssParams> getPssParams() const; bool setPublicKey(BignumPointer&& n, BignumPointer&& e); bool setPrivateKey(BignumPointer&& d, BignumPointer&& q, BignumPointer&& p, BignumPointer&& dp, BignumPointer&& dq, BignumPointer&& qi); using CipherParams = Cipher::CipherParams; BIOPointer derPublicKey() const; static DataPointer encrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); static DataPointer decrypt(const EVPKeyPointer& key, const CipherParams& params, const Buffer<const void> in); private: #if NCRYPTO_USE_OPENSSL3_PROVIDER bool rsa_ = false; bool rsa_pss_ = false; DeleteFnPtr<BIGNUM, BN_free> n_; DeleteFnPtr<BIGNUM, BN_free> e_; DeleteFnPtr<BIGNUM, BN_clear_free> d_; DeleteFnPtr<BIGNUM, BN_clear_free> p_; DeleteFnPtr<BIGNUM, BN_clear_free> q_; DeleteFnPtr<BIGNUM, BN_clear_free> dp_; DeleteFnPtr<BIGNUM, BN_clear_free> dq_; DeleteFnPtr<BIGNUM, BN_clear_free> qi_; std::optional<PssParams> pss_params_; #else OSSL3_CONST RSA* rsa_; #endif }; class BignumPointer final { public: BignumPointer() = default; explicit BignumPointer(BIGNUM* bignum); explicit BignumPointer(const unsigned char* data, size_t len); BignumPointer(BignumPointer&& other) noexcept; BignumPointer& operator=(BignumPointer&& other) noexcept; NCRYPTO_DISALLOW_COPY(BignumPointer) ~BignumPointer(); int operator<=>(const BignumPointer& other) const noexcept; int operator<=>(const BIGNUM* other) const noexcept; inline operator bool() const { return bn_ != nullptr; } inline BIGNUM* get() const noexcept { return bn_.get(); } void reset(BIGNUM* bn = nullptr); void reset(const unsigned char* data, size_t len); BIGNUM* release(); bool isZero() const; bool isOne() const; bool setWord(unsigned long w); // NOLINT(runtime/int) std::optional<unsigned long> getWord() const; // NOLINT(runtime/int) size_t byteLength() const; size_t bitLength() const; DataPointer toHex() const; DataPointer encode() const; DataPointer encodePadded(size_t size) const; size_t encodeInto(unsigned char* out) const; size_t encodePaddedInto(unsigned char* out, size_t size) const; using PrimeCheckCallback = std::function<bool(int, int)>; int isPrime(int checks, PrimeCheckCallback cb = defaultPrimeCheckCallback) const; struct PrimeConfig { int bits; bool safe = false; const BignumPointer& add; const BignumPointer& rem; }; static BignumPointer NewPrime( const PrimeConfig& params, PrimeCheckCallback cb = defaultPrimeCheckCallback); bool generate(const PrimeConfig& params, PrimeCheckCallback cb = defaultPrimeCheckCallback) const; static BignumPointer New(); static BignumPointer NewSecure(); static BignumPointer NewSub(const BignumPointer& a, const BignumPointer& b); static BignumPointer NewLShift(size_t length); static DataPointer Encode(const BIGNUM* bn); static DataPointer EncodePadded(const BIGNUM* bn, size_t size); static size_t EncodePaddedInto(const BIGNUM* bn, unsigned char* out, size_t size); static int GetBitCount(const BIGNUM* bn); static int GetByteCount(const BIGNUM* bn); static std::optional<unsigned long> GetWord( // NOLINT(runtime/int) const BIGNUM* bn); static const BIGNUM* One(); BignumPointer clone(); private: DeleteFnPtr<BIGNUM, BN_clear_free> bn_; static bool defaultPrimeCheckCallback(int, int) { return 1; } }; class Ec final { public: Ec(); #if NCRYPTO_USE_OPENSSL3_PROVIDER explicit Ec(const EVP_PKEY* pkey); #else Ec(OSSL3_CONST EC_KEY* key); #endif NCRYPTO_DISALLOW_COPY_AND_MOVE(Ec) const EC_GROUP* getGroup() const; const EC_POINT* getPublicKey() const; point_conversion_form_t getPointConversionForm() const; int getCurve() const; uint32_t getDegree() const; std::string getCurveName() const; const BIGNUM* getPrivateKey() const; inline operator bool() const { return ec_ != nullptr; } #if NCRYPTO_USE_LEGACY_KEY_TYPES inline operator OSSL3_CONST EC_KEY*() const { return ec_; } #endif static int GetCurveIdFromName(const char* name); using GetCurveCallback = std::function<bool(const char*)>; static bool GetCurves(GetCurveCallback callback); inline const BignumPointer& getX() const { return x_; } inline const BignumPointer& getY() const { return y_; } inline const BignumPointer& getD() const { return d_; } private: #if NCRYPTO_USE_OPENSSL3_PROVIDER DeleteFnPtr<EC_GROUP, EC_GROUP_free> ec_; DeleteFnPtr<EC_POINT, EC_POINT_free> pub_; point_conversion_form_t form_ = POINT_CONVERSION_UNCOMPRESSED; #else OSSL3_CONST EC_KEY* ec_ = nullptr; #endif // Affine coordinates and private scalar for the EC key. BignumPointer x_; BignumPointer y_; BignumPointer d_; }; // A managed pointer to a buffer of data. When destroyed the underlying // buffer will be freed. class DataPointer final { public: static DataPointer Alloc(size_t len); static DataPointer Copy(const Buffer<const void>& buffer); // Attempts to allocate the buffer space using the secure heap, if // supported/enabled. If the secure heap is disabled, then this // ends up being equivalent to Alloc(len). Note that allocation // will fail if there is not enough free space remaining in the // secure heap space. static DataPointer SecureAlloc(size_t len); // If the secure heap is enabled, returns the amount of data that // has been allocated from the heap. static size_t GetSecureHeapUsed(); enum class InitSecureHeapResult { FAILED, UNABLE_TO_MEMORY_MAP, OK, }; // Attempt to initialize the secure heap. The secure heap is not // supported on all operating systems and whenever boringssl is // used. static InitSecureHeapResult TryInitSecureHeap(size_t amount, size_t min); DataPointer() = default; explicit DataPointer(void* data, size_t len, bool secure = false); explicit DataPointer(const Buffer<void>& buffer, bool secure = false); DataPointer(DataPointer&& other) noexcept; DataPointer& operator=(DataPointer&& other) noexcept; NCRYPTO_DISALLOW_COPY(DataPointer) ~DataPointer(); inline bool operator==(std::nullptr_t) noexcept { return data_ == nullptr; } inline operator bool() const { return data_ != nullptr; } template <typename T = void> inline T* get() const noexcept { return static_cast<T*>(data_); } inline size_t size() const noexcept { return len_; } void reset(void* data = nullptr, size_t len = 0); void reset(const Buffer<void>& buffer); // Sets the underlying data buffer to all zeros. void zero(); DataPointer resize(size_t len); // Releases ownership of the underlying data buffer. It is the caller's // responsibility to ensure the buffer is appropriately freed. Buffer<void> release(); // Returns a Buffer struct that is a view of the underlying data. template <typename T = void> inline operator const Buffer<T>() const { return { .data = static_cast<T*>(data_), .len = len_, }; } bool isSecure() const { return secure_; } private: void free(); void* data_ = nullptr; size_t len_ = 0; bool secure_ = false; }; class BIOPointer final { public: static BIOPointer NewMem(); static BIOPointer NewSecMem(); static BIOPointer New(const BIO_METHOD* method); static BIOPointer New(const void* data, size_t len); static BIOPointer New(const BIGNUM* bn); static BIOPointer NewFile(const char* filename, const char* mode); static BIOPointer NewFp(FILE* fd, int flags); template <typename T> static BIOPointer New(const Buffer<T>& buf) { return New(buf.data, buf.len); } BIOPointer() = default; BIOPointer(std::nullptr_t) : bio_(nullptr) {} explicit BIOPointer(BIO* bio); BIOPointer(BIOPointer&& other) noexcept; BIOPointer& operator=(BIOPointer&& other) noexcept; NCRYPTO_DISALLOW_COPY(BIOPointer) ~BIOPointer(); inline bool operator==(std::nullptr_t) noexcept { return bio_ == nullptr; } inline operator bool() const { return bio_ != nullptr; } inline BIO* get() const noexcept { return bio_.get(); } inline operator BUF_MEM*() const { BUF_MEM* mem = nullptr; if (!bio_) return mem; BIO_get_mem_ptr(bio_.get(), &mem); return mem; } inline operator BIO*() const { return bio_.get(); } void reset(BIO* bio = nullptr); BIO* release(); bool resetBio() const; static int Write(BIOPointer* bio, std::string_view message); template <typename... Args> static void Printf(BIOPointer* bio, const char* format, Args... args) { if (bio == nullptr || !*bio) return; BIO_printf(bio->get(), format, std::forward<Args...>(args...)); } private: mutable DeleteFnPtr<BIO, BIO_free_all> bio_; }; class CipherCtxPointer final { public: static CipherCtxPointer New(); CipherCtxPointer() = default; explicit CipherCtxPointer(EVP_CIPHER_CTX* ctx); CipherCtxPointer(CipherCtxPointer&& other) noexcept; CipherCtxPointer& operator=(CipherCtxPointer&& other) noexcept; NCRYPTO_DISALLOW_COPY(CipherCtxPointer) ~CipherCtxPointer(); inline bool operator==(std::nullptr_t) const noexcept { return ctx_ == nullptr; } inline operator bool() const { return ctx_ != nullptr; } inline EVP_CIPHER_CTX* get() const { return ctx_.get(); } inline operator EVP_CIPHER_CTX*() const { return ctx_.get(); } void reset(EVP_CIPHER_CTX* ctx = nullptr); EVP_CIPHER_CTX* release(); void setAllowWrap(); bool setKeyLength(size_t length); bool setIvLength(size_t length); bool setAeadTag(const Buffer<const char>& tag); bool setAeadTagLength(size_t length); bool setPadding(bool padding); bool init(const Cipher& cipher, bool encrypt, const unsigned char* key = nullptr, const unsigned char* iv = nullptr); int getBlockSize() const; int getMode() const; int getNid() const; bool isGcmMode() const; bool isOcbMode() const; bool isCcmMode() const; bool isWrapMode() const; bool isSivMode() const; bool isGcmSivMode() const; bool isChaCha20Poly1305() const; bool update(const Buffer<const unsigned char>& in, unsigned char* out, int* out_len, bool finalize = false); bool getAeadTag(size_t len, unsigned char* out); private: |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |