openresty开发lua-resty-openssl之对称加密解密

openresty开发lua-resty-openssl之对称加密解密

local cipher = require "resty.openssl.cipher"
local rand = require "resty.openssl.rand"
local pkey = require "resty.openssl.pkey"

-- cbc需要32位密钥随机生成32位秘钥
local random_bytes = rand.bytes(32)

-- 加密过程
local function aes_encrypt(data, key)
    -- 创建 AES-256-CBC 加密对象
    local c, err = cipher.new("aes-256-cbc")
    if not c then return nil, err end

    -- 生成随机 IV(AES-CBC 模式需要 16 字节 IV)
    local iv = rand.bytes(16)
    if not iv then return nil, "生成 IV 失败" end

    -- 初始化加密上下文
    local ok, err = c:init(key, iv, {is_encrypt=true}) -- true 表示加密模式
    if not ok then return nil, err end

    -- 加密数据(需处理填充)
    local encrypted, err = c:final(data)
    if not encrypted then return nil, err end

    -- 返回 IV + 加密后的数据(解密时需要 IV)
    return iv .. encrypted
end

-- 解密过程
local function aes_decrypt(encrypted_data, key)
    -- 提取 IV(前 16 字节)
    local iv = encrypted_data:sub(1, 16)
    local data = encrypted_data:sub(17)

    -- 创建解密对象
    local c, err = cipher.new("aes-256-cbc")
    if not c then return nil, err end

    -- 初始化解密上下文
    local ok, err = c:init(key, iv, {is_encrypt=false}) -- false 表示解密模式
    if not ok then return nil, err end

    -- 解密数据
    local decrypted, err = c:final(data)
    if not decrypted then return nil, err end

    return decrypted
end

-- 加密数据
local encode_bin = aes_encrypt("hello",random_bytes)

-- 输出解密结果
ngx.say(aes_decrypt(encode_bin,random_bytes))

 

posted @ 2025-10-16 14:44  liuxm-刘小明  阅读(4)  评论(0)    收藏  举报