Lua中使用\xhh编码进行AES加密

我用Python实现了使用AES-128加密字符串或二进制字符串,并将输出编码为常规十六进制文字,例如\xhh。我想用Lua实现这个函数

local AESCipher = {}
AES_CIPHER.__index = AESCipher
local base64 = require("base64")
local crypto = require("crypto")

function AESCipher.new(key)
    local self = setmetatable({}, AES_CIPHER)
    self.bs = 16
    self.key = key
    return self
end

function AESCipher.encrypt(self, raw, use_base64)
    use_base64 = use_base64 or true
    raw = self:_pad(raw)
    local crypted_text = crypto.encrypt("aes-128-ecb", self.key, raw, "raw")
    if use_base64 then
        return base64.encode(crypted_text)
    else
        return crypted_text
    end
end

function AESCipher.decrypt(self, enc, use_base64)
    use_base64 = use_base64 or true
    if use_base64 then
        enc = base64.decode(enc)
    end
    local raw = crypto.decrypt("aes-128-ecb", self.key, enc, "raw")
    return self:_unpad(raw)
end

function AESCipher._pad(self, s)
    local padnum = self.bs - math.fmod(#s, self.bs)
    return s .. string.rep(string.char(padnum), padnum)
end

function AESCipher._unpad(self, s)
    local padnum = string.byte(s:sub(-1))
    return s:sub(1, -1 * padnum)
end

return AESCipher
local AESCipher = require("AESCipher")
local key = "30a91c993c721aa9"
local test_cipher = AESCipher:new(key)
local payload = "{\"gwId\":\"315716865002915c2717\",\"devId\":\"315716865002915c2717\",\"uid\":\"315716865002915c2717\",\"t\":\"1633628358\"}"
local encrypted = test_cipher:encrypt(payload,false)
print(encrypted)

输出为:

b'\xe15\xf8\xc3\xc1)eW\x19\x0b/\x8d\xaf\xa8\xe0\xb6\xd4\xb7\xf7\xcf\xe4\x02\xa4\xab\xfft\x00]B\xea\xf5\r\xcbI\xef\xf9\xd8\xd6v\x02\xa6&\x0e\xe7\x19\x14\xde\xa3\xd0\xc4\xfb\xcb\xfa\x8c\xb8\x9fd\xa6v@\xdf\x03\xc7\xb8\xe5fe\xaf_\xdc\x931\xff\xfc\xfc\x85\x0b3\x92w\xe7k\x1c~}\xb2"\xe9\xc1\xe0\x9a\x12\xb3\xcak\x8en<t\xdd\x12n9Q\x8eX!\xaba2\x16\x9c'

我该如何在Lua中使用这种编码实现加密功能,我尝试了多种库,但输出的编码不像上面的编码,我该怎么办?

原文链接 https://stackoverflow.com/questions/71199324

点赞