spacewander / lua-resty-rsa

RSA encrypt/decrypt & sign/verify for OpenResty/LuaJIT
MIT License
266 stars 101 forks source link

请问,怎么实现分段加密呢? #15

Closed woshiyjs123 closed 7 years ago

woshiyjs123 commented 7 years ago

要加密的数据比较大(超过256字节),我用java分段加密,lua怎么实现分段解密呢? 麻烦有解决的兄弟,提供一下方案

spacewander commented 7 years ago

作为块加密算法,每个 RSA 加密之后的块大小为 128 字节。所以你可以按 128 字节进行分割,逐块解密后合并起来。

看下面的例子:

            local resty_rsa = require "resty.rsa"
            local pub, err = resty_rsa:new({ public_key = RSA_PUBLIC_KEY })
            if not pub then
                ngx.say("new rsa err: ", err)
                return
            end
            local very_long_data = ("hello"):rep(201)
            local data_len = #very_long_data
            local encrypted_data = {}
            local segment_size = 100
            for i = 1, data_len, segment_size do
                local ceiling = math.min(i+segment_size-1, data_len)
                local encrypted, err = pub:encrypt(very_long_data:sub(i, ceiling))
                if not encrypted then
                    ngx.say("failed to encrypt: ", err)
                    return
                end
                table.insert(encrypted_data, encrypted)
            end

            local priv, err = resty_rsa:new({ private_key = RSA_PRIV_KEY })
            if not priv then
                ngx.say("new rsa err: ", err)
                return
            end
            local decrypted_data = {}
            -- 你自己的分块逻辑应该在这里引入
            for _, data in ipairs(encrypted_data) do
                -- 每个data字符串的大小是128字节
                local decrypted, err = priv:decrypt(data)
                if not decrypted then
                    ngx.say("failed to decrypt ", err)
                    return
                end
                table.insert(decrypted_data, decrypted)
            end
            ngx.say(table.concat(decrypted_data) == very_long_data)
woshiyjs123 commented 7 years ago

多谢,已经解决了