[英]How to convert an hex string into ascii string in Lua
I have no knowledge at all about LUA and I'm trying to craft a small script for nginx. 我对LUA一无所知,我正在尝试为nginx编写一个小脚本。
I'm using the following library ( https://github.com/openresty/lua-resty-string ) to encrypt some data. 我正在使用以下库( https://github.com/openresty/lua-resty-string )加密一些数据。 Specifically I'm using the code for AES 256 CBC (SHA-512, salted) encryption and storing the hex-encoded encrypted string as shown in the example.
具体来说,我正在使用AES 256 CBC(SHA-512,盐腌)加密代码,并存储十六进制编码的加密字符串,如示例所示。
The issue now is that I need to get that hex string back to the decrypt method which expects an ASCII string. 现在的问题是,我需要将十六进制字符串返回到需要ASCII字符串的解密方法。
This is an example of the encrypted hex string: 这是加密的十六进制字符串的示例:
fdbcc47fe5825d49ac3429d4f8408fa4b6528dd99d938f122ee7f00ab71ae0c5c73d29d4f54ea1fbefe706b5dca04f6b6c6b8b96d9807ef58eaba07c6c6cefaf6ad8673b43a4e243fb2912fb4ff93de6488c4795ebb09ecd7a40b7c9dc2003be4ff93425d2d74688208fa4d2a8d22f32490666550f4b01340de708d7aa5bc8468d171da400f59fcff4e7d371d7ab9b48fdfde29aefc0af78b2f934927a7713994c1e8f9435067c851efc5d300405c74d
Just had to write one recently for pretty much same reason. 出于几乎相同的原因,最近不得不写一个。 Abuse
gsub
- capture each two chars and replace them with pre-calculated values from hexnumber->character map. 滥用
gsub
捕获每个两个字符,并用hexnumber-> character map中的预先计算的值替换它们。
-- Needs to be only done once
local hex_to_char = {}
for idx = 0, 255 do
hex_to_char[("%02X"):format(idx)] = string.char(idx)
hex_to_char[("%02x"):format(idx)] = string.char(idx)
end
-- Sometime later
str = "fdbcc47fe5825d49ac3429d4f8408fa4b6528dd99d938f122ee7f00ab71ae0c5c73d29d4f54ea1fbefe706b5dca04f6b6c6b8b96d9807ef58eaba07c6c6cefaf6ad8673b43a4e243fb2912fb4ff93de6488c4795ebb09ecd7a40b7c9dc2003be4ff93425d2d74688208fa4d2a8d22f32490666550f4b01340de708d7aa5bc8468d171da400f59fcff4e7d371d7ab9b48fdfde29aefc0af78b2f934927a7713994c1e8f9435067c851efc5d300405c74d"
print(str:gsub("(..)", hex_to_char))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.