ROBLOX Lua 的低影响加密公式 [英] Low impact encryption formula for ROBLOX Lua
问题描述
在 ROBLOX 上的一个项目中,我正在寻找一种轻量级的纯 Lua 密码,它可以使用密钥相当快地加密和解密字符串.我一直在环顾四周,大多数解决方案都需要实现 C 库,或者对于我正在寻找的东西来说太重了.我对加密不太了解,但它不应该直截了当,但也不要太复杂.有没有我不知何故遗漏的图书馆可以解决这个问题?
In a project on ROBLOX, I am looking for a lightweight pure Lua cipher which can encrypt and decrypt a string fairly quickly using a key. I've been looking around, and most solutions require implementation of a C library, or are too heavy for what I'm looking for. I don't know too much about encryption, but it shouldn't be bluntly obvious, but not too complex. Is there a library out there that I'm somehow missing that would resolve this issue?
推荐答案
这是一个轻量级纯 Lua 密码的示例.
它适用于 Lua 5.1、5.2、5.3,无需外部库.
Here is an example of a lightweight pure Lua cipher.
It works on Lua 5.1, 5.2, 5.3 without external libraries.
do
-- This is your secret 67-bit key (any random bits are OK)
local Key53 = 8186484168865098
local Key14 = 4887
local inv256
function encode(str)
if not inv256 then
inv256 = {}
for M = 0, 127 do
local inv = -1
repeat inv = inv + 2
until inv * (2*M + 1) % 256 == 1
inv256[M] = inv
end
end
local K, F = Key53, 16384 + Key14
return (str:gsub('.',
function(m)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
m = m:byte()
local c = (m * inv256[M] - (H - M) / 128) % 256
K = L * F + H + c + m
return ('%02x'):format(c)
end
))
end
function decode(str)
local K, F = Key53, 16384 + Key14
return (str:gsub('%x%x',
function(c)
local L = K % 274877906944 -- 2^38
local H = (K - L) / 274877906944
local M = H % 128
c = tonumber(c, 16)
local m = (c + (H - M) / 128) * (2*M + 1) % 256
K = L * F + H + c + m
return string.char(m)
end
))
end
end
local s = 'Hello world'
print( encode(s) ) --> 80897dfa1dd85ec196bc84
print(decode(encode(s))) --> Hello world
这篇关于ROBLOX Lua 的低影响加密公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!