Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

selftests/bpf: Add test for libbpf_sha256()

Test that libbpf_sha256() calculates SHA-256 digests correctly.

Tested with:
make -C tools/testing/selftests/bpf/
./tools/testing/selftests/bpf/test_progs -t sha256 -v

Signed-off-by: Eric Biggers <ebiggers@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>

authored by

Eric Biggers and committed by
Alexei Starovoitov
f09f57c7 55c0ced5

+52
+52
tools/testing/selftests/bpf/prog_tests/sha256.c
··· 1 + // SPDX-License-Identifier: GPL-2.0-only 2 + /* Copyright 2025 Google LLC */ 3 + 4 + #include <test_progs.h> 5 + #include "bpf/libbpf_internal.h" 6 + 7 + #define MAX_LEN 4096 8 + 9 + /* Test libbpf_sha256() for all lengths from 0 to MAX_LEN inclusively. */ 10 + void test_sha256(void) 11 + { 12 + /* 13 + * The correctness of this value was verified by running this test with 14 + * libbpf_sha256() replaced by OpenSSL's SHA256(). 15 + */ 16 + static const __u8 expected_digest_of_digests[SHA256_DIGEST_LENGTH] = { 17 + 0x62, 0x30, 0x0e, 0x1d, 0xea, 0x7f, 0xc4, 0x74, 18 + 0xfd, 0x8e, 0x64, 0x0b, 0xd8, 0x5f, 0xea, 0x04, 19 + 0xf3, 0xef, 0x77, 0x42, 0xc2, 0x01, 0xb8, 0x90, 20 + 0x6e, 0x19, 0x91, 0x1b, 0xca, 0xb3, 0x28, 0x42, 21 + }; 22 + __u64 seed = 0; 23 + __u8 *data = NULL, *digests = NULL; 24 + __u8 digest_of_digests[SHA256_DIGEST_LENGTH]; 25 + size_t i; 26 + 27 + data = malloc(MAX_LEN); 28 + if (!ASSERT_OK_PTR(data, "malloc")) 29 + goto out; 30 + digests = malloc((MAX_LEN + 1) * SHA256_DIGEST_LENGTH); 31 + if (!ASSERT_OK_PTR(digests, "malloc")) 32 + goto out; 33 + 34 + /* Generate MAX_LEN bytes of "random" data deterministically. */ 35 + for (i = 0; i < MAX_LEN; i++) { 36 + seed = (seed * 25214903917 + 11) & ((1ULL << 48) - 1); 37 + data[i] = (__u8)(seed >> 16); 38 + } 39 + 40 + /* Calculate a digest for each length 0 through MAX_LEN inclusively. */ 41 + for (i = 0; i <= MAX_LEN; i++) 42 + libbpf_sha256(data, i, &digests[i * SHA256_DIGEST_LENGTH]); 43 + 44 + /* Calculate and verify the digest of all the digests. */ 45 + libbpf_sha256(digests, (MAX_LEN + 1) * SHA256_DIGEST_LENGTH, 46 + digest_of_digests); 47 + ASSERT_MEMEQ(digest_of_digests, expected_digest_of_digests, 48 + SHA256_DIGEST_LENGTH, "digest_of_digests"); 49 + out: 50 + free(data); 51 + free(digests); 52 + }