summaryrefslogtreecommitdiffstats
path: root/lualib/lua_selectors/common.lua
blob: cb2ffc37fdddd99e42efd7eb3038be21613c7857 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
--[[
Copyright (c) 2020, Vsevolod Stakhov <vsevolod@highsecure.ru>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--

local ts = require("tableshape").types
local exports = {}
local cr_hash = require 'rspamd_cryptobox_hash'

local blake2b_key = cr_hash.create_specific('blake2'):update('rspamd'):bin()

local function digest_schema()
  return {ts.one_of{'hex', 'base32', 'bleach32', 'rbase32', 'base64'}:is_optional(),
          ts.one_of{'blake2', 'sha256', 'sha1', 'sha512', 'md5'}:is_optional()}
end

exports.digest_schema = digest_schema

local function create_digest(data, args)

  local encoding = args[1] or 'hex'
  local ht = args[2] or 'blake2'

  local h, s

  if ht == 'blake2' then
    -- Hack to be compatible with various 'get_digest' methods
    h = cr_hash.create_keyed(blake2b_key):update(data)
  else
    h = cr_hash.create_specific(ht):update(data)
  end

  if encoding == 'hex' then
    s = h:hex()
  elseif encoding == 'base32' then
    s = h:base32()
  elseif encoding == 'bleach32' then
    s = h:base32('bleach')
  elseif encoding == 'rbase32' then
    s = h:base32('rfc')
  elseif encoding == 'base64' then
    s = h:base64()
  end

  return s
end

exports.create_digest = create_digest

return exports