@@ 8,7 8,7 @@ local rotr = u32.rotr
local shr = u32.shr
local sum = u32.sum
-M.sha256 = {
+M.sha256 = setmetatable({
H0 = {
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
@@ 32,21 32,15 @@ M.sha256 = {
bsig1 = function(x) return rotr(x, 6) ~ rotr(x, 11) ~ rotr(x, 25) end,
ssig0 = function(x) return rotr(x, 7) ~ rotr(x, 18) ~ shr(x, 3) end,
ssig1 = function(x) return rotr(x, 17) ~ rotr(x, 19) ~ shr(x, 10) end,
-}
-
-function M.sha256.init(buf)
- H = {}
- for k, v in pairs(M.sha256.H0) do
- H[k] = v
- end
-
- local buf = buf or ""
- return {
- H = H,
- buf = buf,
- L = #buf,
- }
-end
+}, {
+ __call = function(L, ...)
+ local ctx = L.init()
+ for _, bs in ipairs({...}) do
+ ctx:update(bs)
+ end
+ return ctx:finalize()
+ end,
+})
local function sha256_process_blocks(ctx)
if #ctx.buf < 64 then
@@ 113,6 107,7 @@ function M.sha256.update(ctx, bs)
ctx.buf = ctx.buf .. bs
ctx.L = ctx.L + #bs
sha256_process_blocks(ctx)
+ return ctx
end
function M.sha256.pad(buf, l)
@@ 143,4 138,22 @@ function M.sha256.finalize(ctx)
return digest
end
+function M.sha256.init(buf)
+ H = {}
+ for k, v in pairs(M.sha256.H0) do
+ H[k] = v
+ end
+
+ local buf = buf or ""
+ local ctx = {
+ H = H,
+ buf = buf,
+ L = #buf,
+ update = M.sha256.update,
+ finalize = M.sha256.finalize,
+ }
+ sha256_process_blocks(ctx)
+ return ctx
+end
+
return M
@@ 7,17 7,25 @@ local F = require("fresh")
local N = 100
function test_sha256_empty()
- local ctx = L.sha256.init()
- local digest = L.sha256.finalize(ctx)
+ local digest = L.sha256.init():finalize()
lu.assertEquals(H.encode(digest), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
end
function test_sha256_foo()
- local ctx = L.sha256.init("foo")
- local digest = L.sha256.finalize(ctx)
+ local digest = L.sha256.init("foo"):finalize()
lu.assertEquals(H.encode(digest), "2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae")
end
+function test_sha256_foobar_1()
+ local digest = L.sha256.init("foo"):update("bar"):finalize()
+ lu.assertEquals(H.encode(digest), "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2")
+end
+
+function test_sha256_foobar_2()
+ local digest = L.sha256("foo", "bar")
+ lu.assertEquals(H.encode(digest), "c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2")
+end
+
function test_sha256_pad()
msg = H.decode("6162636465")
padded = L.sha256.pad(msg, #msg)
@@ 31,9 39,9 @@ function test_sha256_fresh()
local bs2 = F.bytestring()
local ctx = L.sha256.init(bs0)
- L.sha256.update(ctx, bs1)
- L.sha256.update(ctx, bs2)
- local digest = L.sha256.finalize(ctx)
+ ctx:update(bs1)
+ ctx:update(bs2)
+ local digest = ctx:finalize()
lu.assertEquals(H.encode(digest), H.encode(ref.openssl.sha256(bs0, bs1, bs2)))
lu.assertEquals(H.encode(digest), H.encode(ref.rfc.sha256(bs0, bs1, bs2)))