Lua 使用共享密钥加密

Lua Encryption with Shared Key

我一直在使用这个开源函数通过 base64 方法加密和解密字符串,我想知道是否有办法让我和一些朋友共享特定的 'key' 来制作它的工作方式是只有拥有此 'key' 的人才能正确加密或解密消息。

-- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de>
-- licensed under the terms of the LGPL2

-- character table string
local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

-- encoding
function enc(data)
  return ((data:gsub('.', function(x) 
    local r,b='',x:byte()
    for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
    return r;
  end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
    if (#x < 6) then return '' end
    local c=0
    for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
    return b:sub(c+1,c+1)
  end)..({ '', '==', '=' })[#data%3+1])
end

-- decoding
function dec(data)
  data = string.gsub(data, '[^'..b..'=]', '')
  return (data:gsub('.', function(x)
    if (x == '=') then return '' end
    local r,f='',(b:find(x)-1)
    for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
    return r;
  end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
    if (#x ~= 8) then return '' end
    local c=0
    for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
    return string.char(c)
  end))
end

所以,假设我和三个朋友得到了类似的功能,我们都有一个名为 'flibble' 的私钥...我们如何共享其他人无法破译的消息?

不,不是 base 64。Base 64 不是加密,它是编码。 Base 64 不采用密钥作为参数,只是采用二进制并将其转换为可打印的 ASCII。

当然有一些技巧可以使 base 64 看起来更像密文:只需放入一个经过处理的字母表(在您的例子中是变量 b)。然而,这是常见的替代品;因此,它应该被视为混淆而不是加密。我可以向一个随机的高中生解释如何破解它。

一般需要先使用分组密码+运算方式加密,然后进行编码。您需要 AES 之类的东西来保证机密性,需要 HMAC 来保证消息的完整性和真实性。

我会推荐类似 luacrypto 的内容。仅出于性能原因,您真的不想使用 Lua 等高级语言来执行加密。许多 Lua 库只提供 AES 或 HMAC,但不提供两者,而且许多似乎是一个人的项目,而不是很好的 supported/maintained 库 - 所以请谨慎选择。

local a = [[ your script here ]]

复制粘贴到这里 Base64Encode and decode

for encode = print(enc(a)) for decode = print(dec(a))