Smail_的gravatar头像
Smail_ 2019-10-29 11:35:28
openresty des3加密脱坑基地

分享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


打赏
最近浏览
fashion1314  LV5 2020年4月25日
q326063404  LV1 2019年12月21日
youwuzuichen  LV11 2019年11月11日
hhuangh  LV5 2019年11月8日
爷爷在此  LV16 2019年11月5日
q850717441 2019年11月1日
暂无贡献等级
nanjer  LV2 2019年11月1日
珍惜拥有  LV5 2019年11月1日
Smail_  LV19 2019年10月31日
苜蓿123456  LV10 2019年10月31日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友