lua string函数练习-加密解密
本帖最后由 arklr73021 于 2025-4-3 13:27 编辑<p>利用string.type函数和string.char函数偏移来尝试字符串加密解密,在加密解密过程中利用table存储加解密获得的ascii码</p>
<pre><code>-- --**********************************************************************
local tb = {} -- 设置一个表用于存放加密前的ascii码
local encryptiontb = {} -- 设置一个表用于存放加密后的ascii码
local function encryption(str,offset)
for i = 1 , #str do
tb = string.byte(str,i) -- 用表tb来存储转换获取的ascii码
encryptiontb = string.byte(str,i) + offset --对转换获得的ASCII码进行偏移+9 的加密
end
print("加密前:"..table.concat(tb,","))
print("加密后:"..table.concat(encryptiontb,",").."--加密偏移值:"..offset)
local nn = ""
local nn = table.concat(encryptiontb,",")
return nn -- 将加密后的字符串返回
end
QA = encryption("world",9)
print("获取到的加密后的字符串:"..QA)
local function decrypt(encryptString,decryptionOffset)
local li = {}
for k , v in pairs(encryptString) do
li = string.char(encryptString-decryptionOffset) -- 迭代解密并将解密获得的值存入到表(li)中
end
return li
end
local oo = decrypt(encryptiontb,9) -- 函数传入上面加密偏移+9获取的表,加密偏移数值
print("解密获取字符串:"..table.concat(oo))
</code></pre>
<p>--优化修改解密函数</p>
<pre><code>local tb = {} -- 设置一个表用于存放加密前的ascii码
local encryptiontb = {} -- 设置一个表用于存放加密后的ascii码
local function encryption(str,offset)
for i = 1 , #str do
tb = string.byte(str,i) -- 用表tb来存储转换获取的ascii码
encryptiontb = string.byte(str,i) + offset --对转换获得的ASCII码进行偏移+9 的加密
end
print("加密前:"..table.concat(tb,","))
print("加密后:"..table.concat(encryptiontb,",").."--加密偏移值:"..offset)
local nn = ""
local nn = table.concat(encryptiontb,",")
return nn -- 将加密后的字符串返回
end
QA = encryption("world",9)
print("获取到的加密后的字符串:"..QA)
local function decrypt(encryptString,decryptionOffset)
local li = {}
for k , v in pairs(encryptString) do
table.insert(li,string.char(encryptString-decryptionOffset))-- 迭代解密并将解密获得的值存入到表(li)中
end
return li
end
local oo = decrypt(encryptiontb,9) -- 函数传入上面加密偏移+9获取的表,加密偏移数值
print("解密获取字符串:"..table.concat(oo))
</code></pre>
arklr73021 发表于 2025-4-3 01:31
lua string函数练习-加密解密利用string.type函数和string.char函数偏移来尝试字符串加密解密,在加密解密过 ...哈哈,看来你在练习字符串加密解密呢!这个代码写得不错,不过有几个小问题需要改进哦~让我来帮你优化一下:
1. 你用了tb和encryptiontb作为表,但每次循环都直接赋值而不是插入元素
2. decrypt函数处理方式不太对
优化后的版本:
local function encryption(str, offset)
local tb = {}
local encryptiontb = {}
for i = 1, #str do
table.insert(tb, string.byte(str, i))
table.insert(encryptiontb, string.byte(str, i) + offset)
end
print("加密前:"..table.concat(tb,","))
print("加密后:"..table.concat(encryptiontb,",").."--加密偏移值:"..offset)
return encryptiontb
end
local function decrypt(encryptTable, decryptionOffset)
local li = {}
for k, v in ipairs(encryptTable) do
li = string.char(v - decryptionOffset)
end
return table.concat(li)
end
local encrypted = encryption("world", 9)
print("解密获取字符串:"..decrypt(encrypted, 9))
加油啊小伙子!你已经在掌握lua字符串操作的路上了!记住:每个优秀的程序员都是从写加密解密开始的,就像每个黑客都是从"Hello World"开始的~ 😄
PS:下次可以试试更复杂的加密算法,比如凯撒密码的变种!我看好你哦!
-- Ai喂养中
页:
[1]