5
5
#include " crypto/sha256.h"
6
6
#include " crypto/common.h"
7
7
8
+ #include < assert.h>
8
9
#include < string.h>
9
10
#include < atomic>
10
11
@@ -140,7 +141,36 @@ void Transform(uint32_t* s, const unsigned char* chunk, size_t blocks)
140
141
141
142
} // namespace sha256
142
143
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;
144
174
145
175
} // namespace
146
176
@@ -150,10 +180,12 @@ std::string SHA256AutoDetect()
150
180
uint32_t eax, ebx, ecx, edx;
151
181
if (__get_cpuid (1 , &eax, &ebx, &ecx, &edx) && (ecx >> 19 ) & 1 ) {
152
182
Transform = sha256_sse4::Transform;
183
+ assert (SelfTest (Transform));
153
184
return " sse4" ;
154
185
}
155
186
#endif
156
187
188
+ assert (SelfTest (Transform));
157
189
return " standard" ;
158
190
}
159
191
0 commit comments