lugre_md5_L.cpp

Go to the documentation of this file.
00001 #ifdef USE_LUGRE_LIB_MD5
00002 
00003 #include "lugre_prefix.h"
00004 #include "lugre_scripting.h"
00005 #include "lugre_luabind.h"
00006 
00007 #include "md5.h"
00008 #include <stdio.h>
00009 
00010 extern "C" {
00011     #include "lua.h"
00012     #include "lauxlib.h"
00013     #include "lualib.h"
00014 }
00015 
00016 namespace Lugre {
00017   
00018     // return hex md5 sum from file
00019     // lua : string MD5FromFile(filepath)
00020     static int l_MD5FromFile    (lua_State *L) { PROFILE
00021         std::string sFile = luaL_checkstring(L,1);
00022         
00023         md5_state_t state;
00024         md5_byte_t digest[16];
00025         char hex_output[16*2 + 1];
00026         int di;
00027 
00028         md5_init(&state);
00029         
00030         FILE *f = fopen(sFile.c_str(),"r");
00031         if(f){
00032             char buffer[10 * 1024];
00033             int r = 0;
00034             
00035             while(r = fread(buffer,1,10 * 1024,f)){
00036                 md5_append(&state, (const md5_byte_t *)buffer, r);
00037             }
00038             
00039             fclose(f);
00040             
00041             md5_finish(&state, digest);
00042             
00043             for (di = 0; di < 16; ++di)sprintf(hex_output + di * 2, "%02x", digest[di]);
00044             
00045             lua_pushstring( L, hex_output );        
00046 
00047             return 1;
00048         } else {
00049             // error -> return nil
00050             return 0;
00051         }
00052     }
00053     
00054     // return hex md5 sum from string
00055     // lua : string MD5FromString(string)
00056     static int l_MD5FromString  (lua_State *L) { PROFILE
00057         std::string sString = luaL_checkstring(L,1);
00058         
00059         md5_state_t state;
00060         md5_byte_t digest[16];
00061         char hex_output[16*2 + 1];
00062         int di;
00063 
00064         md5_init(&state);
00065         md5_append(&state, (const md5_byte_t *)sString.c_str(), sString.length());
00066         md5_finish(&state, digest);
00067         for (di = 0; di < 16; ++di)sprintf(hex_output + di * 2, "%02x", digest[di]);
00068         
00069         lua_pushstring( L, hex_output );
00070         return 1;
00071     }   
00072     
00074     void    LuaRegisterMD5  (lua_State *L) { PROFILE
00075         lua_register(L,"MD5FromFile",    &l_MD5FromFile);
00076         lua_register(L,"MD5FromString",    &l_MD5FromString);
00077     }
00078 }
00079 
00080 
00081 #endif

Generated on Wed May 23 06:00:14 2012 for cpp by  doxygen 1.5.6