Truly independent web browser
LibCrypto: Support cSHAKE with a function name or customization
Shannon Booth6c35444b0b36
diff --git a/Libraries/LibCrypto/Hash/SHAKE.cpp b/Libraries/LibCrypto/Hash/SHAKE.cppindex afd4844b24e..049e14b67ce 100644--- a/Libraries/LibCrypto/Hash/SHAKE.cpp+++ b/Libraries/LibCrypto/Hash/SHAKE.cpp@@ -12,22 +12,12 @@namespace Crypto::Hash {SHAKE::SHAKE(SHAKEKind kind)+ : m_kind(kind){- m_md = (kind == SHAKEKind::CSHAKE128) ? EVP_shake128() : EVP_shake256();}-ErrorOr<void> SHAKE::validate_parameters(- u32 length,- Optional<ReadonlyBytes> customization,- Optional<ReadonlyBytes> function_name)+ErrorOr<void> SHAKE::validate_parameters(u32 length){- bool wants_cshake = (customization.has_value() && !customization->is_empty()) || (function_name.has_value() && !function_name->is_empty());-- if (wants_cshake) {- // FIXME: Implement cSHAKE with non-empty N or S- return Error::from_string_literal("cSHAKE with non-empty N or S is not supported yet (OpenSSL EVP limitation)");- }-if (length % 8 != 0) {return Error::from_string_literal("SHAKE output length must be a multiple of 8 bits");}@@ -35,25 +25,71 @@ ErrorOr<void> SHAKE::validate_parameters(return {};}+// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf+static ErrorOr<void> left_encode(ByteBuffer& output, u64 value)+{+ u8 bytes[sizeof(u64)];+ size_t length = 0;+ do {+ bytes[sizeof(u64) - ++length] = static_cast<u8>(value);+ value >>= 8;+ } while (value != 0);++ TRY(output.try_append(static_cast<u8>(length)));+ return output.try_append(bytes + sizeof(u64) - length, length);+}++// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-185.pdf+static ErrorOr<void> encode_string(ByteBuffer& output, ReadonlyBytes string)+{+ TRY(left_encode(output, static_cast<u64>(string.size()) * 8));+ return output.try_append(string);+}+ErrorOr<ByteBuffer> SHAKE::digest(ReadonlyBytes data,u32 length,Optional<ReadonlyBytes> customization,Optional<ReadonlyBytes> function_name) const{- TRY(validate_parameters(length, customization, function_name));+ TRY(validate_parameters(length));size_t output_bytes = length / 8;auto buf = TRY(ByteBuffer::create_uninitialized(output_bytes));auto ctx = TRY(OpenSSL_MD_CTX::wrap(EVP_MD_CTX_new()));- OPENSSL_TRY(EVP_DigestInit_ex(ctx.ptr(), m_md, nullptr));+ auto name = function_name.value_or({});+ auto customization_string = customization.value_or({});- OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), data.data(), data.size()));+ // If N = "" and S = "", return SHAKE128(X, L) (or SHAKE256(X, L) for cSHAKE256).+ if (name.is_empty() && customization_string.is_empty()) {+ OPENSSL_TRY(EVP_DigestInit_ex(ctx.ptr(), m_kind == SHAKEKind::CSHAKE128 ? EVP_shake128() : EVP_shake256(), nullptr));+ OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), data.data(), data.size()));+ OPENSSL_TRY(EVP_DigestFinalXOF(ctx.ptr(), buf.data(), output_bytes));+ return buf;+ }- OPENSSL_TRY(EVP_DigestFinalXOF(ctx.ptr(), buf.data(), output_bytes));+ // Else return KECCAK[256](bytepad(encode_string(N) || encode_string(S), 168) || X || 00, L) for cSHAKE128, or+ // KECCAK[512](bytepad(encode_string(N) || encode_string(S), 136) || X || 00, L) for cSHAKE256.+ // NB: OpenSSL's KECCAK-KMAC digests are KECCAK[c](M || 00, L), the function that KMAC builds on.+ size_t rate = m_kind == SHAKEKind::CSHAKE128 ? 168 : 136;+ auto const* keccak_name = m_kind == SHAKEKind::CSHAKE128 ? "KECCAK-KMAC-128" : "KECCAK-KMAC-256";+ ByteBuffer prefix;+ TRY(left_encode(prefix, rate));+ TRY(encode_string(prefix, name));+ TRY(encode_string(prefix, customization_string));+ TRY(prefix.try_resize(ceil_div(prefix.size(), rate) * rate, ByteBuffer::ZeroFillNewElements::Yes));++ auto* keccak = OPENSSL_TRY_PTR(EVP_MD_fetch(nullptr, keccak_name, nullptr));+ auto init_result = EVP_DigestInit_ex(ctx.ptr(), keccak, nullptr);+ EVP_MD_free(keccak);+ OPENSSL_TRY(init_result);++ OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), prefix.data(), prefix.size()));+ OPENSSL_TRY(EVP_DigestUpdate(ctx.ptr(), data.data(), data.size()));+ OPENSSL_TRY(EVP_DigestFinalXOF(ctx.ptr(), buf.data(), output_bytes));return buf;}diff --git a/Libraries/LibCrypto/Hash/SHAKE.h b/Libraries/LibCrypto/Hash/SHAKE.hindex 7c94c1ff1d9..76b97efbf3e 100644--- a/Libraries/LibCrypto/Hash/SHAKE.h+++ b/Libraries/LibCrypto/Hash/SHAKE.h@@ -26,10 +26,7 @@ public:~SHAKE() = default;- static ErrorOr<void> validate_parameters(- u32 length,- Optional<ReadonlyBytes> customization,- Optional<ReadonlyBytes> function_name);+ static ErrorOr<void> validate_parameters(u32 length);ErrorOr<ByteBuffer> digest(ReadonlyBytes data,@@ -38,7 +35,7 @@ public:Optional<ReadonlyBytes> function_name) const;private:- EVP_MD const* m_md;+ SHAKEKind m_kind;};}diff --git a/Libraries/LibCrypto/Rust/src/ffi.rs b/Libraries/LibCrypto/Rust/src/ffi.rsindex 5a826dedc1a..b12b12df3b6 100644--- a/Libraries/LibCrypto/Rust/src/ffi.rs+++ b/Libraries/LibCrypto/Rust/src/ffi.rs@@ -50,11 +50,7 @@ unsafe extern "C" {state: *mut c_void,receive: ReceiveBytes,) -> bool;- pub(super) fn crypto_cshake_validate_parameters(- output_length: u32,- customization: OptionalBytes<'_>,- function_name: OptionalBytes<'_>,- ) -> usize;+ pub(super) fn crypto_cshake_validate_parameters(output_length: u32) -> usize;pub(super) fn crypto_cshake_digest(kind: CShakeKind,data: Span<'_, u8>,diff --git a/Libraries/LibCrypto/Rust/src/lib.rs b/Libraries/LibCrypto/Rust/src/lib.rsindex 8c6c3951b61..f52a6941d9d 100644--- a/Libraries/LibCrypto/Rust/src/lib.rs+++ b/Libraries/LibCrypto/Rust/src/lib.rs@@ -162,15 +162,9 @@ pub fn sha_digest(kind: ShaHashKind, data: &[u8]) -> Result<Vec<u8>, BackendErroOk(bytes)}-pub fn cshake_validate_parameters(- output_length: u32,- customization: Option<&[u8]>,- function_name: Option<&[u8]>,-) -> Result<(), Utf16String> {- // SAFETY: The input is borrowed for the call.- result_from_error(unsafe {- ffi::crypto_cshake_validate_parameters(output_length, customization.into(), function_name.into())- })+pub fn cshake_validate_parameters(output_length: u32) -> Result<(), Utf16String> {+ // SAFETY: The call takes no pointers.+ result_from_error(unsafe { ffi::crypto_cshake_validate_parameters(output_length) })}pub fn cshake_digest(diff --git a/Libraries/LibCrypto/RustBindings.cpp b/Libraries/LibCrypto/RustBindings.cppindex 9bda4e3d25e..69e038e776c 100644--- a/Libraries/LibCrypto/RustBindings.cpp+++ b/Libraries/LibCrypto/RustBindings.cpp@@ -1013,12 +1013,12 @@ FlatPtr crypto_argon2_derive_key(::Crypto::Hash::Argon2Type kind, Argon2Inputs cstatic_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE128) == 0);static_assert(to_underlying(::Crypto::Hash::SHAKEKind::CSHAKE256) == 1);-extern "C" FlatPtr crypto_cshake_validate_parameters(u32, OptionalBytes, OptionalBytes);+extern "C" FlatPtr crypto_cshake_validate_parameters(u32);extern "C" FlatPtr crypto_cshake_digest(::Crypto::Hash::SHAKEKind, ReadonlyBytes, u32, OptionalBytes, OptionalBytes, void*, ReceiveEncodedBytes);-FlatPtr crypto_cshake_validate_parameters(u32 output_length, OptionalBytes customization, OptionalBytes function_name)+FlatPtr crypto_cshake_validate_parameters(u32 output_length){- auto result = ::Crypto::Hash::SHAKE::validate_parameters(output_length, customization.to_optional(), function_name.to_optional());+ auto result = ::Crypto::Hash::SHAKE::validate_parameters(output_length);if (result.is_error())return Utf16String::formatted("{}", result.error()).into_raw();return 0;diff --git a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rsindex 4b574c3a4cc..b55f09b1af0 100644--- a/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs+++ b/Libraries/LibWeb/Bindings/Rust/src/crypto/crypto_algorithms.rs@@ -522,11 +522,7 @@ impl AlgorithmMethods for CShakeParams {// NB: Step 5 throws an OperationError for the parameters that our cSHAKE does not support.let normalized_algorithm = self;- let result = libcrypto_rust::cshake_validate_parameters(- normalized_algorithm.output_length,- normalized_algorithm.customization.as_ref().map(Bytes::as_slice),- normalized_algorithm.function_name.as_ref().map(Bytes::as_slice),- );+ let result = libcrypto_rust::cshake_validate_parameters(normalized_algorithm.output_length);if let Err(detail) = result {return Err(Exception::Dom("OperationError",diff --git a/Tests/LibCrypto/TestHash.cpp b/Tests/LibCrypto/TestHash.cppindex 411c74e0c7a..7667ef96782 100644--- a/Tests/LibCrypto/TestHash.cpp+++ b/Tests/LibCrypto/TestHash.cpp@@ -5,6 +5,7 @@*/#include <LibCrypto/Hash/Hash.h>+#include <LibCrypto/Hash/SHAKE.h>#include <LibTest/TestCase.h>#include <cstring>@@ -57,3 +58,49 @@ TEST_CASE(test_SHA3_256_hash_split_into_blocks)auto digest = Crypto::Hash::digest(Crypto::Hash::HashKind::SHA3_256, "0123456789012345678901234567890123456789012345678901234567890123abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcd"sv.bytes());EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });}++TEST_CASE(test_cSHAKE128_without_function_name_or_customization)+{+ u8 result[] {+ 0x58, 0x81, 0x09, 0x2d, 0xd8, 0x18, 0xbf, 0x5c, 0xf8, 0xa3, 0xdd, 0xb7, 0x93, 0xfb, 0xcb, 0xa7,+ 0x40, 0x97, 0xd5, 0xc5, 0x26, 0xa6, 0xd3, 0x5f, 0x97, 0xb8, 0x33, 0x51, 0x94, 0x0f, 0x2c, 0xc8+ };+ auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE128).digest("abc"sv.bytes(), 256, {}, {}));+ EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });+}++// NIST SP 800-185 cSHAKE sample #1+TEST_CASE(test_cSHAKE128_with_customization)+{+ u8 const data[] { 0x00, 0x01, 0x02, 0x03 };+ u8 result[] {+ 0xc1, 0xc3, 0x69, 0x25, 0xb6, 0x40, 0x9a, 0x04, 0xf1, 0xb5, 0x04, 0xfc, 0xbc, 0xa9, 0xd8, 0x2b,+ 0x40, 0x17, 0x27, 0x7c, 0xb5, 0xed, 0x2b, 0x20, 0x65, 0xfc, 0x1d, 0x38, 0x14, 0xd5, 0xaa, 0xf5+ };+ auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE128).digest(data, 256, "Email Signature"sv.bytes(), {}));+ EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });+}++// NIST SP 800-185 cSHAKE sample #3+TEST_CASE(test_cSHAKE256_with_customization)+{+ u8 const data[] { 0x00, 0x01, 0x02, 0x03 };+ u8 result[] {+ 0xd0, 0x08, 0x82, 0x8e, 0x2b, 0x80, 0xac, 0x9d, 0x22, 0x18, 0xff, 0xee, 0x1d, 0x07, 0x0c, 0x48,+ 0xb8, 0xe4, 0xc8, 0x7b, 0xff, 0x32, 0xc9, 0x69, 0x9d, 0x5b, 0x68, 0x96, 0xee, 0xe0, 0xed, 0xd1,+ 0x64, 0x02, 0x0e, 0x2b, 0xe0, 0x56, 0x08, 0x58, 0xd9, 0xc0, 0x0c, 0x03, 0x7e, 0x34, 0xa9, 0x69,+ 0x37, 0xc5, 0x61, 0xa7, 0x4c, 0x41, 0x2b, 0xb4, 0xc7, 0x46, 0x46, 0x95, 0x27, 0x28, 0x1c, 0x8c+ };+ auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE256).digest(data, 512, "Email Signature"sv.bytes(), {}));+ EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });+}++TEST_CASE(test_cSHAKE128_with_function_name)+{+ u8 result[] {+ 0xd8, 0x02, 0x43, 0xb8, 0x42, 0x23, 0x2b, 0xe0, 0xbd, 0x24, 0x26, 0x7d, 0x41, 0x81, 0xc2, 0x5d,+ 0x69, 0xb2, 0x86, 0xf4, 0x3a, 0x85, 0xe1, 0xc6, 0xf3, 0x24, 0xdb, 0x04, 0x86, 0xae, 0x19, 0x26+ };+ auto digest = TRY_OR_FAIL(Crypto::Hash::SHAKE(Crypto::Hash::SHAKEKind::CSHAKE128).digest("hello"sv.bytes(), 256, {}, "KMAC"sv.bytes()));+ EXPECT_EQ(digest.bytes(), ReadonlyBytes { result });+}diff --git a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-supports-implementation-limits.txt b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-supports-implementation-limits.txtindex c8e8f28f217..7e1b419e70a 100644--- a/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-supports-implementation-limits.txt+++ b/Tests/LibWeb/Text/expected/Crypto/SubtleCrypto-supports-implementation-limits.txt@@ -1,6 +1,6 @@cSHAKE128: supports true, digest ok-cSHAKE128 with customization: supports false, digest OperationError-cSHAKE256 with function name: supports false, digest OperationError+cSHAKE128 with customization: supports true, digest ok+cSHAKE256 with function name: supports true, digest okcSHAKE128 with partial byte output length: supports false, digest OperationErrorHMAC SHA-256: supports true, generateKey okHMAC SHA3-256: supports false, generateKey NotSupportedError