反转一个解码函数

我正在尝试反转一个解码函数。这个函数使用一个字符串和一个密钥对字符串进行编码。这是代码:

function decode(key, code)
  return (code:gsub("..", function(h)
    return string.char((tonumber(h, 16) + 256 - 13 - key + 255999744) % 256)
  end))
end

如果我将“7A”作为“code”输入,将“9990”作为“key”,它将返回“g”

我尝试反转操作符并将解码函数的输出反馈回去,但是我得到一个错误,因为“tonumber()”返回nil。我怎样才能翻转这个函数?

点赞
用户1999909
用户1999909

通过使用这个 Lua基数转换器 的答案并翻转解码函数的运算符,我能够将输入转换回来。

以下是完整的代码:

function encodes(key, code)
  return (code:gsub("..", function(h)
    return string.char((tonumber(h, 16) + 256 - 13 - key + 255999744) % 256)
  end))
end

local floor,insert = math.floor, table.insert
function basen(n,b)
    n = floor(n)
    if not b or b == 10 then return tostring(n) end
    local digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    local t = {}
    local sign = ""
    if n < 0 then
        sign = "-"
    n = -n
    end
    repeat
        local d = (n % b) + 1
        n = floor(n / b)
        insert(t, 1, digits:sub(d,d))
    until n == 0
    return sign .. table.concat(t,"")
end

function decodes(key, code)
  return (code:gsub(".", function(h)
    out = (string.byte(h) - 256 + 13 + key - 255999744) % 256
    return basen(out,16)
  end))
end

a = encodes(9999, "7c7A")
print(a) --prints: `^
print("----------")
b = decodes(9999, a)
print(b) --prints: 7C7A
2018-09-05 15:02:05