哈希模块加载器

lua-users home
wiki

这是一个模块加载器的示例,它在加载模块之前验证模块的哈希值。它基于 LuaCrypto [1]。它并不真正安全,它只是作为示例创建,以展示如何添加新的模块加载器。(JeromeVuarand

module(..., package.seeall)

local crypto = require 'crypto'

local dtypes = {"md5", "md4", "md2", "sha1", "sha", "sha256", "sha512"}

local function load(modulename)
  -- Find source
  local filename
  local file,hashfile,hashtype
  local errmsg = ""
  for path in string.gmatch(package.path..";", "([^;]*);") do
    filename = string.gsub(path, "%?", (string.gsub(modulename, "%.", "\\")))
    file = io.open(filename, "rb")
    -- If we found a module check if it has a hash file
    if file then
      for _,dtype in ipairs(dtypes) do
        hashfile = io.open(filename.."."..dtype, "rb")
        if hashfile then
          hashtype = dtype
          break
        end
      end
    end
    if hashfile then
      break
    end
    errmsg = errmsg.."\n\tno file '"..filename.."' (signed)"
  end
  if not file then
    return errmsg
  end
  -- Read source file
  local source = file:read("*a")
  -- Read saved hash
  local hash = hashfile:read("*a"):gsub("[^%x]", "")
  -- Check that the saved hash match the file hash
  assert(crypto.evp.digest(hashtype, source)==hash,
    "module "..modulename.." (from file '"..filename.."')"
    .." does not match its "..hashtype.." hash")
  -- Compile and return the module
  return assert(loadstring(source, filename))
end

-- Install the loader so that it's called just before the normal Lua loader
table.insert(package.loaders, 2, load)

您可以在 [hashedmodules-200705100234.zip] 中找到该代码,其中包含示例模块和测试脚本。


最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2008 年 2 月 27 日下午 5:36 GMT (差异)