| 1 | #include "hkdf.h" |
| 2 | #include "openssl_common.h" |
| 3 | |
| 4 | #include <openssl/err.h> |
| 5 | #include <openssl/evp.h> |
| 6 | #include <stdexcept> |
| 7 | |
| 8 | namespace mlspp::hpke { |
| 9 | |
| 10 | template<> |
| 11 | const HKDF& |
| 12 | HKDF::get<Digest::ID::SHA256>() |
| 13 | { |
| 14 | static const HKDF instance(Digest::get<Digest::ID::SHA256>()); |
| 15 | return instance; |
| 16 | } |
| 17 | |
| 18 | template<> |
| 19 | const HKDF& |
| 20 | HKDF::get<Digest::ID::SHA384>() |
| 21 | { |
| 22 | static const HKDF instance(Digest::get<Digest::ID::SHA384>()); |
| 23 | return instance; |
| 24 | } |
| 25 | |
| 26 | template<> |
| 27 | const HKDF& |
| 28 | HKDF::get<Digest::ID::SHA512>() |
| 29 | { |
| 30 | static const HKDF instance(Digest::get<Digest::ID::SHA512>()); |
| 31 | return instance; |
| 32 | } |
| 33 | |
| 34 | static KDF::ID |
| 35 | digest_to_kdf(Digest::ID digest_id) |
| 36 | { |
| 37 | switch (digest_id) { |
| 38 | case Digest::ID::SHA256: |
| 39 | return KDF::ID::HKDF_SHA256; |
| 40 | case Digest::ID::SHA384: |
| 41 | return KDF::ID::HKDF_SHA384; |
| 42 | case Digest::ID::SHA512: |
| 43 | return KDF::ID::HKDF_SHA512; |
| 44 | } |
| 45 | |
| 46 | throw std::runtime_error("Unsupported algorithm"); |
| 47 | } |
| 48 | |
| 49 | HKDF::HKDF(const Digest& digest_in) |
| 50 | : KDF(digest_to_kdf(digest_in.id), digest_in.hash_size) |
| 51 | , digest(digest_in) |
| 52 | { |
| 53 | } |
| 54 | |
| 55 | bytes |
| 56 | HKDF::extract(const bytes& salt, const bytes& ikm) const |
| 57 | { |
| 58 | return digest.hmac_for_hkdf_extract(salt, ikm); |
| 59 | } |
| 60 | |
| 61 | bytes |
| 62 | HKDF::expand(const bytes& prk, const bytes& info, size_t size) const |
| 63 | { |
| 64 | auto okm = bytes{}; |
| 65 | auto i = uint8_t(0x00); |
| 66 | auto Ti = bytes{}; |
| 67 | while (okm.size() < size) { |
| 68 | i += 1; |
| 69 | auto block = Ti + info + bytes{ i }; |
| 70 | |
| 71 | Ti = digest.hmac(prk, block); |
| 72 | okm += Ti; |
| 73 | } |
| 74 | |
| 75 | okm.resize(size); |
| 76 | return okm; |
| 77 | } |
| 78 | |
| 79 | } // namespace mlspp::hpke |