You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
2.1 KiB
Lua

local resty_rsa = require "resty.rsa"
local bit = require "bit"
local cjson = require "cjson"
local str = require "resty.string"
local _M = {}
local bits = 2048
local step = {
[1024] = 128,
[2048] = 256,
}
function _M.getKey(size)
size = size or bits
return resty_rsa:generate_rsa_keys(size, true)
end
function _M.getBase64Key(size)
size = size or bits
local rsa_public_key, rsa_priv_key, _ = _M.getKey(size)
return ngx.encode_base64(rsa_public_key), ngx.encode_base64(rsa_priv_key)
end
--[[
私钥解密
@param encryptedData 已加密数据
@param privateKey 私钥(BASE64编码)
padding = resty_rsa.PADDING.RSA_PKCS1_OAEP_PADDING
]]
function _M.decryptByPrivateKey(encryptedData, privateKey)
local priv, err = resty_rsa:new({ private_key = privateKey, algorithm = "SHA256"})
assert(priv, err)
return priv:decrypt(encryptedData)
end
--[[
私钥解密(长文本)
@param encrypted 源数据
@param privateKey 公钥(BASE64编码)
]]
function _M.decryptLongByPrivateKey(encrypted, privateKey)
local priv, err = resty_rsa:new({ private_key = privateKey })
assert(priv, err)
local decrypted = ''
for i = 1, #encrypted, step[bits] do
local text = encrypted:sub(i, i + step[bits] - 1)
local d, err = priv:decrypt(text)
assert(d, err)
decrypted = decrypted .. d
end
return decrypted
end
--[[
公钥加密
@param data 源数据
@param publicKey 公钥(BASE64编码)
]]
function _M.encryptByPublicKey(data, publicKey)
local pub, err = resty_rsa:new({ public_key = publicKey })
assert(pub, err)
return pub:encrypt(data)
end
--[[
公钥加密(长文本)
@param data 源数据
@param publicKey 公钥(BASE64编码)
]]
function _M.encryptLongByPublicKey(data, publicKey)
local pub, err = resty_rsa:new({ public_key = publicKey })
assert(pub, err)
local encrypted = ""
for i = 1, #data, 117 do
local text = data:sub(i, i + 117 - 1)
local s, err = pub:encrypt(text)
assert(s, err)
encrypted = encrypted .. s
end
return encrypted
end
return _M