#!/usr/local/bin/lua50 --[[ -- $Id: test.lua,v 1.3 2006/08/25 03:24:17 nezroy Exp $ -- See Copyright Notice in license.html --]] require("crypto") local evp = crypto.evp local hmac = crypto.hmac md5_KNOWN = "09920f6f666f8e7b09a8d00bd4d06873" sha1_KNOWN = "d6ed6e26ebeb37ba0792ec75a3d0b4dcec279d25" hmac_KNOWN = "70a7ea81a287d094c534cdd67be82e85066e13be" print("LuaCrypto version: " .. crypto._VERSION) print("") function report(w, s, F, t) print(w, s .. " " .. F) assert(s == _G[t .. "_KNOWN"]) end F = "test_crypto_file.txt" local file = io.open(F,"wb") file:write("This is a sample message to use for hashing tests.\n") file:close() for i, t in ipairs({"sha1", "md5", "sha1", "hmac"}) do print("testing " .. t) local d if (t == "hmac") then d = hmac.new("sha1", "luacrypto") else d = evp.new(t) end assert(io.input(F)) report("all", d:digest(io.read("*all")), F, t) d:reset(d) assert(io.input(F)) while true do local c = io.read(1) if c == nil then break end d:update(c) end report("loop", d:digest(), F, t) if (t ~= "hmac") then report("again", d:digest(), F, t) assert(io.input(F)) report("alone", evp.digest(t, io.read("*all")), F, t) else assert(io.input(F)) report("alone", hmac.digest("sha1", io.read("*all"), "luacrypto"), F, t); end assert(io.input(F)) d:reset() while true do local c = io.read(math.random(1, 16)) if c == nil then break end d:update(c) end report("reset", d:digest(d), F, t) report("known", _G[t .. "_KNOWN"], F, t) print("") end -- Random crypto module local rand = crypto.rand print("RAND version: " .. crypto._VERSION) print("") local SEEDFILE = "test_crypto_rand.txt" if rand.load(SEEDFILE) then print("loaded previous random seed") end if rand.status() then print("ready to generate") print("") else print("The PRNG does not yet have enough data.") local prompt = "Please type some random characters and press ENTER: " repeat io.write(prompt); io.flush() local line = io.read("*l") -- entropy of English is 1.1 bits per character rand.add(line, string.len(line) * 1.1 / 8) prompt = "More: " until rand.status() end local N = 20 local S = 5 print(string.format("generating %d sets of %d random bytes using pseudo_bytes()", S, N)) for i = 1, S do local data = assert(rand.pseudo_bytes(N)) print(table.concat({string.byte(data, 1, N)}, ",")) end print("") print(string.format("generating %d sets of %d random bytes using bytes()", S, N)) for i = 1, S do local data = assert(rand.bytes(N)) print(table.concat({string.byte(data, 1, N)}, ",")) end print("") print("saving seed in " .. SEEDFILE) print("") rand.write(SEEDFILE) -- don't leave any sensitive data lying around in memory print("cleaning up state") print("") rand.cleanup() print("all tests passed")