|
| 1 | +-- SPDX-License-Identifier: MIT |
| 2 | +-- Author: Jianhui Zhao <zhaojh329@gmail.com> |
| 3 | + |
| 4 | +local M = {} |
| 5 | + |
| 6 | +local blocksize = 64 |
| 7 | + |
| 8 | +local methods = {} |
| 9 | + |
| 10 | +function methods:update(data) |
| 11 | + assert(type(data) == 'string', 'expecting data to be a string') |
| 12 | + |
| 13 | + self.ctx:update(data) |
| 14 | +end |
| 15 | + |
| 16 | +function methods:final() |
| 17 | + return self.hash.sum(self.key .. self.ctx:final()) |
| 18 | +end |
| 19 | + |
| 20 | +local metatable = { |
| 21 | + __index = methods |
| 22 | +} |
| 23 | + |
| 24 | +function M.new(hash, key) |
| 25 | + local mtname = hash and hash.mtname |
| 26 | + |
| 27 | + assert(mtname == 'eco{md5}' |
| 28 | + or mtname == 'eco{sha1}' |
| 29 | + or mtname == 'eco{sha256}', |
| 30 | + 'expecting hash to be a hash module') |
| 31 | + |
| 32 | + assert(type(key) == 'string', 'expecting key to be a string') |
| 33 | + |
| 34 | + if #key > blocksize then |
| 35 | + key = hash.sum(key) |
| 36 | + end |
| 37 | + |
| 38 | + local key_xord_with_0x36 = key:gsub('.', function(c) |
| 39 | + return string.char(c:byte() ~ 0x36) |
| 40 | + end) .. string.rep(string.char(0x36), blocksize - #key) |
| 41 | + |
| 42 | + local key_xord_with_0x5c = key:gsub('.', function(c) |
| 43 | + return string.char(c:byte() ~ 0x5c) |
| 44 | + end) .. string.rep(string.char(0x5c), blocksize - #key) |
| 45 | + |
| 46 | + local ctx = hash.new() |
| 47 | + |
| 48 | + ctx:update(key_xord_with_0x36) |
| 49 | + |
| 50 | + return setmetatable({ |
| 51 | + ctx = ctx, |
| 52 | + hash = hash, |
| 53 | + key = key_xord_with_0x5c |
| 54 | + }, metatable) |
| 55 | +end |
| 56 | + |
| 57 | +function M.sum(hash, key, data) |
| 58 | + local ctx = M.new(hash, key) |
| 59 | + |
| 60 | + ctx:update(data) |
| 61 | + |
| 62 | + return ctx:final() |
| 63 | +end |
| 64 | + |
| 65 | +return M |
0 commit comments