Skip to content

Commit fa9be90

Browse files
committed
Add selftest for SHA256 transform
1 parent c1ccb15 commit fa9be90

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

src/crypto/sha256.cpp

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#include "crypto/sha256.h"
66
#include "crypto/common.h"
77

8+
#include <assert.h>
89
#include <string.h>
910
#include <atomic>
1011

@@ -140,7 +141,36 @@ void Transform(uint32_t* s, const unsigned char* chunk, size_t blocks)
140141

141142
} // namespace sha256
142143

143-
void (*Transform)(uint32_t*, const unsigned char*, size_t) = sha256::Transform;
144+
typedef void (*TransformType)(uint32_t*, const unsigned char*, size_t);
145+
146+
bool SelfTest(TransformType tr) {
147+
static const unsigned char in1[65] = {0, 0x80};
148+
static const unsigned char in2[129] = {
149+
0,
150+
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
151+
32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
152+
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
153+
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0
154+
};
155+
static const uint32_t init[8] = {0x6a09e667ul, 0xbb67ae85ul, 0x3c6ef372ul, 0xa54ff53aul, 0x510e527ful, 0x9b05688cul, 0x1f83d9abul, 0x5be0cd19ul};
156+
static const uint32_t out1[8] = {0xe3b0c442ul, 0x98fc1c14ul, 0x9afbf4c8ul, 0x996fb924ul, 0x27ae41e4ul, 0x649b934cul, 0xa495991bul, 0x7852b855ul};
157+
static const uint32_t out2[8] = {0xce4153b0ul, 0x147c2a86ul, 0x3ed4298eul, 0xe0676bc8ul, 0x79fc77a1ul, 0x2abe1f49ul, 0xb2b055dful, 0x1069523eul};
158+
uint32_t buf[8];
159+
memcpy(buf, init, sizeof(buf));
160+
// Process nothing, and check we remain in the initial state.
161+
tr(buf, nullptr, 0);
162+
if (memcmp(buf, init, sizeof(buf))) return false;
163+
// Process the padded empty string (unaligned)
164+
tr(buf, in1 + 1, 1);
165+
if (memcmp(buf, out1, sizeof(buf))) return false;
166+
// Process 64 spaces (unaligned)
167+
memcpy(buf, init, sizeof(buf));
168+
tr(buf, in2 + 1, 2);
169+
if (memcmp(buf, out2, sizeof(buf))) return false;
170+
return true;
171+
}
172+
173+
TransformType Transform = sha256::Transform;
144174

145175
} // namespace
146176

@@ -150,10 +180,12 @@ std::string SHA256AutoDetect()
150180
uint32_t eax, ebx, ecx, edx;
151181
if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) && (ecx >> 19) & 1) {
152182
Transform = sha256_sse4::Transform;
183+
assert(SelfTest(Transform));
153184
return "sse4";
154185
}
155186
#endif
156187

188+
assert(SelfTest(Transform));
157189
return "standard";
158190
}
159191

0 commit comments

Comments
 (0)