fffonion / lua-resty-openssl

FFI-based OpenSSL binding for OpenResty
BSD 2-Clause "Simplified" License
130 stars 43 forks source link

cipher:final() returns nil #185

Open anbu1506 opened 1 week ago

anbu1506 commented 1 week ago
local cipher = require("resty.openssl.cipher")

local key = "12345678901234567890123456789012" -- 32 bytes
local iv = "1234567890123456" -- 16 bytes

local function init_encryption()
    local aes = cipher.new('aes256')
    aes:init(key, iv, {
        is_encrypt = true,
        no_padding = true
    })
    return aes
end

local function encrypt_chunk(aes, chunk)
    return aes:update(chunk)
end

local function complete_encryption(aes)
    return aes:final()
end

local function init_decryption()
    local aes = cipher.new('aes256')
    aes:init(key, iv, {
        is_encrypt = false,
        no_padding = true
    })
    return aes
end

local function decrypt_chunk(aes, chunk)
    return aes:update(chunk)
end

local function complete_decryption(aes)
    return aes:final()
end

return {
    init_encryption = init_encryption,
    encrypt_chunk = encrypt_chunk,
    complete_encryption = complete_encryption,
    init_decryption = init_decryption,
    decrypt_chunk = decrypt_chunk,
    complete_decryption = complete_decryption
}

anbu1506 commented 1 week ago

im using these functions in body filter in openresty . the upstream server encrypted data in body filter. the actual proxy decrypts it in its body filter

but its working fine . but i need to know why final() returns nil

fffonion commented 1 week ago

This is how block cipher works, it output data in a unit of a block at a time. If there's no remaining data when you call final then you will not receive output. Different padding will affect this behaviour. You can read more from https://docs.openssl.org/3.1/man3/EVP_EncryptInit/#description.