/*
文件名:MD5Class.nut
路径:Dps_A/BaseClass/MD5Class/MD5Class.nut
创建日期:2024-09-20	00:06
文件用途:MD5类
*/
class MD5 {
    MD5_Init_ptr = Module.getExportByName(null, "MD5_Init");
    MD5_Update_ptr = Module.getExportByName(null, "MD5_Update");
    MD5_Final_ptr = Module.getExportByName(null, "MD5_Final");

    function MD5_Init(Ctx) {
        Sq_CallFunc(MD5_Init_ptr, "void", ["pointer"], Ctx);
    }

    function MD5_Update(Ctx, Buffer, Size) {
        Sq_CallFunc(MD5_Update_ptr, "void", ["pointer", "pointer", "int"], Ctx, Buffer, Size);
    }

    function MD5_Final(Ctx, Result) {
        Sq_CallFunc(MD5_Final_ptr, "void", ["pointer", "pointer"], Ctx, Result);
    }

    function base64_encode(input) {
        local base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        local inputLength = input.len();
        local i = 0;
        local j = 0;
        local charArray3 = array(3);
        local charArray4 = array(4);
        local encoded = "";

        while (inputLength--) {
            charArray3[i++] = input[inputLength];
            if (i == 3) {
                charArray4[0] = (charArray3[0] & 0xfc) >> 2;
                charArray4[1] = ((charArray3[0] & 0x03) << 4) + ((charArray3[1] & 0xf0) >> 4);
                charArray4[2] = ((charArray3[1] & 0x0f) << 2) + ((charArray3[2] & 0xc0) >> 6);
                charArray4[3] = charArray3[2] & 0x3f;

                for (i = 0; i< 4; i++) {
                    encoded += base64_chars[charArray4[i]];
                }
                i = 0;
            }
        }

        if (i) {
            for (j = i; j< 3; j++) {
                charArray3[j] = 0;
            }

            charArray4[0] = (charArray3[0] & 0xfc) >> 2;
            charArray4[1] = ((charArray3[0] & 0x03) << 4) + ((charArray3[1] & 0xf0) >> 4);
            charArray4[2] = ((charArray3[1] & 0x0f) << 2) + ((charArray3[2] & 0xc0) >> 6);
            charArray4[3] = charArray3[2] & 0x3f;

            for (j = 0; j< i + 1; j++) {
                encoded += base64_chars[charArray4[j]];
            }

            while (i++<3) {
                encoded += "=";
            }
        }

        return encoded;
    }

    function GetFile(FileName) {
        local Io = IO(FileName, "r+");

        local Ctx = Memory.alloc(0x100);
        MD5.MD5_Init(Ctx.C_Object);

        while (true) {
            local Buffer = Memory.alloc(0x1000);
            local Res = Io.ReadBuffer(0x1000);
            if (Res.count == 0) break;
            MD5.MD5_Update(Ctx.C_Object, Memory.allocUtf8String(Res.str).C_Object, Res.count);
        }

        local Result = Memory.alloc(16);
        MD5.MD5_Final(Result.C_Object, Ctx.C_Object);
        Io.Close();
        return base64_encode(Result.readUtf8String(16));
    }
}