Comparison

util-src/hashes.c @ 12562:4f4d096a14cb

util.hashes: Refactor PBKDF2 to deduplicate code
author Kim Alvefur <zash@zash.se>
date Thu, 10 Sep 2020 21:58:25 +0200
parent 12561:adfb46a3e8a7
child 12563:d9a4e28689eb
comparison
equal deleted inserted replaced
12561:adfb46a3e8a7 12562:4f4d096a14cb
188 static int Lhmac_md5(lua_State *L) { 188 static int Lhmac_md5(lua_State *L) {
189 return Levp_hmac(L, EVP_md5()); 189 return Levp_hmac(L, EVP_md5());
190 } 190 }
191 191
192 192
193 static int Lpbkdf2_sha1(lua_State *L) { 193 static int Levp_pbkdf2(lua_State *L, const EVP_MD *evp, size_t out_len) {
194 unsigned char out[SHA_DIGEST_LENGTH]; 194 unsigned char out[EVP_MAX_MD_SIZE];
195 195
196 size_t pass_len, salt_len; 196 size_t pass_len, salt_len;
197 const char *pass = luaL_checklstring(L, 1, &pass_len); 197 const char *pass = luaL_checklstring(L, 1, &pass_len);
198 const unsigned char *salt = (unsigned char *)luaL_checklstring(L, 2, &salt_len); 198 const unsigned char *salt = (unsigned char *)luaL_checklstring(L, 2, &salt_len);
199 const int iter = luaL_checkinteger(L, 3); 199 const int iter = luaL_checkinteger(L, 3);
200 200
201 if(PKCS5_PBKDF2_HMAC(pass, pass_len, salt, salt_len, iter, EVP_sha1(), SHA_DIGEST_LENGTH, out) == 0) { 201 if(PKCS5_PBKDF2_HMAC(pass, pass_len, salt, salt_len, iter, evp, out_len, out) == 0) {
202 return luaL_error(L, "PKCS5_PBKDF2_HMAC() failed"); 202 return luaL_error(L, "PKCS5_PBKDF2_HMAC() failed");
203 } 203 }
204 204
205 lua_pushlstring(L, (char *)out, SHA_DIGEST_LENGTH); 205 lua_pushlstring(L, (char *)out, out_len);
206 206
207 return 1; 207 return 1;
208 } 208 }
209 209
210 static int Lpbkdf2_sha1(lua_State *L) {
211 return Levp_pbkdf2(L, EVP_sha1(), SHA_DIGEST_LENGTH);
212 }
210 213
211 static int Lpbkdf2_sha256(lua_State *L) { 214 static int Lpbkdf2_sha256(lua_State *L) {
212 unsigned char out[SHA256_DIGEST_LENGTH]; 215 return Levp_pbkdf2(L, EVP_sha256(), SHA256_DIGEST_LENGTH);
213
214 size_t pass_len, salt_len;
215 const char *pass = luaL_checklstring(L, 1, &pass_len);
216 const unsigned char *salt = (unsigned char *)luaL_checklstring(L, 2, &salt_len);
217 const int iter = luaL_checkinteger(L, 3);
218
219 if(PKCS5_PBKDF2_HMAC(pass, pass_len, salt, salt_len, iter, EVP_sha256(), SHA256_DIGEST_LENGTH, out) == 0) {
220 return luaL_error(L, "PKCS5_PBKDF2_HMAC() failed");
221 }
222
223 lua_pushlstring(L, (char *)out, SHA256_DIGEST_LENGTH);
224 return 1;
225 } 216 }
226 217
227 static int Lhash_equals(lua_State *L) { 218 static int Lhash_equals(lua_State *L) {
228 size_t len1, len2; 219 size_t len1, len2;
229 const char *s1 = luaL_checklstring(L, 1, &len1); 220 const char *s1 = luaL_checklstring(L, 1, &len1);