Comparison

util-src/hashes.c @ 11541:13b84682518e 0.11

util.hashes: Add constant-time string comparison (binding to CRYPTO_memcmp)
author Matthew Wild <mwild1@gmail.com>
date Mon, 10 May 2021 16:24:54 +0100
parent 9962:29bc3dff3419
child 11560:3bbb1af92514
comparison
equal deleted inserted replaced
11540:1937b3c3efb5 11541:13b84682518e
21 #include <inttypes.h> 21 #include <inttypes.h>
22 #endif 22 #endif
23 23
24 #include "lua.h" 24 #include "lua.h"
25 #include "lauxlib.h" 25 #include "lauxlib.h"
26 #include <openssl/crypto.h>
26 #include <openssl/sha.h> 27 #include <openssl/sha.h>
27 #include <openssl/md5.h> 28 #include <openssl/md5.h>
28 #include <openssl/hmac.h> 29 #include <openssl/hmac.h>
29 30
30 #if (LUA_VERSION_NUM == 501) 31 #if (LUA_VERSION_NUM == 501)
187 lua_pushlstring(L, (char *)res.bytes, SHA_DIGEST_LENGTH); 188 lua_pushlstring(L, (char *)res.bytes, SHA_DIGEST_LENGTH);
188 189
189 return 1; 190 return 1;
190 } 191 }
191 192
193 static int Lhash_equals(lua_State *L) {
194 size_t len1, len2;
195 const char *s1 = luaL_checklstring(L, 1, &len1);
196 const char *s2 = luaL_checklstring(L, 2, &len2);
197 if(len1 == len2) {
198 lua_pushboolean(L, CRYPTO_memcmp(s1, s2, len1) == 0);
199 } else {
200 lua_pushboolean(L, 0);
201 }
202 return 1;
203 }
204
192 static const luaL_Reg Reg[] = { 205 static const luaL_Reg Reg[] = {
193 { "sha1", Lsha1 }, 206 { "sha1", Lsha1 },
194 { "sha224", Lsha224 }, 207 { "sha224", Lsha224 },
195 { "sha256", Lsha256 }, 208 { "sha256", Lsha256 },
196 { "sha384", Lsha384 }, 209 { "sha384", Lsha384 },
199 { "hmac_sha1", Lhmac_sha1 }, 212 { "hmac_sha1", Lhmac_sha1 },
200 { "hmac_sha256", Lhmac_sha256 }, 213 { "hmac_sha256", Lhmac_sha256 },
201 { "hmac_sha512", Lhmac_sha512 }, 214 { "hmac_sha512", Lhmac_sha512 },
202 { "hmac_md5", Lhmac_md5 }, 215 { "hmac_md5", Lhmac_md5 },
203 { "scram_Hi_sha1", LscramHi }, 216 { "scram_Hi_sha1", LscramHi },
217 { "equals", Lhash_equals },
204 { NULL, NULL } 218 { NULL, NULL }
205 }; 219 };
206 220
207 LUALIB_API int luaopen_util_hashes(lua_State *L) { 221 LUALIB_API int luaopen_util_hashes(lua_State *L) {
208 #if (LUA_VERSION_NUM > 501) 222 #if (LUA_VERSION_NUM > 501)