function _M.decryptfile(self, filename)
local s_len = 2048
local buf = ffi_new("unsigned char[?]", s_len)
local out_len = ffi_new("int[1]")
local tmp_len = ffi_new("int[1]")
local ctx = self._decrypt_ctx
local hinfile, houtfile, data, decdata, tlen
hinfile = io.open(filename, "rb")
if hinfile == nil then
return nil
end
houtfile = io.open(filename:match("(%w+)."), "wb")
if houtfile == nil then
return nil
end
if C.EVP_DecryptInit_ex(ctx, nil, nil, nil, nil) == 0 then
return nil
end
while true do
data = hinfile:read(2048)
if data == nil then
break
end
s_len = #data
buf = ffi_new("unsigned char[?]", s_len)
--- It will Segmentation fault (core dumped) on after the six iteration
if C.EVP_DecryptUpdate(ctx, buf, out_len, data, s_len) == 0 then
return nil
else
decdata = ffi_str(buf, out_len[0] + tmp_len[0])
end
houtfile:write(decdata)
end
-- if the file is small then C.EVP_DecryptFinal_ex will Segmentation fault (core dumped)
if C.EVP_DecryptFinal_ex(ctx, buf + out_len[0], tmp_len) == 0 then
return nil
else
decdata = ffi_str(buf, tmp_len[0])
houtfile:write(decdata)
end
houtfile:flush()
houtfile:close()
hinfile:close()
return true
end
function _M.encryptfile(self, filename)
local s_len = 2048
local max_len = s_len + 16
local buf = ffi_new("unsigned char[?]", max_len)
local out_len = ffi_new("int[1]")
local tmp_len = ffi_new("int[1]")
local ctx = self._encrypt_ctx
local hinfile, houtfile, data, encdata
hinfile = io.open(filename, "rb")
if hinfile == nil then
return nil
end
houtfile = io.open(filename..".enc", "wb")
if houtfile == nil then
return nil
end
if C.EVP_EncryptInit_ex(ctx, nil, nil, nil, nil) == 0 then
return nil
end
while true do
data = hinfile:read(2048)
if data == nil then
break
end
s_len = #data
buf = ffi_new("unsigned char[?]", s_len+16)
if C.EVP_EncryptUpdate(ctx, buf, out_len, data, s_len) == 0 then
return nil
else
encdata = ffi_str(buf, out_len[0] + tmp_len[0])
end
houtfile:write(encdata)
end
if C.EVP_EncryptFinal_ex(ctx, buf , tmp_len) == 0 then
return nil
else
encdata = ffi_str(buf, tmp_len[0])
houtfile:write(encdata)
end
houtfile:flush()
houtfile:close()
hinfile:close()
return true
end