分享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;
2021年7月1日补充:
第一种方案需要依赖Nettle,最新的resty-nettle已不再需要修改上方提到的代码,使用时的代码无需修改,完全兼容,centos7编译安装最新的nettle时不要用官方那个install指南,编译后在使用时会报nettle_base64_decode_update: Assertion `*dst_length >= ((((src_length) + 1) * 6) / 8)' failed.
参照下方的方案通过:
wget https://ftp.gnu.org/gnu/nettle/nettle-3.7.3.tar.gz
tar -zxf nettle-3.7.3.tar.gz
cd nettle-3.7.3
./configure --prefix=/usr --enable-mini-gmp && make
make install
