分享2种openresty des3加密的代码,节省大家脱坑的时间:
1.based on lua-resty-nettle
local pkcs7 = require "resty.nettle.padding.pkcs7"
local base64 = require "resty.nettle.base64"
local des = require "resty.nettle.des"
local cipher= des.new("密钥")
local encrypted = cipher:encrypt(pkcs7.pad('要加密的文本', 8))
ngx.print(base64.encode(encrypted))
2.based on lua-lockbox
local Array = require("lockbox.util.array")
local Stream = require("lockbox.util.stream")
local ECBMode = require("lockbox.cipher.mode.ecb")
local PKCS7Padding = require("lockbox.padding.pkcs7")
local DESCipher = require("lockbox.cipher.des3")
local Base64 = require("lockbox.util.base64")
local cipher = ECBMode.Cipher().setKey(Array.fromString("密钥")).setBlockCipher(DESCipher).setPadding(PKCS7Padding)
local res = cipher.init().update(Stream.fromArray(Array.fromString(""))).update(Stream.fromArray(Array.fromString('要加密的文本'))).finish().asBytes()
local out = Base64.fromArray(res)
ngx.print(out)
推荐第1种,性能还可以,lua-lockbox需要修改lockbox.padding.pkcs7中的一行代码local paddingCount = blockSize - byteCount % blockSize;