openresty 里面 aes ecb加密

先上地址(代碼將就著用吧O(∩_∩)O哈哈~)

https://github.com/lilien1010/lua-bit

因為再nginx+lua,openresty項目要用到 AES的的ecb模式加解密,
但是春哥用openssl實現的string庫 我個人覺得不是很好理解。
作為一個PHPer,于是參照php的 mcrypt庫,利用luajit的ffi實現了一個aes加解密的庫。

aes encrypt with PHP:

mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,$text, MCRYPT_MODE_ECB );

aes encrypt with lua:

local data      =   'wait to be encrypted'
local key       =   '01234567890123456' --length is 16
local mc_ecb    = require("resty.ecb_mcrypt")
local ecb       = mc_ecb:new();
local enc_data  = ecb:encrypt(key,data );
ngx.print(enc_data)
--  you must use 'ngx.print' rather then 'ngx.say'
-- while 'ngx.say' will append a '\n'  at the end of string
需要注意輸出的數據在客戶端要主要數據尾巴后面的\0,因為默認是有padding模式的。而且輸出加密后的二進制數據,一定要用ngx.print,因為ngx.say會在數據的最后輸出換行符(已經坑了部分人了)

同時你需要在操作系統里面安裝 libmcrypt的庫

yum install libmcrypt libmcrypt-devel

其實利用類似的想法,基本上openresty里面缺少的庫,利用luajit的ffi從php擴展里面參照代碼,實現一份,還是挺簡單的。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容