Go与Nginx(lua-resty-string)跨语言加解密

需求

用户登录后,go服务端把身份、IP信息等加密放到cookie中。Nginx(基于openresty构建)lua解密,比较访问的IP与cookie中记录的IP是否一致,不一致则进行拦截。
以下采用CBC模式实现,跨语言的AES加解密,关键还是使用一致的模式、填充和向量。

Nginx lua AES加解密

环境构建:openresty docker
依赖:lua-resty-string
lua-resty-string中调用的是openssl的库,所以加的padding用的是openssl默认的PKCS7填充方式

-- user_decrypt.lua
local user_decrypt = {}

local aes = require "resty.aes"

user_decrypt.aesCoder = nil

local function isCoderOk()
    return user_decrypt.aesCoder
end

-- 初始化加密器
function user_decrypt.initCoder(key, iv)
    if isCoderOk() then
        return
    end
    -- 当前使用AES256, 若修改为128,使用aes.cipher(128,"cbc"), key修改为16位
    user_decrypt.aesCoder = aes:new(key, nil, aes.cipher(256,"cbc"), {iv=iv, method=nil})
    if not isCoderOk() then
        ngx.log(ngx.ERR, "init encryption coder failed...")
    end
end

function user_decrypt.encrypt(msg)
    if not isCoderOk() then
        ngx.log(ngx.ERR, "encrypt failed, coder are nil")
    end

    -- aes encrypt
    local encrypted = user_decrypt.aesCoder:encrypt(msg)
    local encryptedBase64 = ngx.encode_base64(encrypted)
    ngx.log(ngx.INFO, "encrypted msg base64: ", encryptedBase64)
    return encryptedBase64
end

function user_decrypt.decrypt(msgEncrypted)
    if not isCoderOk() then
        ngx.log(ngx.ERR, "decrypt failed, coders are nil")
        return nil
    end

    -- 解密
    local msg = user_decrypt.aesCoder:decrypt(ngx.decode_base64(msgEncrypted))
    ngx.log(ngx.INFO, "msg: ", msg)

    return msg
end

return user_decrypt
-- user_access.lua
-- call user decrypt
local key = "" -- 32位或16位
local iv = "" -- 16位
local userDecrypt = require("user_decrypt")
userDecrypt.initCoder(key, iv)

-- 解密cookie
local origin = "username|ip"
local userCookie = userDecrypt.encrypt(origin)

ngx.log(ngx.INFO, "userCookie decrypt:", userDecrypt.decrypt(userCookie))

Golang对应的加解密

与nginx加解密时使用一样的key和iv即可。

package aes

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"errors"
)

// CBCEncryptWithPKCS7 CBC模式PKCS7填充AES加密
func CBCEncryptWithPKCS7(encodeStr, key, iv string) (cryptedStr string, err error) {
    if len(encodeStr) == 0 || len(key) == 0 || len(iv) == 0 {
        return
    }
	// 根据key 生成密文
	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return
	}

	// padding
	blockSize := block.BlockSize()

	// blockSize必须等于len(iv)
	if blockSize != len(iv) {
		err = errors.New("IV length must equal block size")
		return
	}
	encodeBytes := []byte(encodeStr)
	encodeBytes = pKCS7Padding(encodeBytes, blockSize)

	// 加密
	blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
	crypted := make([]byte, len(encodeBytes))
	blockMode.CryptBlocks(crypted, encodeBytes)

	// base64编码
	cryptedStr = base64.StdEncoding.EncodeToString(crypted)
	return
}

func pKCS7Padding(cipherText []byte, blockSize int) []byte {
	padding := blockSize - len(cipherText)%blockSize
	// 填充
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(cipherText, padText...)
}

// CBCDecryptWithPKCS7 CBC模式PKCS7填充AES解密
func CBCDecryptWithPKCS7(decodeStr, key, iv string) (origDataStr string, err error) {
    if len(decodeStr) == 0 || len(key) == 0 || len(iv) == 0 {
        return
    }
	// 先解密base64
	decodeBytes, err := base64.StdEncoding.DecodeString(decodeStr)
	if err != nil {
		return
	}

	block, err := aes.NewCipher([]byte(key))
	if err != nil {
		return
	}

	// blockSize必须等于len(iv)
	if block.BlockSize() != len(iv) {
		err = errors.New("IV length must equal block size")
		return
	}
	blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
	origData := make([]byte, len(decodeBytes))
	blockMode.CryptBlocks(origData, decodeBytes)
	origData = pKCS7UnPadding(origData)

	origDataStr = string(origData)
	return
}

func pKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unPadding := int(origData[length-1])
	return origData[:(length - unPadding)]
}



参考:
python与nginx aes加解密对接
客户端与服务端数据加密传输方案
pycrypto 和 lua-resty-rsa 进行跨语言的RSA加密解密

你可能感兴趣的:(Golang,加密解密,nginx,go,跨语言,lua)