80 lines
2.2 KiB
Lua
80 lines
2.2 KiB
Lua
local pkey = require "resty.openssl.pkey"
|
||
local str = require "resty.string"
|
||
|
||
local _M = {}
|
||
|
||
-- 生成密钥对
|
||
function _M:generate_rsa_keys(length)
|
||
-- 生成2048位RSA密钥对
|
||
local key, err = pkey.new({
|
||
type = "RSA",
|
||
bits = length or 2048
|
||
})
|
||
|
||
-- 提取公钥
|
||
local pub_pem = key:to_PEM("public")
|
||
-- 提取私钥
|
||
local priv_pem = key:to_PEM("private")
|
||
|
||
if not priv_pem or not pub_pem then
|
||
return nil, nil, "转换 PEM 格式失败: " .. (err or "未知错误")
|
||
end
|
||
|
||
return pub_pem, priv_pem, nil
|
||
end
|
||
|
||
-- 公钥加密(用于生成测试数据)
|
||
function _M:rsa_encrypt(pub_key, plaintext)
|
||
--
|
||
local pkey, err = pkey.new(pub_key)
|
||
if not pkey or not plaintext then
|
||
return nil, "参数错误"
|
||
end
|
||
|
||
local oaep_params = {
|
||
oaep_md = "sha256", -- 对应pkey.lua中的opts.oaep_md
|
||
mgf1_md = "sha256", -- 对应pkey.lua中的opts.mgf1_md
|
||
label = nil
|
||
}
|
||
|
||
local RSA_PKCS1_OAEP_PADDING = "4"
|
||
local ciphertext, err = pkey:encrypt(plaintext, RSA_PKCS1_OAEP_PADDING ,oaep_params)
|
||
if not ciphertext then
|
||
return nil, "加密失败: " .. (err or "未知错误")
|
||
end
|
||
-- 返回Base64编码的密文(便于传输存储)
|
||
return ngx.encode_base64(ciphertext), nil
|
||
end
|
||
|
||
-- 私钥解密(核心实现)
|
||
function _M:rsa_decrypt(private_key, encrypted_data)
|
||
|
||
local pkey, err = pkey.new(private_key)
|
||
|
||
if not pkey or not encrypted_data then
|
||
return nil, "参数错误(公钥或密文为空)"
|
||
end
|
||
|
||
-- 1. 先解码Base64密文
|
||
local ciphertext, err = ngx.decode_base64(encrypted_data)
|
||
if not ciphertext then
|
||
return nil, "Base64解码失败: " .. (err or "无效密文")
|
||
end
|
||
-- 2. 设置解密填充方式(必须与加密时一致)
|
||
local oaep_params = {
|
||
oaep_md = "sha256", -- 对应pkey.lua中的opts.oaep_md
|
||
mgf1_md = "sha256", -- 对应pkey.lua中的opts.mgf1_md
|
||
label = nil
|
||
}
|
||
|
||
local RSA_PKCS1_OAEP_PADDING = "4"
|
||
-- 3. 执行解密
|
||
local result, err = pkey:decrypt(ciphertext, RSA_PKCS1_OAEP_PADDING, oaep_params)
|
||
if not result then
|
||
return nil, "解密返回空结果"
|
||
end
|
||
|
||
return result, nil -- 返回解密后的原始数据
|
||
end
|
||
|
||
return _M |