From 024c7fb409dc9b0c921a41a89a411496a17b0f70 Mon Sep 17 00:00:00 2001 From: George Hazan Date: Tue, 1 Apr 2014 14:58:49 +0000 Subject: CryptoPP: code cleaning git-svn-id: http://svn.miranda-ng.org/main/trunk@8813 1316c22d-e87f-b044-9b9b-93d7a3e3ba9c --- plugins/CryptoPP/cryptopp_10.vcxproj | 2 - plugins/CryptoPP/cryptopp_10.vcxproj.filters | 6 - plugins/CryptoPP/cryptopp_12.vcxproj | 1 - plugins/CryptoPP/cryptopp_12.vcxproj.filters | 3 - plugins/CryptoPP/src/base16.cpp | 34 +- plugins/CryptoPP/src/base64.cpp | 4 +- plugins/CryptoPP/src/commonheaders.h | 126 ++-- plugins/CryptoPP/src/cpp_cntx.cpp | 63 +- plugins/CryptoPP/src/cpp_gpgw.cpp | 80 +-- plugins/CryptoPP/src/cpp_gzip.cpp | 40 +- plugins/CryptoPP/src/cpp_keys.cpp | 109 ++- plugins/CryptoPP/src/cpp_misc.cpp | 132 ++-- plugins/CryptoPP/src/cpp_pgpw.cpp | 92 +-- plugins/CryptoPP/src/cpp_rsam.cpp | 982 +++++++++++++-------------- plugins/CryptoPP/src/cpp_rsam.h | 2 +- plugins/CryptoPP/src/cpp_rsau.cpp | 160 ++--- plugins/CryptoPP/src/cpp_svcs.cpp | 114 ++-- plugins/CryptoPP/src/dllloader.cpp | 280 -------- plugins/CryptoPP/src/dllloader.h | 8 - plugins/CryptoPP/src/gettime.cpp | 23 +- plugins/CryptoPP/src/main.cpp | 62 +- plugins/CryptoPP/src/mmi.cpp | 19 +- plugins/CryptoPP/src/utf8.cpp | 126 ++-- 23 files changed, 1033 insertions(+), 1435 deletions(-) delete mode 100644 plugins/CryptoPP/src/dllloader.cpp delete mode 100644 plugins/CryptoPP/src/dllloader.h diff --git a/plugins/CryptoPP/cryptopp_10.vcxproj b/plugins/CryptoPP/cryptopp_10.vcxproj index 3371e31d62..ad3b93eaef 100644 --- a/plugins/CryptoPP/cryptopp_10.vcxproj +++ b/plugins/CryptoPP/cryptopp_10.vcxproj @@ -227,7 +227,6 @@ - @@ -239,7 +238,6 @@ - diff --git a/plugins/CryptoPP/cryptopp_10.vcxproj.filters b/plugins/CryptoPP/cryptopp_10.vcxproj.filters index e0aa4f9a0c..4ff895140c 100644 --- a/plugins/CryptoPP/cryptopp_10.vcxproj.filters +++ b/plugins/CryptoPP/cryptopp_10.vcxproj.filters @@ -48,9 +48,6 @@ Source Files - - Source Files - Source Files @@ -119,9 +116,6 @@ Header Files - - Header Files - Header Files diff --git a/plugins/CryptoPP/cryptopp_12.vcxproj b/plugins/CryptoPP/cryptopp_12.vcxproj index c040bd0c50..2cdc1c19a1 100644 --- a/plugins/CryptoPP/cryptopp_12.vcxproj +++ b/plugins/CryptoPP/cryptopp_12.vcxproj @@ -229,7 +229,6 @@ - diff --git a/plugins/CryptoPP/cryptopp_12.vcxproj.filters b/plugins/CryptoPP/cryptopp_12.vcxproj.filters index e0aa4f9a0c..e0caad8707 100644 --- a/plugins/CryptoPP/cryptopp_12.vcxproj.filters +++ b/plugins/CryptoPP/cryptopp_12.vcxproj.filters @@ -48,9 +48,6 @@ Source Files - - Source Files - Source Files diff --git a/plugins/CryptoPP/src/base16.cpp b/plugins/CryptoPP/src/base16.cpp index d28daf99a3..689d54c88a 100644 --- a/plugins/CryptoPP/src/base16.cpp +++ b/plugins/CryptoPP/src/base16.cpp @@ -1,15 +1,14 @@ #include "commonheaders.h" - -char *base16encode(const char *inBuffer, int count) { - - char *outBuffer = (char *) malloc(count*2+1); +char *base16encode(const char *inBuffer, int count) +{ + char *outBuffer = (char *)malloc(count * 2 + 1); char *outBufferPtr = outBuffer; - BYTE *inBufferPtr = (BYTE *) inBuffer; + BYTE *inBufferPtr = (BYTE *)inBuffer; - while(count){ - *outBufferPtr++ = encode16(((*inBufferPtr)>>4)&0x0F); - *outBufferPtr++ = encode16((*inBufferPtr++)&0x0F); + while (count) { + *outBufferPtr++ = encode16(((*inBufferPtr) >> 4) & 0x0F); + *outBufferPtr++ = encode16((*inBufferPtr++) & 0x0F); count--; } *outBufferPtr = '\0'; @@ -17,20 +16,19 @@ char *base16encode(const char *inBuffer, int count) { return outBuffer; } - -char *base16decode(const char *inBuffer, unsigned int *count) { - +char *base16decode(const char *inBuffer, unsigned int *count) +{ char *outBuffer = (char *)mir_alloc(*count); BYTE *outBufferPtr = (BYTE *)outBuffer; bool big_endian = false; - if (*inBuffer == '0' && *(inBuffer+1) == 'x') { + if (*inBuffer == '0' && *(inBuffer + 1) == 'x') { inBuffer += *count; big_endian = true; *count -= 2; } - while(*count>1){ - BYTE c0,c1; + while (*count > 1) { + BYTE c0, c1; if (big_endian) { c1 = decode16(*--inBuffer); c0 = decode16(*--inBuffer); @@ -44,21 +42,17 @@ char *base16decode(const char *inBuffer, unsigned int *count) { *count = 0; return(NULL); } - *outBufferPtr++ = (c0<<4) | c1; + *outBufferPtr++ = (c0 << 4) | c1; *count -= 2; } *outBufferPtr = '\0'; - *count = (int)(outBufferPtr-(BYTE *)outBuffer); + *count = (int)(outBufferPtr - (BYTE *)outBuffer); return outBuffer; } - char *base16decode(const char *inBuffer) { unsigned count = (unsigned)strlen(inBuffer); return base16decode(inBuffer, &count); } - - -// EOF diff --git a/plugins/CryptoPP/src/base64.cpp b/plugins/CryptoPP/src/base64.cpp index 8daa2bd598..24ead6eed2 100644 --- a/plugins/CryptoPP/src/base64.cpp +++ b/plugins/CryptoPP/src/base64.cpp @@ -2,7 +2,7 @@ string base64encode(const string& buf) { - return (char*)ptrA( mir_base64_encode((PBYTE)buf.data(), (unsigned)buf.length())); + return (char*)ptrA(mir_base64_encode((PBYTE)buf.data(), (unsigned)buf.length())); } string base64decode(const string& buf) @@ -18,5 +18,3 @@ string base64decode(const char *buf) char *plain = (char*)mir_base64_decode(buf, &len); return (plain == NULL) ? string() : string(plain, len); } - -// EOF diff --git a/plugins/CryptoPP/src/commonheaders.h b/plugins/CryptoPP/src/commonheaders.h index 9b4fce001a..c1dfa05234 100644 --- a/plugins/CryptoPP/src/commonheaders.h +++ b/plugins/CryptoPP/src/commonheaders.h @@ -54,7 +54,6 @@ #include "cryptopp.h" #include "version.h" #include "resource.h" -#include "dllloader.h" #include "mmi.h" #include "utf8.h" #include "base16.h" @@ -94,67 +93,66 @@ int Sent_NetLog(const char *,...); PBYTE cpp_alloc_pdata(pCNTX); -extern "C" { - DLLEXPORT HANDLE __cdecl cpp_create_context(int); // create crypt-context - DLLEXPORT void __cdecl cpp_delete_context(HANDLE); // delete crypt-context - DLLEXPORT void __cdecl cpp_reset_context(HANDLE); // reset crypt-context (free all data) - DLLEXPORT LPSTR __cdecl cpp_init_keya(HANDLE,int); // make KeyA - DLLEXPORT int __cdecl cpp_init_keyb(HANDLE,LPCSTR); // load KeyB - DLLEXPORT int __cdecl cpp_calc_keyx(HANDLE); // calculate KeyX - DLLEXPORT int __cdecl cpp_init_keyp(HANDLE,LPCSTR); // make KeyP from password - DLLEXPORT LPSTR __cdecl cpp_encodeA(HANDLE,LPCSTR); // encode ANSIz string - DLLEXPORT LPSTR __cdecl cpp_encodeW(HANDLE,LPWSTR); // encode USC2z string - DLLEXPORT LPSTR __cdecl cpp_encodeU(HANDLE,LPCSTR); // encode UTF8z string - DLLEXPORT LPSTR __cdecl cpp_decode(HANDLE,LPCSTR); // decode as ANSIzUCS2z - DLLEXPORT LPSTR __cdecl cpp_decodeU(HANDLE,LPCSTR); // decode as UTF8z - DLLEXPORT int __cdecl cpp_encrypt_file(HANDLE,LPCSTR,LPCSTR); // encrypt file - DLLEXPORT int __cdecl cpp_decrypt_file(HANDLE,LPCSTR,LPCSTR); // decrypt file - DLLEXPORT int __cdecl cpp_get_features(HANDLE); // get features field from client - DLLEXPORT int __cdecl cpp_get_error(HANDLE); // get last error code - DLLEXPORT int __cdecl cpp_get_version(void); // get dll version - DLLEXPORT int __cdecl cpp_size_keyx(void); - DLLEXPORT void __cdecl cpp_get_keyx(HANDLE,byte*); // get crypto key - DLLEXPORT void __cdecl cpp_set_keyx(HANDLE,byte*); // set crypto key - DLLEXPORT int __cdecl cpp_size_keyp(void); - DLLEXPORT void __cdecl cpp_get_keyp(HANDLE,byte*); // get pre-shared key - DLLEXPORT void __cdecl cpp_set_keyp(HANDLE,byte*); // set pre-shared key - DLLEXPORT int __cdecl cpp_keya(HANDLE); // KeyA exist ? - DLLEXPORT int __cdecl cpp_keyb(HANDLE); // KeyB exist ? - DLLEXPORT int __cdecl cpp_keyx(HANDLE); // KeyX exist ? - DLLEXPORT int __cdecl cpp_keyp(HANDLE); // KeyP exist ? - - DLLEXPORT int __cdecl pgp_init(void); - DLLEXPORT int __cdecl pgp_done(void); - DLLEXPORT int __cdecl pgp_open_keyrings(LPSTR,LPSTR); - DLLEXPORT int __cdecl pgp_close_keyrings(void); - DLLEXPORT int __cdecl pgp_get_version(void); - DLLEXPORT LPSTR __cdecl pgp_get_error(void); - DLLEXPORT int __cdecl pgp_set_priv_key(LPCSTR); - DLLEXPORT int __cdecl pgp_set_key(HANDLE,LPCSTR); - DLLEXPORT int __cdecl pgp_set_keyid(HANDLE,PVOID); - DLLEXPORT int __cdecl pgp_size_keyid(void); - DLLEXPORT PVOID __cdecl pgp_select_keyid(HWND,LPSTR); - DLLEXPORT LPSTR __cdecl pgp_encode(HANDLE,LPCSTR); - DLLEXPORT LPSTR __cdecl pgp_decode(HANDLE,LPCSTR); - - DLLEXPORT int __cdecl gpg_init(void); - DLLEXPORT int __cdecl gpg_done(void); - DLLEXPORT int __cdecl gpg_open_keyrings(LPSTR,LPSTR); - DLLEXPORT int __cdecl gpg_close_keyrings(void); - DLLEXPORT void __cdecl gpg_set_log(LPCSTR); - DLLEXPORT void __cdecl gpg_set_tmp(LPCSTR); - DLLEXPORT LPSTR __cdecl gpg_get_error(void); - DLLEXPORT int __cdecl gpg_set_key(HANDLE,LPCSTR); - DLLEXPORT int __cdecl gpg_set_keyid(HANDLE,LPCSTR); - DLLEXPORT int __cdecl gpg_size_keyid(void); - DLLEXPORT int __cdecl gpg_select_keyid(HWND,LPSTR); - DLLEXPORT LPSTR __cdecl gpg_encode(HANDLE,LPCSTR); - DLLEXPORT LPSTR __cdecl gpg_decode(HANDLE,LPCSTR); - DLLEXPORT LPSTR __cdecl gpg_get_passphrases(); - DLLEXPORT void __cdecl gpg_set_passphrases(LPCSTR); - - DLLEXPORT int __cdecl rsa_init(pRSA_EXPORT*,pRSA_IMPORT); - DLLEXPORT int __cdecl rsa_done(void); +extern "C" +{ + DLLEXPORT HANDLE __cdecl cpp_create_context(int); // create crypt-context + DLLEXPORT void __cdecl cpp_delete_context(HANDLE); // delete crypt-context + DLLEXPORT void __cdecl cpp_reset_context(HANDLE); // reset crypt-context (free all data) + DLLEXPORT LPSTR __cdecl cpp_init_keya(HANDLE, int); // make KeyA + DLLEXPORT int __cdecl cpp_init_keyb(HANDLE, LPCSTR); // load KeyB + DLLEXPORT int __cdecl cpp_calc_keyx(HANDLE); // calculate KeyX + DLLEXPORT int __cdecl cpp_init_keyp(HANDLE, LPCSTR); // make KeyP from password + DLLEXPORT LPSTR __cdecl cpp_encodeA(HANDLE, LPCSTR); // encode ANSIz string + DLLEXPORT LPSTR __cdecl cpp_encodeW(HANDLE, LPWSTR); // encode USC2z string + DLLEXPORT LPSTR __cdecl cpp_encodeU(HANDLE, LPCSTR); // encode UTF8z string + DLLEXPORT LPSTR __cdecl cpp_decode(HANDLE, LPCSTR); // decode as ANSIzUCS2z + DLLEXPORT LPSTR __cdecl cpp_decodeU(HANDLE, LPCSTR); // decode as UTF8z + DLLEXPORT int __cdecl cpp_encrypt_file(HANDLE, LPCSTR, LPCSTR); // encrypt file + DLLEXPORT int __cdecl cpp_decrypt_file(HANDLE, LPCSTR, LPCSTR); // decrypt file + DLLEXPORT int __cdecl cpp_get_features(HANDLE); // get features field from client + DLLEXPORT int __cdecl cpp_get_error(HANDLE); // get last error code + DLLEXPORT int __cdecl cpp_get_version(void); // get dll version + DLLEXPORT int __cdecl cpp_size_keyx(void); + DLLEXPORT void __cdecl cpp_get_keyx(HANDLE, byte*); // get crypto key + DLLEXPORT void __cdecl cpp_set_keyx(HANDLE, byte*); // set crypto key + DLLEXPORT int __cdecl cpp_size_keyp(void); + DLLEXPORT void __cdecl cpp_get_keyp(HANDLE, byte*); // get pre-shared key + DLLEXPORT void __cdecl cpp_set_keyp(HANDLE, byte*); // set pre-shared key + DLLEXPORT int __cdecl cpp_keya(HANDLE); // KeyA exist ? + DLLEXPORT int __cdecl cpp_keyb(HANDLE); // KeyB exist ? + DLLEXPORT int __cdecl cpp_keyx(HANDLE); // KeyX exist ? + DLLEXPORT int __cdecl cpp_keyp(HANDLE); // KeyP exist ? + + DLLEXPORT int __cdecl pgp_init(void); + DLLEXPORT int __cdecl pgp_done(void); + DLLEXPORT int __cdecl pgp_open_keyrings(LPSTR, LPSTR); + DLLEXPORT int __cdecl pgp_close_keyrings(void); + DLLEXPORT int __cdecl pgp_get_version(void); + DLLEXPORT LPSTR __cdecl pgp_get_error(void); + DLLEXPORT int __cdecl pgp_set_priv_key(LPCSTR); + DLLEXPORT int __cdecl pgp_set_key(HANDLE, LPCSTR); + DLLEXPORT int __cdecl pgp_set_keyid(HANDLE, PVOID); + DLLEXPORT int __cdecl pgp_size_keyid(void); + DLLEXPORT PVOID __cdecl pgp_select_keyid(HWND, LPSTR); + DLLEXPORT LPSTR __cdecl pgp_encode(HANDLE, LPCSTR); + DLLEXPORT LPSTR __cdecl pgp_decode(HANDLE, LPCSTR); + + DLLEXPORT int __cdecl gpg_init(void); + DLLEXPORT int __cdecl gpg_done(void); + DLLEXPORT int __cdecl gpg_open_keyrings(LPSTR, LPSTR); + DLLEXPORT int __cdecl gpg_close_keyrings(void); + DLLEXPORT void __cdecl gpg_set_log(LPCSTR); + DLLEXPORT void __cdecl gpg_set_tmp(LPCSTR); + DLLEXPORT LPSTR __cdecl gpg_get_error(void); + DLLEXPORT int __cdecl gpg_set_key(HANDLE, LPCSTR); + DLLEXPORT int __cdecl gpg_set_keyid(HANDLE, LPCSTR); + DLLEXPORT int __cdecl gpg_size_keyid(void); + DLLEXPORT int __cdecl gpg_select_keyid(HWND, LPSTR); + DLLEXPORT LPSTR __cdecl gpg_encode(HANDLE, LPCSTR); + DLLEXPORT LPSTR __cdecl gpg_decode(HANDLE, LPCSTR); + DLLEXPORT LPSTR __cdecl gpg_get_passphrases(); + DLLEXPORT void __cdecl gpg_set_passphrases(LPCSTR); + + DLLEXPORT int __cdecl rsa_init(pRSA_EXPORT*, pRSA_IMPORT); + DLLEXPORT int __cdecl rsa_done(void); } - -// EOF diff --git a/plugins/CryptoPP/src/cpp_cntx.cpp b/plugins/CryptoPP/src/cpp_cntx.cpp index 62ee204079..867060daba 100644 --- a/plugins/CryptoPP/src/cpp_cntx.cpp +++ b/plugins/CryptoPP/src/cpp_cntx.cpp @@ -3,14 +3,14 @@ // get context data on context id pCNTX get_context_on_id(HANDLE context) { - if ( context ) { - pCNTX cntx = (pCNTX) context; - if ( cntx->header == HEADER && cntx->footer == FOOTER ) + if (context) { + pCNTX cntx = (pCNTX)context; + if (cntx->header == HEADER && cntx->footer == FOOTER) return cntx; - #if defined(_DEBUG) || defined(NETLIB_LOG) - Sent_NetLog("get_context_on_id: corrupted context %08X", cntx); - #endif +#if defined(_DEBUG) || defined(NETLIB_LOG) + Sent_NetLog("get_context_on_id: corrupted context %08X", cntx); +#endif } return NULL; } @@ -18,15 +18,14 @@ pCNTX get_context_on_id(HANDLE context) // create context, return context id HANDLE __cdecl cpp_create_context(int mode) { - pCNTX cntx = (pCNTX) malloc(sizeof(CNTX)); - memset(cntx,0,sizeof(CNTX)); // очищаем выделенный блок + pCNTX cntx = (pCNTX)malloc(sizeof(CNTX)); + memset(cntx, 0, sizeof(CNTX)); // очищаем выделенный блок cntx->header = HEADER; cntx->footer = FOOTER; cntx->mode = mode; return (HANDLE)cntx; } - // delete context void __cdecl cpp_delete_context(HANDLE context) { @@ -37,63 +36,59 @@ void __cdecl cpp_delete_context(HANDLE context) } } - // reset context void __cdecl cpp_reset_context(HANDLE context) { pCNTX tmp = get_context_on_id(context); - if (tmp) cpp_free_keys(tmp); + if (tmp) + cpp_free_keys(tmp); } - // allocate pdata PBYTE cpp_alloc_pdata(pCNTX ptr) { - if ( !ptr->pdata ) { - if ( ptr->mode & MODE_PGP ) { - ptr->pdata = (PBYTE) malloc(sizeof(PGPDATA)); - memset(ptr->pdata,0,sizeof(PGPDATA)); + if (!ptr->pdata) { + if (ptr->mode & MODE_PGP) { + ptr->pdata = (PBYTE)malloc(sizeof(PGPDATA)); + memset(ptr->pdata, 0, sizeof(PGPDATA)); } - else if ( ptr->mode & MODE_GPG ) { - ptr->pdata = (PBYTE) malloc(sizeof(GPGDATA)); - memset(ptr->pdata,0,sizeof(GPGDATA)); + else if (ptr->mode & MODE_GPG) { + ptr->pdata = (PBYTE)malloc(sizeof(GPGDATA)); + memset(ptr->pdata, 0, sizeof(GPGDATA)); } - else if ( ptr->mode & MODE_RSA ) { + else if (ptr->mode & MODE_RSA) { rsa_alloc(ptr); } else { - ptr->pdata = (PBYTE) malloc(sizeof(SIMDATA)); - memset(ptr->pdata,0,sizeof(SIMDATA)); + ptr->pdata = (PBYTE)malloc(sizeof(SIMDATA)); + memset(ptr->pdata, 0, sizeof(SIMDATA)); } } return ptr->pdata; } - // free memory from keys void cpp_free_keys(pCNTX ptr) { replaceStr(ptr->tmp, 0); cpp_alloc_pdata(ptr); - if ( ptr->mode & MODE_PGP ) { - pPGPDATA p = (pPGPDATA) ptr->pdata; + if (ptr->mode & MODE_PGP) { + pPGPDATA p = (pPGPDATA)ptr->pdata; SAFE_FREE(p->pgpKeyID); SAFE_FREE(p->pgpKey); SAFE_FREE(ptr->pdata); } - else - if ( ptr->mode & MODE_GPG ) { - pGPGDATA p = (pGPGDATA) ptr->pdata; + else if (ptr->mode & MODE_GPG) { + pGPGDATA p = (pGPGDATA)ptr->pdata; SAFE_FREE(p->gpgKeyID); SAFE_FREE(ptr->pdata); } - else - if ( ptr->mode & MODE_RSA ) { - rsa_free(ptr); - SAFE_DELETE(ptr->pdata); + else if (ptr->mode & MODE_RSA) { + if (rsa_free(ptr)) + SAFE_DELETE(ptr->pdata); } else { - pSIMDATA p = (pSIMDATA) ptr->pdata; + pSIMDATA p = (pSIMDATA)ptr->pdata; SAFE_FREE(p->PubA); SAFE_FREE(p->KeyA); mir_free(p->KeyB); @@ -103,5 +98,3 @@ void cpp_free_keys(pCNTX ptr) SAFE_FREE(ptr->pdata); } } - -// EOF diff --git a/plugins/CryptoPP/src/cpp_gpgw.cpp b/plugins/CryptoPP/src/cpp_gpgw.cpp index 3336b825df..2e62b77deb 100644 --- a/plugins/CryptoPP/src/cpp_gpgw.cpp +++ b/plugins/CryptoPP/src/cpp_gpgw.cpp @@ -27,52 +27,46 @@ int __cdecl gpg_init() int __cdecl gpg_done() { - int r = 0; - if (hgpg) { - r = _gpg_done(); + int r = 0; + if (hgpg) { + r = _gpg_done(); hgpg = 0; - } + } return r; } - int __cdecl gpg_open_keyrings(LPSTR ExecPath, LPSTR HomePath) { return _gpg_open_keyrings(ExecPath, HomePath); } - int __cdecl gpg_close_keyrings() { return _gpg_close_keyrings(); } - void __cdecl gpg_set_log(LPCSTR LogPath) { _gpg_set_log(LogPath); } - void __cdecl gpg_set_tmp(LPCSTR TmpPath) { _gpg_set_tmp(TmpPath); } - LPSTR __cdecl gpg_get_error() { return _gpg_get_error(); } - LPSTR __cdecl gpg_encrypt(pCNTX ptr, LPCSTR szPlainMsg) { ptr->error = ERROR_NONE; - pGPGDATA p = (pGPGDATA) ptr->pdata; + pGPGDATA p = (pGPGDATA)ptr->pdata; LPSTR szEncMsg; - szEncMsg = _gpg_encrypt(szPlainMsg,(LPCSTR)p->gpgKeyID); + szEncMsg = _gpg_encrypt(szPlainMsg, (LPCSTR)p->gpgKeyID); if (!szEncMsg) { replaceStr(ptr->tmp, 0); return 0; @@ -83,31 +77,29 @@ LPSTR __cdecl gpg_encrypt(pCNTX ptr, LPCSTR szPlainMsg) return ptr->tmp; } - LPSTR __cdecl gpg_decrypt(pCNTX ptr, LPCSTR szEncMsg) { - ptr->error = ERROR_NONE; + ptr->error = ERROR_NONE; - LPSTR szPlainMsg = _gpg_decrypt(szEncMsg); - replaceStr(ptr->tmp, mir_strdup(szPlainMsg)); - LocalFree((LPVOID)szPlainMsg); + LPSTR szPlainMsg = _gpg_decrypt(szEncMsg); + replaceStr(ptr->tmp, mir_strdup(szPlainMsg)); + LocalFree((LPVOID)szPlainMsg); - return ptr->tmp; + return ptr->tmp; } - LPSTR __cdecl gpg_encode(HANDLE context, LPCSTR szPlainMsg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - pGPGDATA p = (pGPGDATA) cpp_alloc_pdata(ptr); + pGPGDATA p = (pGPGDATA)cpp_alloc_pdata(ptr); if (!p->gpgKeyID) { ptr->error = ERROR_NO_GPG_KEY; return NULL; } // utf8 message: encrypt. LPSTR szUtfMsg; - if ( ptr->mode & MODE_GPG_ANSI ) { + if (ptr->mode & MODE_GPG_ANSI) { LPWSTR wszMsg = utf8decode(szPlainMsg); - int wlen = (int)wcslen(wszMsg)+1; - szUtfMsg = (LPSTR) alloca(wlen); + int wlen = (int)wcslen(wszMsg) + 1; + szUtfMsg = (LPSTR)alloca(wlen); WideCharToMultiByte(CP_ACP, 0, wszMsg, -1, szUtfMsg, wlen, 0, 0); } else { @@ -126,9 +118,9 @@ LPSTR __cdecl gpg_decode(HANDLE context, LPCSTR szEncMsg) LPSTR szOldMsg = gpg_decrypt(ptr, szEncMsg); if (szOldMsg) { - if ( !is_7bit_string(szOldMsg) && !is_utf8_string(szOldMsg) ) { - int slen = (int)strlen(szOldMsg)+1; - LPWSTR wszMsg = (LPWSTR) alloca(slen*sizeof(WCHAR)); + if (!is_7bit_string(szOldMsg) && !is_utf8_string(szOldMsg)) { + int slen = (int)strlen(szOldMsg) + 1; + LPWSTR wszMsg = (LPWSTR)alloca(slen*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, szOldMsg, -1, wszMsg, slen*sizeof(WCHAR)); szNewMsg = _strdup(utf8encode(wszMsg)); } @@ -140,60 +132,52 @@ LPSTR __cdecl gpg_decode(HANDLE context, LPCSTR szEncMsg) return szNewMsg; } - int __cdecl gpg_set_key(HANDLE context, LPCSTR RemoteKey) { -/* pCNTX ptr = get_context_on_id(context); - if (!ptr) return 0; - ptr->error = ERROR_NONE; + /* + pCNTX ptr = get_context_on_id(context); + if (!ptr) return 0; + ptr->error = ERROR_NONE; -// if (!_gpg_check_key(RemoteKey)) return 0; + if (!_gpg_check_key(RemoteKey)) return 0; - SAFE_FREE(ptr->pgpKey); + SAFE_FREE(ptr->pgpKey); ptr->pgpKey = (BYTE *) malloc(strlen(RemoteKey)+1); strcpy((LPSTR)ptr->pgpKey,RemoteKey); - return 1; -*/ + return 1; + */ return 0; } - int __cdecl gpg_set_keyid(HANDLE context, LPCSTR RemoteKeyID) { pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pGPGDATA p = (pGPGDATA) cpp_alloc_pdata(ptr); - ptr->error = ERROR_NONE; + pGPGDATA p = (pGPGDATA)cpp_alloc_pdata(ptr); + ptr->error = ERROR_NONE; - SAFE_FREE(p->gpgKeyID); + SAFE_FREE(p->gpgKeyID); p->gpgKeyID = (PBYTE)_strdup(RemoteKeyID); - return 1; + return 1; } - int __cdecl gpg_size_keyid() { return _gpg_size_keyid(); } - -int __cdecl gpg_select_keyid(HWND hDlg,LPSTR szKeyID) +int __cdecl gpg_select_keyid(HWND hDlg, LPSTR szKeyID) { - return _gpg_select_keyid(hDlg,szKeyID); + return _gpg_select_keyid(hDlg, szKeyID); } - LPSTR __cdecl gpg_get_passphrases() { return _gpg_get_passphrases(); } - void __cdecl gpg_set_passphrases(LPCSTR buffer) { _gpg_set_passphrases(buffer); } - - -// EOF \ No newline at end of file diff --git a/plugins/CryptoPP/src/cpp_gzip.cpp b/plugins/CryptoPP/src/cpp_gzip.cpp index 36a4ae7e20..41183d3eb5 100644 --- a/plugins/CryptoPP/src/cpp_gzip.cpp +++ b/plugins/CryptoPP/src/cpp_gzip.cpp @@ -1,41 +1,40 @@ #include "commonheaders.h" // gzip data -BYTE *cpp_gzip(BYTE *pData, size_t nLen, size_t& nCompressedLen) { - +BYTE *cpp_gzip(BYTE *pData, size_t nLen, size_t& nCompressedLen) +{ string zipped; - Gzip gzip(new StringSink(zipped),5); // 1 is fast, 9 is slow + Gzip gzip(new StringSink(zipped), 5); // 1 is fast, 9 is slow gzip.Put(pData, nLen); gzip.MessageEnd(); - nCompressedLen = (int) zipped.length(); - PBYTE pCompressed = (PBYTE) malloc(nCompressedLen+1); - memcpy(pCompressed,zipped.data(),nCompressedLen); + nCompressedLen = (int)zipped.length(); + PBYTE pCompressed = (PBYTE)malloc(nCompressedLen + 1); + memcpy(pCompressed, zipped.data(), nCompressedLen); return pCompressed; } // gunzip data -BYTE *cpp_gunzip(BYTE *pCompressedData, size_t nCompressedLen, size_t& nLen) { - +BYTE *cpp_gunzip(BYTE *pCompressedData, size_t nCompressedLen, size_t& nLen) +{ string unzipped; Gunzip gunzip(new StringSink(unzipped)); - gunzip.Put((PBYTE)pCompressedData,nCompressedLen); + gunzip.Put((PBYTE)pCompressedData, nCompressedLen); gunzip.MessageEnd(); - nLen = (int) unzipped.length(); - PBYTE pData = (PBYTE) malloc(nLen+1); - memcpy(pData,unzipped.data(),nLen); + nLen = (int)unzipped.length(); + PBYTE pData = (PBYTE)malloc(nLen + 1); + memcpy(pData, unzipped.data(), nLen); return pData; } // zlibc data -string cpp_zlibc(string& pData) { - +string cpp_zlibc(string& pData) +{ string zipped; - - ZlibCompressor zlib(new StringSink(zipped),5); // 1 is fast, 9 is slow + ZlibCompressor zlib(new StringSink(zipped), 5); // 1 is fast, 9 is slow zlib.Put((PBYTE)pData.data(), pData.length()); zlib.MessageEnd(); @@ -43,15 +42,12 @@ string cpp_zlibc(string& pData) { } // zlibd data -string cpp_zlibd(string& pData) { - +string cpp_zlibd(string& pData) +{ string unzipped; - ZlibDecompressor zlib(new StringSink(unzipped)); - zlib.Put((PBYTE)pData.data(),pData.length()); + zlib.Put((PBYTE)pData.data(), pData.length()); zlib.MessageEnd(); return unzipped; } - -// EOF diff --git a/plugins/CryptoPP/src/cpp_keys.cpp b/plugins/CryptoPP/src/cpp_keys.cpp index 990ead35ec..ec1659f179 100644 --- a/plugins/CryptoPP/src/cpp_keys.cpp +++ b/plugins/CryptoPP/src/cpp_keys.cpp @@ -2,12 +2,11 @@ const unsigned char IV[] = "PSKhell@MIRANDA!"; - // generate KeyA pair, return public key as ASCII -LPSTR __cdecl cpp_init_keya(HANDLE context, int features) { - +LPSTR __cdecl cpp_init_keya(HANDLE context, int features) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - pSIMDATA p = (pSIMDATA) cpp_alloc_pdata(ptr); + pSIMDATA p = (pSIMDATA)cpp_alloc_pdata(ptr); int send_features = FEATURES; if (p->KeyP) send_features |= FEATURES_PSK; @@ -17,71 +16,70 @@ LPSTR __cdecl cpp_init_keya(HANDLE context, int features) { Integer p0("0x865734026113B4DF0082CED84C197718516088FBDA406CFDFD7F033694E11E46F01C8F01E0E5AE6B09F6284691C7DD30A5BA8A74BA4B780198624B84BC8DAF6E0DFF874C0440ABB5C043C82E9E9C9E6F1A470B6A2A6BCEAC9460C43B1BB1331DF0FFD898DB74D22E8A71DB2659F1B0F52F337718D233DED611DA25AEAA90F3BE0C42FA9E541D0487DF58A77E2F44D295AD0C54C369CE260C969CA12F690EAAFAEEF8676C631AF29A3DE3389D3000B94EFA775E31FCA879AEB00A4D05EEF50D4C084A049EB12EF4CDFBD48E36B29CEAF8978D535D6C70BB274D1FEA02ABD521D2EF482A76326C17AF597FCB9B8BF37D9110E22AB0746D6A9779DF5133822E3F15"); Integer q0("0xF1515160E1BFC7636338C13AD5BA775318E287147A1F96B73CF0FB4D97EFFB9D1FCDCF31AB9D92C4F49C9F8D50F06E697D2313E2EBAC7781312A51F458D66FFC687960CAA86BDF150A36ED53D79FBDB4F501FD25E37C181B45F9555D7F1C6124CAB29A822AD1E7BF5DA93C2FDB12A61919B5E5359793CBB16E71516919040A7F"); Integer g0("0x434158F2FF2CF667E3CC1A707770DDE7B56048F6C5005473C6DC4A5E3FC490667F2908C44F9ADC2071EB8A8A1EC6AD6901CDAAAFE806626E3F4C5E69D4FCBF9DF1B67D574DC61C687C4BEF3ACF77A7256752F4D3A7EAEEE5874ED4912AB10C5B122A24E698B14CAC3E0FD006E0DB02714E028AECCA25BAB9DDCA2CF6405E862B403C61BC381D64B46BD96D3FEFBE22B7497FCBDA2B49C840C1B2853502A5216B036F83D2EAD8F835B603FC5BA1EFB816C7634915B1D43963FDD1B1ED626F48CCF8F152392E4693D38C566016708FA9E9598AECF95A8B067212669247552418E538A706564F855D3D5D50717D356259A20D8FD0C6B2A9FCC045D3F7AED1E857C5"); - p->dh = new DH(p0,q0,g0); + p->dh = new DH(p0, q0, g0); } else { Integer p0("0xD494AAFBCD2EAC6A36DB8E7DD4A2A64512A5BBB15B9BFB581C7C1CAFB647D4612973C3770C2166D75EEA695F67EA8261557591DB78BCF5A886AA5294F3AEE4D25B57C8EE8C7FE8DBF70C132CD7FFCB6F89426F807F552C5DAE2FB1F329E340094E4B30D8EF6265AB4D350E9837B151C86AC524DE4E1FC04746C668BE318275E420D51AEDDFBDF887D435CDEEF6AC81293DB45287132F8236A43AD8F4D6642D7CA6732DA06A1DE008259008C9D74403B68ADAC788CF8AB5BEFFC310DCCCD32901D1F290E5B7A993D2CF6A652AF81B6DA0FD2E70678D1AE086150E41444522F20621195AD2A1F0975652B4AF7DE5261A9FD46B9EA8B443641F3BBA695B9B020103"); Integer g0("0x12A567BC9ABCDEF1234567823BCDEF1E"); - p->dh = new DH(p0,g0); + p->dh = new DH(p0, g0); } BYTE priv1[KEYSIZE]; // private key of 2048 bit - BYTE publ1[KEYSIZE+2]; // public key of 2048 bit + faetures field + BYTE publ1[KEYSIZE + 2]; // public key of 2048 bit + faetures field - memset(priv1,0,sizeof(priv1)); - memset(publ1,0,sizeof(publ1)); + memset(priv1, 0, sizeof(priv1)); + memset(publ1, 0, sizeof(publ1)); AutoSeededRandomPool autorng; p->dh->GenerateKeyPair(autorng, priv1, publ1); SAFE_FREE(p->PubA); - p->PubA = (PBYTE) malloc(KEYSIZE); - memcpy(p->PubA,publ1,KEYSIZE); + p->PubA = (PBYTE)malloc(KEYSIZE); + memcpy(p->PubA, publ1, KEYSIZE); SAFE_FREE(p->KeyA); - p->KeyA = (PBYTE) malloc(KEYSIZE); - memcpy(p->KeyA,priv1,KEYSIZE); + p->KeyA = (PBYTE)malloc(KEYSIZE); + memcpy(p->KeyA, priv1, KEYSIZE); if (p->KeyP) { // encrypt PUBLIC use PSK string ciphered; - CFB_Mode::Encryption enc(p->KeyP,Tiger::DIGESTSIZE,IV); - StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered)); + CFB_Mode::Encryption enc(p->KeyP, Tiger::DIGESTSIZE, IV); + StreamTransformationFilter cbcEncryptor(enc, new StringSink(ciphered)); - cbcEncryptor.Put(publ1,KEYSIZE); + cbcEncryptor.Put(publ1, KEYSIZE); cbcEncryptor.MessageEnd(); - memcpy(publ1,ciphered.data(),ciphered.length()); + memcpy(publ1, ciphered.data(), ciphered.length()); #if defined(_DEBUG) || defined(NETLIB_LOG) - Sent_NetLog("cpp_init_keya: %d %d",KEYSIZE,ciphered.length()); + Sent_NetLog("cpp_init_keya: %d %d", KEYSIZE, ciphered.length()); #endif } - memcpy((PVOID)&publ1[KEYSIZE],(PVOID)&send_features,2); + memcpy((PVOID)&publ1[KEYSIZE], (PVOID)&send_features, 2); if (ptr->mode & MODE_BASE64 || features & FEATURES_NEWPG) - replaceStr(ptr->tmp, mir_base64_encode(publ1,KEYSIZE+2)); + replaceStr(ptr->tmp, mir_base64_encode(publ1, KEYSIZE + 2)); else - replaceStr(ptr->tmp, base16encode((LPSTR)&publ1,KEYSIZE+2)); + replaceStr(ptr->tmp, base16encode((LPSTR)&publ1, KEYSIZE + 2)); return ptr->tmp; } - // store KeyB -int __cdecl cpp_init_keyb(HANDLE context, LPCSTR key) { - +int __cdecl cpp_init_keyb(HANDLE context, LPCSTR key) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pSIMDATA p = (pSIMDATA) cpp_alloc_pdata(ptr); + pSIMDATA p = (pSIMDATA)cpp_alloc_pdata(ptr); unsigned clen = (unsigned)rtrim(key); ptr->features = 0; LPSTR pub_binary; - if ((clen==KEYSIZE*2) || (clen==(KEYSIZE+2)*2)) - pub_binary = base16decode(key,&clen); + if ((clen == KEYSIZE * 2) || (clen == (KEYSIZE + 2) * 2)) + pub_binary = base16decode(key, &clen); else - pub_binary = (LPSTR)mir_base64_decode(key,&clen); + pub_binary = (LPSTR)mir_base64_decode(key, &clen); - if ( !pub_binary || (clen!=KEYSIZE && clen!=KEYSIZE+2) ) { + if (!pub_binary || (clen != KEYSIZE && clen != KEYSIZE + 2)) { #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("cpp_init_keyb: error bad_keyb"); #endif @@ -90,8 +88,8 @@ int __cdecl cpp_init_keyb(HANDLE context, LPCSTR key) { return 0; } - if (clen==KEYSIZE+2) - memcpy((PVOID)&ptr->features,(PVOID)(pub_binary+KEYSIZE),2); + if (clen == KEYSIZE + 2) + memcpy((PVOID)&ptr->features, (PVOID)(pub_binary + KEYSIZE), 2); if (p->KeyP) { if (!(ptr->features & FEATURES_PSK)) { // if NO PSK on other side @@ -105,14 +103,14 @@ int __cdecl cpp_init_keyb(HANDLE context, LPCSTR key) { try { // decrypt PUBLIC use PSK string unciphered; - CFB_Mode::Decryption dec(p->KeyP,Tiger::DIGESTSIZE,IV); - StreamTransformationFilter cbcDecryptor(dec,new StringSink(unciphered)); + CFB_Mode::Decryption dec(p->KeyP, Tiger::DIGESTSIZE, IV); + StreamTransformationFilter cbcDecryptor(dec, new StringSink(unciphered)); - cbcDecryptor.Put((PBYTE)pub_binary,KEYSIZE); + cbcDecryptor.Put((PBYTE)pub_binary, KEYSIZE); cbcDecryptor.MessageEnd(); - memcpy(pub_binary,unciphered.data(),unciphered.length()); + memcpy(pub_binary, unciphered.data(), unciphered.length()); } - catch (...) { + catch (...) { #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("cpp_init_keyb: error bad_psk"); #endif @@ -121,9 +119,9 @@ int __cdecl cpp_init_keyb(HANDLE context, LPCSTR key) { } mir_free(p->KeyB); - p->KeyB = (PBYTE) pub_binary; + p->KeyB = (PBYTE)pub_binary; - if (p->PubA && memcmp(p->PubA,p->KeyB,KEYSIZE)==0) { + if (p->PubA && memcmp(p->PubA, p->KeyB, KEYSIZE) == 0) { #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("cpp_init_keyb: error bad_keyb keya==keyb"); #endif @@ -136,19 +134,18 @@ int __cdecl cpp_init_keyb(HANDLE context, LPCSTR key) { return 1; } - // calculate secret key, return true or false -int __cdecl cpp_calc_keyx(HANDLE context) { - +int __cdecl cpp_calc_keyx(HANDLE context) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pSIMDATA p = (pSIMDATA) cpp_alloc_pdata(ptr); + pSIMDATA p = (pSIMDATA)cpp_alloc_pdata(ptr); if (!p->KeyA) { ptr->error = ERROR_NO_KEYA; return 0; } if (!p->KeyB) { ptr->error = ERROR_NO_KEYB; return 0; } - ptr->error = ERROR_NONE; + ptr->error = ERROR_NONE; BYTE agreeVal[KEYSIZE]; - memset(agreeVal,0,sizeof(agreeVal)); + memset(agreeVal, 0, sizeof(agreeVal)); BYTE agr = p->dh->Agree(agreeVal, p->KeyA, p->KeyB, true); // calculate key if (agr) { @@ -158,7 +155,7 @@ int __cdecl cpp_calc_keyx(HANDLE context) { mir_free(p->KeyB); p->KeyB = 0; BYTE buffer[Tiger::DIGESTSIZE]; // buffer for hash - memset(buffer,0,sizeof(buffer)); + memset(buffer, 0, sizeof(buffer)); // do this only if key exchanged is ok // we use a 192bit key (24*8) @@ -166,32 +163,28 @@ int __cdecl cpp_calc_keyx(HANDLE context) { // store key SAFE_FREE(p->KeyX); - p->KeyX = (PBYTE) malloc(Tiger::DIGESTSIZE); - memcpy(p->KeyX,buffer,Tiger::DIGESTSIZE); + p->KeyX = (PBYTE)malloc(Tiger::DIGESTSIZE); + memcpy(p->KeyX, buffer, Tiger::DIGESTSIZE); } return (int)agr; } - // create pre-shared key from password -int __cdecl cpp_init_keyp(HANDLE context, LPCSTR password) { - +int __cdecl cpp_init_keyp(HANDLE context, LPCSTR password) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pSIMDATA p = (pSIMDATA) cpp_alloc_pdata(ptr); + pSIMDATA p = (pSIMDATA)cpp_alloc_pdata(ptr); BYTE buffer[Tiger::DIGESTSIZE]; // buffer for hash - memset(buffer,0,sizeof(buffer)); + memset(buffer, 0, sizeof(buffer)); // calculate hash - Tiger().CalculateDigest(buffer,(PBYTE)password,strlen(password)); + Tiger().CalculateDigest(buffer, (PBYTE)password, strlen(password)); // store pre-shared key SAFE_FREE(p->KeyP); - p->KeyP = (PBYTE) malloc(Tiger::DIGESTSIZE); - memcpy(p->KeyP,buffer,Tiger::DIGESTSIZE); + p->KeyP = (PBYTE)malloc(Tiger::DIGESTSIZE); + memcpy(p->KeyP, buffer, Tiger::DIGESTSIZE); return 1; } - - -// EOF diff --git a/plugins/CryptoPP/src/cpp_misc.cpp b/plugins/CryptoPP/src/cpp_misc.cpp index ec7a0ae043..a0721ed5f3 100644 --- a/plugins/CryptoPP/src/cpp_misc.cpp +++ b/plugins/CryptoPP/src/cpp_misc.cpp @@ -1,97 +1,93 @@ #include "commonheaders.h" - -int __cdecl cpp_get_features(HANDLE context) { - pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - return ptr->features; +int __cdecl cpp_get_features(HANDLE context) +{ + pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; + return ptr->features; } - -int __cdecl cpp_get_error(HANDLE context) { - pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - return ptr->error; +int __cdecl cpp_get_error(HANDLE context) +{ + pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; + return ptr->error; } - -int __cdecl cpp_get_version(void) { - return PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM); +int __cdecl cpp_get_version(void) +{ + return PLUGIN_MAKE_VERSION(__MAJOR_VERSION, __MINOR_VERSION, __RELEASE_NUM, __BUILD_NUM); } - -BOOL cpp_get_simdata(HANDLE context, pCNTX *ptr, pSIMDATA *p) { - *ptr = get_context_on_id(context); if (!ptr) return 0; -// if (!*ptr || !(*ptr)->pdata || (*ptr)->mode&(MODE_PGP|MODE_GPG|MODE_RSA)) return FALSE; - if (!*ptr || (*ptr)->mode&(MODE_PGP|MODE_GPG|MODE_RSA)) return FALSE; - *p = (pSIMDATA) cpp_alloc_pdata(*ptr); - return TRUE; +BOOL cpp_get_simdata(HANDLE context, pCNTX *ptr, pSIMDATA *p) +{ + *ptr = get_context_on_id(context); if (!ptr) return 0; + if (!*ptr || (*ptr)->mode&(MODE_PGP | MODE_GPG | MODE_RSA)) return FALSE; + *p = (pSIMDATA)cpp_alloc_pdata(*ptr); + return TRUE; } - -int __cdecl cpp_size_keyx(void) { - return(Tiger::DIGESTSIZE+2); +int __cdecl cpp_size_keyx(void) +{ + return(Tiger::DIGESTSIZE + 2); } - -void __cdecl cpp_get_keyx(HANDLE context, BYTE *key) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return; - memcpy(key,p->KeyX,Tiger::DIGESTSIZE); - memcpy(key+Tiger::DIGESTSIZE,&ptr->features,2); +void __cdecl cpp_get_keyx(HANDLE context, BYTE *key) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return; + memcpy(key, p->KeyX, Tiger::DIGESTSIZE); + memcpy(key + Tiger::DIGESTSIZE, &ptr->features, 2); } - -void __cdecl cpp_set_keyx(HANDLE context, BYTE *key) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return; - SAFE_FREE(p->PubA); - SAFE_FREE(p->KeyA); - mir_free(p->KeyB); p->KeyB = 0; - SAFE_FREE(p->KeyX); - p->KeyX = (PBYTE) malloc(Tiger::DIGESTSIZE+2); - memcpy(p->KeyX,key,Tiger::DIGESTSIZE); - memcpy(&ptr->features,key+Tiger::DIGESTSIZE,2); +void __cdecl cpp_set_keyx(HANDLE context, BYTE *key) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return; + SAFE_FREE(p->PubA); + SAFE_FREE(p->KeyA); + mir_free(p->KeyB); p->KeyB = 0; + SAFE_FREE(p->KeyX); + p->KeyX = (PBYTE)malloc(Tiger::DIGESTSIZE + 2); + memcpy(p->KeyX, key, Tiger::DIGESTSIZE); + memcpy(&ptr->features, key + Tiger::DIGESTSIZE, 2); } - -void __cdecl cpp_get_keyp(HANDLE context, BYTE *key) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return; - memcpy(key,p->KeyP,Tiger::DIGESTSIZE); +void __cdecl cpp_get_keyp(HANDLE context, BYTE *key) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return; + memcpy(key, p->KeyP, Tiger::DIGESTSIZE); } - -int __cdecl cpp_size_keyp(void) { - return(Tiger::DIGESTSIZE); +int __cdecl cpp_size_keyp(void) +{ + return(Tiger::DIGESTSIZE); } - -void __cdecl cpp_set_keyp(HANDLE context, BYTE *key) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return; - SAFE_FREE(p->KeyP); - p->KeyP = (PBYTE) malloc(Tiger::DIGESTSIZE); - memcpy(p->KeyP,key,Tiger::DIGESTSIZE); +void __cdecl cpp_set_keyp(HANDLE context, BYTE *key) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return; + SAFE_FREE(p->KeyP); + p->KeyP = (PBYTE)malloc(Tiger::DIGESTSIZE); + memcpy(p->KeyP, key, Tiger::DIGESTSIZE); } - -int __cdecl cpp_keya(HANDLE context) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return 0; - return p->KeyA!=NULL; +int __cdecl cpp_keya(HANDLE context) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return 0; + return p->KeyA != NULL; } - -int __cdecl cpp_keyb(HANDLE context) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return 0; - return p->KeyB!=NULL; +int __cdecl cpp_keyb(HANDLE context) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return 0; + return p->KeyB != NULL; } - -int __cdecl cpp_keyx(HANDLE context) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return 0; - return p->KeyX!=NULL; +int __cdecl cpp_keyx(HANDLE context) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return 0; + return p->KeyX != NULL; } - -int __cdecl cpp_keyp(HANDLE context) { - pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context,&ptr,&p)) return 0; - return p->KeyP!=NULL; +int __cdecl cpp_keyp(HANDLE context) +{ + pCNTX ptr; pSIMDATA p; if (!cpp_get_simdata(context, &ptr, &p)) return 0; + return p->KeyP != NULL; } - - -// EOF diff --git a/plugins/CryptoPP/src/cpp_pgpw.cpp b/plugins/CryptoPP/src/cpp_pgpw.cpp index 96a6baece4..85de0513f0 100644 --- a/plugins/CryptoPP/src/cpp_pgpw.cpp +++ b/plugins/CryptoPP/src/cpp_pgpw.cpp @@ -6,7 +6,6 @@ UINT pgpVer; HRSRC hRS_pgp; PBYTE pRS_pgp; - int __cdecl _pgp_init(void); int __cdecl _pgp_done(void); int __cdecl _pgp_open_keyrings(LPSTR,LPSTR); @@ -35,15 +34,14 @@ LPSTR (__cdecl *p_pgp_decrypt_keydb)(LPCSTR); LPSTR (__cdecl *p_pgp_encrypt_key)(LPCSTR,LPCSTR); LPSTR (__cdecl *p_pgp_decrypt_key)(LPCSTR,LPCSTR); - #define GPA(x) \ -{ \ +{ \ *((PVOID*)&p##x) = (PVOID)GetProcAddress(mod, TEXT(#x)); \ - if (!p##x) return 0; \ + if (!p##x) return 0; \ } -int load_pgpsdk_dll(HMODULE mod) { - +int load_pgpsdk_dll(HMODULE mod) +{ GPA(_pgp_init); GPA(_pgp_done); GPA(_pgp_open_keyrings); @@ -62,17 +60,16 @@ int load_pgpsdk_dll(HMODULE mod) { #undef GPA - -#define GPA(x) \ -{ \ - *((PVOID*)&p##x) = (PVOID)MemGetProcAddress(mod, TEXT(#x)); \ - if (!p##x) { \ - return 0; \ - } \ +#define GPA(x) \ +{ \ + *((PVOID*)&p##x) = (PVOID)GetProcAddress(mod, TEXT(#x)); \ + if (!p##x) { \ + return 0; \ + } \ } -int load_pgpsdk_mem(HMODULE mod) { - +int load_pgpsdk_mem(HMODULE mod) +{ GPA(_pgp_init); GPA(_pgp_done); GPA(_pgp_open_keyrings); @@ -85,28 +82,25 @@ int load_pgpsdk_mem(HMODULE mod) { GPA(_pgp_decrypt_keydb); GPA(_pgp_encrypt_key); GPA(_pgp_decrypt_key); - return 1; } #undef GPA - int __cdecl pgp_init() { - if ( !hPGPPRIV ) { + if (!hPGPPRIV) { // create context for private pgp keys - hPGPPRIV = (HANDLE) cpp_create_context(MODE_PGP|MODE_PRIV_KEY); - pCNTX tmp = (pCNTX) hPGPPRIV; - tmp->pdata = (PBYTE) malloc(sizeof(PGPDATA)); - memset(tmp->pdata,0,sizeof(PGPDATA)); + hPGPPRIV = (HANDLE)cpp_create_context(MODE_PGP | MODE_PRIV_KEY); + pCNTX tmp = (pCNTX)hPGPPRIV; + tmp->pdata = (PBYTE)malloc(sizeof(PGPDATA)); + memset(tmp->pdata, 0, sizeof(PGPDATA)); } hpgpsdk = g_hInst; return 0; } - int __cdecl pgp_done() { int r = 0; @@ -118,19 +112,16 @@ int __cdecl pgp_done() return r; } - int __cdecl pgp_open_keyrings(LPSTR PubRingPath, LPSTR SecRingPath) { - return p_pgp_open_keyrings(PubRingPath,SecRingPath); + return p_pgp_open_keyrings(PubRingPath, SecRingPath); } - int __cdecl pgp_close_keyrings() { return p_pgp_close_keyrings(); } - int __cdecl pgp_get_version() { return pgpVer; @@ -144,13 +135,13 @@ LPSTR __cdecl pgp_get_error() LPSTR __cdecl pgp_encrypt(pCNTX ptr, LPCSTR szPlainMsg) { ptr->error = ERROR_NONE; - pPGPDATA p = (pPGPDATA) ptr->pdata; + pPGPDATA p = (pPGPDATA)ptr->pdata; LPSTR szEncMsg; - if (p->pgpKey) - szEncMsg = p_pgp_encrypt_key(szPlainMsg,(LPCSTR)p->pgpKey); + if (p->pgpKey) + szEncMsg = p_pgp_encrypt_key(szPlainMsg, (LPCSTR)p->pgpKey); else - szEncMsg = p_pgp_encrypt_keydb(szPlainMsg,p->pgpKeyID); + szEncMsg = p_pgp_encrypt_keydb(szPlainMsg, p->pgpKeyID); if (!szEncMsg) { replaceStr(ptr->tmp, NULL); return 0; @@ -162,7 +153,6 @@ LPSTR __cdecl pgp_encrypt(pCNTX ptr, LPCSTR szPlainMsg) return ptr->tmp; } - LPSTR __cdecl pgp_decrypt(pCNTX ptr, LPCSTR szEncMsg) { ptr->error = ERROR_NONE; @@ -171,9 +161,9 @@ LPSTR __cdecl pgp_decrypt(pCNTX ptr, LPCSTR szEncMsg) if (!szPlainMsg) { ptr = get_context_on_id(hPGPPRIV); // find private pgp keys if (ptr) { - pPGPDATA p = (pPGPDATA) ptr->pdata; + pPGPDATA p = (pPGPDATA)ptr->pdata; if (p->pgpKey) - szPlainMsg = p_pgp_decrypt_key(szEncMsg,(LPCSTR)p->pgpKey); + szPlainMsg = p_pgp_decrypt_key(szEncMsg, (LPCSTR)p->pgpKey); } if (!szPlainMsg) { replaceStr(ptr->tmp, NULL); @@ -186,12 +176,11 @@ LPSTR __cdecl pgp_decrypt(pCNTX ptr, LPCSTR szEncMsg) return ptr->tmp; } - LPSTR __cdecl pgp_encode(HANDLE context, LPCSTR szPlainMsg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - pPGPDATA p = (pPGPDATA) cpp_alloc_pdata(ptr); - if ( !p->pgpKeyID && !p->pgpKey ) { + pPGPDATA p = (pPGPDATA)cpp_alloc_pdata(ptr); + if (!p->pgpKeyID && !p->pgpKey) { ptr->error = ERROR_NO_PGP_KEY; return NULL; } @@ -200,7 +189,6 @@ LPSTR __cdecl pgp_encode(HANDLE context, LPCSTR szPlainMsg) return pgp_encrypt(ptr, szPlainMsg); } - LPSTR __cdecl pgp_decode(HANDLE context, LPCSTR szEncMsg) { pCNTX ptr = get_context_on_id(context); @@ -210,9 +198,9 @@ LPSTR __cdecl pgp_decode(HANDLE context, LPCSTR szEncMsg) LPSTR szOldMsg = pgp_decrypt(ptr, szEncMsg); if (szOldMsg) { - if ( !is_7bit_string(szOldMsg) && !is_utf8_string(szOldMsg) ) { - int slen = (int)strlen(szOldMsg)+1; - LPWSTR wszMsg = (LPWSTR) alloca(slen*sizeof(WCHAR)); + if (!is_7bit_string(szOldMsg) && !is_utf8_string(szOldMsg)) { + int slen = (int)strlen(szOldMsg) + 1; + LPWSTR wszMsg = (LPWSTR)alloca(slen*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, szOldMsg, -1, wszMsg, slen*sizeof(WCHAR)); szNewMsg = _strdup(utf8encode(wszMsg)); } @@ -222,48 +210,42 @@ LPSTR __cdecl pgp_decode(HANDLE context, LPCSTR szEncMsg) return szNewMsg; } - int __cdecl pgp_set_priv_key(LPCSTR LocalKey) { - return pgp_set_key(hPGPPRIV,LocalKey); + return pgp_set_key(hPGPPRIV, LocalKey); } - int __cdecl pgp_set_key(HANDLE context, LPCSTR RemoteKey) { pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pPGPDATA p = (pPGPDATA) cpp_alloc_pdata(ptr); + pPGPDATA p = (pPGPDATA)cpp_alloc_pdata(ptr); ptr->error = ERROR_NONE; SAFE_FREE(p->pgpKey); - p->pgpKey = (PBYTE) _strdup(RemoteKey); + p->pgpKey = (PBYTE)_strdup(RemoteKey); return 1; } - int __cdecl pgp_set_keyid(HANDLE context, PVOID RemoteKeyID) { pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pPGPDATA p = (pPGPDATA) cpp_alloc_pdata(ptr); + pPGPDATA p = (pPGPDATA)cpp_alloc_pdata(ptr); ptr->error = ERROR_NONE; SAFE_FREE(p->pgpKeyID); - p->pgpKeyID = (PBYTE) malloc(p_pgp_size_keyid()); - memcpy(p->pgpKeyID,RemoteKeyID,p_pgp_size_keyid()); + p->pgpKeyID = (PBYTE)malloc(p_pgp_size_keyid()); + memcpy(p->pgpKeyID, RemoteKeyID, p_pgp_size_keyid()); return 1; } - int __cdecl pgp_size_keyid() { return p_pgp_size_keyid(); } - -PVOID __cdecl pgp_select_keyid(HWND hDlg,LPSTR szKeyID) +PVOID __cdecl pgp_select_keyid(HWND hDlg, LPSTR szKeyID) { - return p_pgp_select_keyid(hDlg,szKeyID); + return p_pgp_select_keyid(hDlg, szKeyID); } - diff --git a/plugins/CryptoPP/src/cpp_rsam.cpp b/plugins/CryptoPP/src/cpp_rsam.cpp index 202dffbc94..f20d1c399c 100644 --- a/plugins/CryptoPP/src/cpp_rsam.cpp +++ b/plugins/CryptoPP/src/cpp_rsam.cpp @@ -5,30 +5,30 @@ #define RAND_SIZE (256/8) RSA_EXPORT exports = { - rsa_gen_keypair, - rsa_get_keypair, - rsa_get_keyhash, - rsa_set_keypair, - rsa_get_pubkey, - rsa_set_pubkey, - rsa_set_timeout, - rsa_get_state, - rsa_get_hash, - rsa_connect, - rsa_disconnect, - rsa_disabled, - rsa_recv, - rsa_send, - rsa_encrypt_file, - rsa_decrypt_file, - utf8encode, - utf8decode, - is_7bit_string, - is_utf8_string, - rsa_export_keypair, - rsa_import_keypair, - rsa_export_pubkey, - rsa_import_pubkey + rsa_gen_keypair, + rsa_get_keypair, + rsa_get_keyhash, + rsa_set_keypair, + rsa_get_pubkey, + rsa_set_pubkey, + rsa_set_timeout, + rsa_get_state, + rsa_get_hash, + rsa_connect, + rsa_disconnect, + rsa_disabled, + rsa_recv, + rsa_send, + rsa_encrypt_file, + rsa_decrypt_file, + utf8encode, + utf8decode, + is_7bit_string, + is_utf8_string, + rsa_export_keypair, + rsa_import_keypair, + rsa_export_pubkey, + rsa_import_pubkey }; pRSA_IMPORT imp; @@ -46,30 +46,30 @@ const string crlf = "\x0D\x0A"; /////////////////////////////////////////////////////////////////////////// - -int __cdecl rsa_init(pRSA_EXPORT* e, pRSA_IMPORT i) { +int __cdecl rsa_init(pRSA_EXPORT* e, pRSA_IMPORT i) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_init"); #endif *e = &exports; imp = i; - if ( !hRSA4096 ) { + if (!hRSA4096) { // create context for private rsa keys - hRSA4096 = (HANDLE) cpp_create_context(MODE_RSA_4096|MODE_PRIV_KEY); - pCNTX tmp = (pCNTX) hRSA4096; + hRSA4096 = (HANDLE)cpp_create_context(MODE_RSA_4096 | MODE_PRIV_KEY); + pCNTX tmp = (pCNTX)hRSA4096; pRSAPRIV p = new RSAPRIV; - tmp->pdata = (PBYTE) p; + tmp->pdata = (PBYTE)p; } return 1; } - -int __cdecl rsa_done(void) { +int __cdecl rsa_done(void) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_done"); #endif - if ( hRSA4096 ) { - pCNTX tmp = (pCNTX) hRSA4096; + if (hRSA4096) { + pCNTX tmp = (pCNTX)hRSA4096; pRSAPRIV p = (pRSAPRIV)tmp->pdata; delete p; tmp->pdata = 0; @@ -84,15 +84,15 @@ int __cdecl rsa_done(void) { /////////////////////////////////////////////////////////////////////////// -pRSAPRIV rsa_gen_keys(HANDLE context) { - - if ( context!=hRSA4096 ) return 0; +pRSAPRIV rsa_gen_keys(HANDLE context) +{ + if (context != hRSA4096) return 0; #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_gen_keys: %d", context); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSAPRIV r = (pRSAPRIV) ptr->pdata; + pRSAPRIV r = (pRSAPRIV)ptr->pdata; string priv, pub; GenerateRSAKey(4096, priv, pub); @@ -100,149 +100,146 @@ pRSAPRIV rsa_gen_keys(HANDLE context) { StringSource privsrc(priv, true, NULL); RSAES_PKCS1v15_Decryptor Decryptor(privsrc); - priv = tlv(1, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModulus() )) + - tlv(2, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPublicExponent() )) + - tlv(3, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrivateExponent() )) + - tlv(4, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime1() )) + - tlv(5, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime2() )) + - tlv(6, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime1PrivateExponent() )) + - tlv(7, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime2PrivateExponent() )) + - tlv(8, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetMultiplicativeInverseOfPrime2ModPrime1() )); + priv = tlv(1, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModulus())) + + tlv(2, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPublicExponent())) + + tlv(3, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrivateExponent())) + + tlv(4, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime1())) + + tlv(5, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime2())) + + tlv(6, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime1PrivateExponent())) + + tlv(7, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime2PrivateExponent())) + + tlv(8, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetMultiplicativeInverseOfPrime2ModPrime1())); - init_priv(r,priv); + init_priv(r, priv); return r; } - -pRSAPRIV rsa_get_priv(pCNTX ptr) { +pRSAPRIV rsa_get_priv(pCNTX ptr) +{ pCNTX p = get_context_on_id(hRSA4096); if (!p) return 0; - pRSAPRIV r = (pRSAPRIV) p->pdata; + pRSAPRIV r = (pRSAPRIV)p->pdata; return r; } - -int __cdecl rsa_gen_keypair(short mode) { +int __cdecl rsa_gen_keypair(short mode) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_gen_keypair: %d", mode); #endif - if ( mode&MODE_RSA_4096 ) rsa_gen_keys(hRSA4096); // 4096 + if (mode&MODE_RSA_4096) rsa_gen_keys(hRSA4096); // 4096 return 1; } - -int __cdecl rsa_get_keypair(short mode, PBYTE privKey, int* privKeyLen, PBYTE pubKey, int* pubKeyLen) { +int __cdecl rsa_get_keypair(short mode, PBYTE privKey, int* privKeyLen, PBYTE pubKey, int* pubKeyLen) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_get_keypair: %d", mode); #endif pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0; - pRSAPRIV r = (pRSAPRIV) ptr->pdata; - - *privKeyLen = (int)r->priv_k.length(); if ( privKey ) r->priv_k.copy((char*)privKey, *privKeyLen); - *pubKeyLen = (int)r->pub_k.length(); if ( pubKey ) r->pub_k.copy((char*)pubKey, *pubKeyLen); + pRSAPRIV r = (pRSAPRIV)ptr->pdata; + *privKeyLen = (int)r->priv_k.length(); if (privKey) r->priv_k.copy((char*)privKey, *privKeyLen); + *pubKeyLen = (int)r->pub_k.length(); if (pubKey) r->pub_k.copy((char*)pubKey, *pubKeyLen); return 1; } - -int __cdecl rsa_get_keyhash(short mode, PBYTE privKey, int* privKeyLen, PBYTE pubKey, int* pubKeyLen) { +int __cdecl rsa_get_keyhash(short mode, PBYTE privKey, int* privKeyLen, PBYTE pubKey, int* pubKeyLen) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_get_keyhash: %d", mode); #endif pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0; - pRSAPRIV r = (pRSAPRIV) ptr->pdata; + pRSAPRIV r = (pRSAPRIV)ptr->pdata; - if ( privKey ) { *privKeyLen = (int)r->priv_s.length(); r->priv_s.copy((char*)privKey, *privKeyLen); } - if ( pubKey ) { *pubKeyLen = (int)r->pub_s.length(); r->pub_s.copy((char*)pubKey, *pubKeyLen); } + if (privKey) { *privKeyLen = (int)r->priv_s.length(); r->priv_s.copy((char*)privKey, *privKeyLen); } + if (pubKey) { *pubKeyLen = (int)r->pub_s.length(); r->pub_s.copy((char*)pubKey, *pubKeyLen); } return 1; } - -int __cdecl rsa_set_keypair(short mode, PBYTE privKey, int privKeyLen) { +int __cdecl rsa_set_keypair(short mode, PBYTE privKey, int privKeyLen) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_set_keypair: %s", privKey); #endif pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0; - pRSAPRIV r = (pRSAPRIV) ptr->pdata; - - if ( privKey && privKeyLen ) { - string priv; - priv.assign((char*)privKey, privKeyLen); - - if ( mode & MODE_RSA_BER ) { - // old BER format - StringStore s(priv); - r->priv.BERDecode(s); - - RSAES_PKCS1v15_Decryptor Decryptor(r->priv); - - priv = tlv(1, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModulus() )) + - tlv(2, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPublicExponent() )) + - tlv(3, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrivateExponent() )) + - tlv(4, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime1() )) + - tlv(5, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime2() )) + - tlv(6, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime1PrivateExponent() )) + - tlv(7, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime2PrivateExponent() )) + - tlv(8, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetMultiplicativeInverseOfPrime2ModPrime1() )); - - } - init_priv(r,priv); + pRSAPRIV r = (pRSAPRIV)ptr->pdata; + + if (privKey && privKeyLen) { + string priv; + priv.assign((char*)privKey, privKeyLen); + + if (mode & MODE_RSA_BER) { + // old BER format + StringStore s(priv); + r->priv.BERDecode(s); + + RSAES_PKCS1v15_Decryptor Decryptor(r->priv); + + priv = tlv(1, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModulus())) + + tlv(2, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPublicExponent())) + + tlv(3, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrivateExponent())) + + tlv(4, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime1())) + + tlv(5, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetPrime2())) + + tlv(6, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime1PrivateExponent())) + + tlv(7, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetModPrime2PrivateExponent())) + + tlv(8, IntegerToBinary(Decryptor.GetTrapdoorFunction().GetMultiplicativeInverseOfPrime2ModPrime1())); + + } + init_priv(r, priv); } return 1; } - -int __cdecl rsa_get_pubkey(HANDLE context, PBYTE pubKey, int* pubKeyLen) { +int __cdecl rsa_get_pubkey(HANDLE context, PBYTE pubKey, int* pubKeyLen) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_get_pubkey: %s", pubKey); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); - *pubKeyLen = (int)p->pub_k.length(); if ( pubKey ) p->pub_k.copy((char*)pubKey, *pubKeyLen); + *pubKeyLen = (int)p->pub_k.length(); if (pubKey) p->pub_k.copy((char*)pubKey, *pubKeyLen); return 1; } - -int __cdecl rsa_set_pubkey(HANDLE context, PBYTE pubKey, int pubKeyLen) { +int __cdecl rsa_set_pubkey(HANDLE context, PBYTE pubKey, int pubKeyLen) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_set_pubkey: %s", pubKey); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); - if ( pubKey && pubKeyLen ) { - string pub; - pub.assign((char*)pubKey, pubKeyLen); - init_pub(p,pub); + if (pubKey && pubKeyLen) { + string pub; + pub.assign((char*)pubKey, pubKeyLen); + init_pub(p, pub); } return 1; } - -void __cdecl rsa_set_timeout(int t) { +void __cdecl rsa_set_timeout(int t) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_set_timeout: %d", t); #endif timeout = t; } - -int __cdecl rsa_get_state(HANDLE context) { - +int __cdecl rsa_get_state(HANDLE context) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); - + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); return p->state; } - -int __cdecl rsa_get_hash(PBYTE pubKey, int pubKeyLen, PBYTE pubHash, int* pubHashLen) { +int __cdecl rsa_get_hash(PBYTE pubKey, int pubKeyLen, PBYTE pubHash, int* pubHashLen) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_get_hash: %d", pubKeyLen); #endif @@ -256,104 +253,103 @@ int __cdecl rsa_get_hash(PBYTE pubKey, int pubKeyLen, PBYTE pubHash, int* pubHas return 1; } - -int __cdecl rsa_connect(HANDLE context) { +int __cdecl rsa_connect(HANDLE context) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_connect: %08x", context); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state) return p->state; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); if (p->state) return p->state; pRSAPRIV r = rsa_get_priv(ptr); - if (ptr->mode&MODE_RSA_ONLY) { - inject_msg(context,0x0D,tlv(0,0)+tlv(1,r->pub_k)+tlv(2,p->pub_s)); + if (ptr->mode&MODE_RSA_ONLY) { + inject_msg(context, 0x0D, tlv(0, 0) + tlv(1, r->pub_k) + tlv(2, p->pub_s)); p->state = 0x0D; - } - else { - inject_msg(context,0x10,tlv(0,0)+tlv(1,r->pub_s)+tlv(2,p->pub_s)); + } + else { + inject_msg(context, 0x10, tlv(0, 0) + tlv(1, r->pub_s) + tlv(2, p->pub_s)); p->state = 2; } - p->time = gettime()+timeout; + p->time = gettime() + timeout; return p->state; } - -int __cdecl rsa_disconnect(HANDLE context) { +int __cdecl rsa_disconnect(HANDLE context) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_disconnect: %08x", context); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - rsa_free( ptr ); // удалим трэд и очередь сообщений + rsa_free(ptr); // удалим трэд и очередь сообщений - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); - if ( !p->state ) return 1; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); + if (!p->state) return 1; - PBYTE buffer=(PBYTE) alloca(RAND_SIZE); - GlobalRNG().GenerateBlock(buffer,RAND_SIZE); - inject_msg(context,0xF0,encode_msg(0,p,::hash(buffer,RAND_SIZE))); + PBYTE buffer = (PBYTE)alloca(RAND_SIZE); + GlobalRNG().GenerateBlock(buffer, RAND_SIZE); + inject_msg(context, 0xF0, encode_msg(0, p, ::hash(buffer, RAND_SIZE))); p->state = 0; - imp->rsa_notify(context,-3); // соединение разорвано вручную + imp->rsa_notify(context, -3); // соединение разорвано вручную return 1; } - -int __cdecl rsa_disabled(HANDLE context) { +int __cdecl rsa_disabled(HANDLE context) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_disabled: %08x", context); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - rsa_free( ptr ); // удалим трэд и очередь сообщений + rsa_free(ptr); // удалим трэд и очередь сообщений - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); p->state = 0; - inject_msg(context,0xFF,null); -// imp->rsa_notify(-context,-8); // соединение разорвано по причине "disabled" + inject_msg(context, 0xFF, null); + // imp->rsa_notify(-context,-8); // соединение разорвано по причине "disabled" return 1; } - -LPSTR __cdecl rsa_recv(HANDLE context, LPCSTR msg) { - +LPSTR __cdecl rsa_recv(HANDLE context, LPCSTR msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_recv: %s", msg); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); pRSAPRIV r = rsa_get_priv(ptr); rtrim(msg); string buf = base64decode(msg); - if ( !buf.length() ) return 0; + if (!buf.length()) return 0; string data; int type; - un_tlv(buf,type,data); - if ( type==-1 ) return 0; + un_tlv(buf, type, data); + if (type == -1) return 0; #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_recv: %02x %d", type, p->state); #endif - if ( type>0x10 && type<0xE0 ) // проверим тип сообщения (когда соединение еще не установлено) - if ( p->state==0 || p->state!=(type>>4) ) { // неверное состояние - // шлем перерывание сессии - p->state=0; p->time=0; - rsa_free( ptr ); // удалим трэд и очередь сообщений - null_msg(context,0x00,-1); // сессия разорвана по ошибке, неверный тип сообщения - return 0; - } + if (type > 0x10 && type < 0xE0) // проверим тип сообщения (когда соединение еще не установлено) + if (p->state == 0 || p->state != (type >> 4)) { // неверное состояние + // шлем перерывание сессии + p->state = 0; p->time = 0; + rsa_free(ptr); // удалим трэд и очередь сообщений + null_msg(context, 0x00, -1); // сессия разорвана по ошибке, неверный тип сообщения + return 0; + } - switch( type ) { + switch (type) { case 0x00: // прерывание сессии по ошибке другой стороной { - // если соединение установлено - ничего не делаем - if ( p->state == 0 || p->state == 7 ) return 0; + // если соединение установлено - ничего не делаем + if (p->state == 0 || p->state == 7) return 0; // иначе сбрасываем текущее состояние - p->state=0; p->time=0; - imp->rsa_notify(context,-2); // сессия разорвана по ошибке другой стороной + p->state = 0; p->time = 0; + imp->rsa_notify(context, -2); // сессия разорвана по ошибке другой стороной } break; // это все будем обрабатывать в отдельном потоке, чтобы избежать таймаутов @@ -368,128 +364,125 @@ LPSTR __cdecl rsa_recv(HANDLE context, LPCSTR msg) { case 0x40: case 0x0D: // запрос паблика case 0xD0: // ответ пабликом - { - if ( !p->event ) { - p->event = CreateEvent(NULL,FALSE,FALSE,NULL); + if (!p->event) { + p->event = CreateEvent(NULL, FALSE, FALSE, NULL); unsigned int tID; - p->thread = (HANDLE) _beginthreadex(NULL, 0, sttConnectThread, (PVOID)context, 0, &tID); + p->thread = (HANDLE)_beginthreadex(NULL, 0, sttConnectThread, (PVOID)context, 0, &tID); #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_recv: _beginthreadex(sttConnectThread)"); #endif } - EnterCriticalSection(&localQueueMutex); - p->queue->push(tlv(type,data)); - LeaveCriticalSection(&localQueueMutex); + { + mir_cslock lck(localQueueMutex); + p->queue->push(tlv(type, data)); + } SetEvent(p->event); // сказали обрабатывать :) - } break; + break; case 0x50: // получили криптотест, отправляем свой криптотест - { - string msg = decode_msg(p,data); - if ( !msg.length() ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке + if (!decode_msg(p, data).length()) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке return 0; } - PBYTE buffer=(PBYTE) alloca(RAND_SIZE); - GlobalRNG().GenerateBlock(buffer,RAND_SIZE); - inject_msg(context,0x60,encode_msg(0,p,::hash(buffer,RAND_SIZE))); - p->state=7; p->time=0; - rsa_free_thread( p ); // удалим трэд и очередь сообщений - imp->rsa_notify(context,1); // заебися, криптосессия установлена - } break; + { + PBYTE buffer = (PBYTE)alloca(RAND_SIZE); + GlobalRNG().GenerateBlock(buffer, RAND_SIZE); + inject_msg(context, 0x60, encode_msg(0, p, ::hash(buffer, RAND_SIZE))); + } + p->state = 7; p->time = 0; + rsa_free_thread(p); // удалим трэд и очередь сообщений + imp->rsa_notify(context, 1); // заебися, криптосессия установлена + break; case 0x60: // получили криптотест, сессия установлена - { - string msg = decode_msg(p,data); - if ( !msg.length() ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке + if (!decode_msg(p, data).length()) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке return 0; } - p->state=7; p->time=0; - rsa_free_thread( p ); // удалим трэд и очередь сообщений - imp->rsa_notify(context,1); // заебися, криптосессия установлена - } break; + p->state = 7; p->time = 0; + rsa_free_thread(p); // удалим трэд и очередь сообщений + imp->rsa_notify(context, 1); // заебися, криптосессия установлена + break; case 0x70: // получили AES сообщение, декодируем { - string msg = decode_msg(p,data); - if ( msg.length() ) + string msg = decode_msg(p, data); + if (msg.length()) replaceStr(ptr->tmp, mir_strdup(msg.c_str())); else { - imp->rsa_notify(context,-5); // ошибка декодирования AES сообщения + imp->rsa_notify(context, -5); // ошибка декодирования AES сообщения replaceStr(ptr->tmp, NULL); } + } return ptr->tmp; - } break; case 0xE0: // получили RSA сообщение, декодируем { - string msg = decode_rsa(p,r,data); - if ( msg.length() ) + string msg = decode_rsa(p, r, data); + if (msg.length()) replaceStr(ptr->tmp, mir_strdup(msg.c_str())); else { - imp->rsa_notify(context,-6); // ошибка декодирования RSA сообщения + imp->rsa_notify(context, -6); // ошибка декодирования RSA сообщения replaceStr(ptr->tmp, NULL); } + } return ptr->tmp; - } break; case 0xF0: // разрыв соединения вручную { - if ( p->state != 7 ) return 0; - string msg = decode_msg(p,data); - if ( !msg.length() ) return 0; - p->state=0; - rsa_free( ptr ); // удалим трэд и очередь сообщений - imp->rsa_notify(context,-4); // соединение разорвано вручную другой стороной - } break; + if (p->state != 7) return 0; + string msg = decode_msg(p, data); + if (!msg.length()) return 0; + p->state = 0; + rsa_free(ptr); // удалим трэд и очередь сообщений + imp->rsa_notify(context, -4); // соединение разорвано вручную другой стороной + } + break; case 0xFF: // разрыв соединения по причине "disabled" - { - p->state=0; - rsa_free( ptr ); // удалим трэд и очередь сообщений - imp->rsa_notify(context,-8); // соединение разорвано по причине "disabled" - } break; - + p->state = 0; + rsa_free(ptr); // удалим трэд и очередь сообщений + imp->rsa_notify(context, -8); // соединение разорвано по причине "disabled" + break; } - if ( p->state != 0 && p->state != 7 ) + if (p->state != 0 && p->state != 7) p->time = gettime() + timeout; return 0; } -int __cdecl rsa_send(HANDLE context, LPCSTR msg) { - +int __cdecl rsa_send(HANDLE context, LPCSTR msg) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state!=0 && p->state!=7) return 0; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); if (p->state != 0 && p->state != 7) return 0; - if ( p->state == 7 ) // сессия установлена, шифруем AES и отправляем - inject_msg(context,0x70,encode_msg(1,p,string(msg))); - else - if ( p->state == 0 ) { // сессия установлена, отправляем RSA сообщение - if ( !p->pub_k.length() ) return 0; + if (p->state == 7) // сессия установлена, шифруем AES и отправляем + inject_msg(context, 0x70, encode_msg(1, p, string(msg))); + else if (p->state == 0) { // сессия установлена, отправляем RSA сообщение + if (!p->pub_k.length()) return 0; // есть паблик ключ - отправим сообщение pRSAPRIV r = rsa_get_priv(ptr); - inject_msg(context,0xE0,encode_rsa(1,p,r,string(msg))); + inject_msg(context, 0xE0, encode_rsa(1, p, r, string(msg))); } return 1; } - -void inject_msg(HANDLE context, int type, const string& msg) { +void inject_msg(HANDLE context, int type, const string& msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("inject_msg(%02x): %s", type, msg.c_str()); #endif - string txt=base64encode(tlv(type,msg)); - imp->rsa_inject(context,(LPCSTR)txt.c_str()); + string txt = base64encode(tlv(type, msg)); + imp->rsa_inject(context, (LPCSTR)txt.c_str()); } -string encode_msg(short z, pRSADATA p, string& msg) { +string encode_msg(short z, pRSADATA p, string& msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("encode_msg: %s", msg.c_str()); #endif @@ -498,36 +491,35 @@ string encode_msg(short z, pRSADATA p, string& msg) { string ciphered; try { - CBC_Mode::Encryption enc((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data()); - StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered)); - cbcEncryptor.Put((PBYTE)zlib.data(),zlib.length()); + CBC_Mode::Encryption enc((PBYTE)p->aes_k.data(), p->aes_k.length(), (PBYTE)p->aes_v.data()); + StreamTransformationFilter cbcEncryptor(enc, new StringSink(ciphered)); + cbcEncryptor.Put((PBYTE)zlib.data(), zlib.length()); cbcEncryptor.MessageEnd(); } catch (...) { ; } - return tlv(z,ciphered)+tlv(2,sig); + return tlv(z, ciphered) + tlv(2, sig); } - -string decode_msg(pRSADATA p, string& msg) { +string decode_msg(pRSADATA p, string& msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("decode_msg: %s", msg.c_str()); #endif - string ciphered,sig; int t1,t2; - un_tlv(msg,t1,ciphered); - un_tlv(msg,t2,sig); + string ciphered, sig; int t1, t2; + un_tlv(msg, t1, ciphered); + un_tlv(msg, t2, sig); - string unciphered,zlib; + string unciphered, zlib; try { - CBC_Mode::Decryption dec((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data()); - StreamTransformationFilter cbcDecryptor(dec,new StringSink(zlib)); - cbcDecryptor.Put((PBYTE)ciphered.data(),ciphered.length()); + CBC_Mode::Decryption dec((PBYTE)p->aes_k.data(), p->aes_k.length(), (PBYTE)p->aes_v.data()); + StreamTransformationFilter cbcDecryptor(dec, new StringSink(zlib)); + cbcDecryptor.Put((PBYTE)ciphered.data(), ciphered.length()); cbcDecryptor.MessageEnd(); - if ( sig == ::hash(zlib) ) { - unciphered = (t1==1) ? cpp_zlibd(zlib) : zlib; - } + if (sig == ::hash(zlib)) + unciphered = (t1 == 1) ? cpp_zlibd(zlib) : zlib; } catch (...) { ; @@ -535,56 +527,57 @@ string decode_msg(pRSADATA p, string& msg) { return unciphered; } - -string encode_rsa(short z, pRSADATA p, pRSAPRIV r, string& msg) { +string encode_rsa(short z, pRSADATA p, pRSAPRIV r, string& msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("encode_rsa: %s", msg.c_str()); #endif string zlib = (z) ? cpp_zlibc(msg) : msg; - string enc = RSAEncryptString(p->pub,zlib); - string sig = RSASignString(r->priv,zlib); + string enc = RSAEncryptString(p->pub, zlib); + string sig = RSASignString(r->priv, zlib); - return tlv(z,enc)+tlv(2,sig); + return tlv(z, enc) + tlv(2, sig); } - -string decode_rsa(pRSADATA p, pRSAPRIV r, string& msg) { +string decode_rsa(pRSADATA p, pRSAPRIV r, string& msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("decode_rsa: %s", msg.c_str()); #endif - string ciphered,sig; int t1,t2; - un_tlv(msg,t1,ciphered); - un_tlv(msg,t2,sig); - - string unciphered,zlib; - zlib = RSADecryptString(r->priv,ciphered); - if ( zlib.length() && RSAVerifyString(p->pub,zlib,sig) ) { - unciphered = (t1==1) ? cpp_zlibd(zlib) : zlib; + string ciphered, sig; int t1, t2; + un_tlv(msg, t1, ciphered); + un_tlv(msg, t2, sig); + + string unciphered, zlib; + zlib = RSADecryptString(r->priv, ciphered); + if (zlib.length() && RSAVerifyString(p->pub, zlib, sig)) { + unciphered = (t1 == 1) ? cpp_zlibd(zlib) : zlib; } return unciphered; } -string gen_aes_key_iv(short m, pRSADATA p, pRSAPRIV r) { +string gen_aes_key_iv(short m, pRSADATA p, pRSAPRIV r) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("gen_aes_key_iv: %04x", m); #endif - PBYTE buffer=(PBYTE) alloca(RAND_SIZE); + PBYTE buffer = (PBYTE)alloca(RAND_SIZE); GlobalRNG().GenerateBlock(buffer, RAND_SIZE); - p->aes_k = hash256(buffer,RAND_SIZE); - + p->aes_k = hash256(buffer, RAND_SIZE); + GlobalRNG().GenerateBlock(buffer, RAND_SIZE); - p->aes_v = hash256(buffer,RAND_SIZE); + p->aes_v = hash256(buffer, RAND_SIZE); - string buf = tlv(10,p->aes_k)+tlv(11,p->aes_v); + string buf = tlv(10, p->aes_k) + tlv(11, p->aes_v); - return encode_rsa(0,p,r,buf); + return encode_rsa(0, p, r, buf); } - -void init_priv(pRSAPRIV r, string& priv) { +void init_priv(pRSAPRIV r, string& priv) +{ r->priv_k = priv; r->priv_s = ::hash(priv); @@ -592,9 +585,9 @@ void init_priv(pRSAPRIV r, string& priv) { int t; string tmp, n, e, d, p, q, dp, dq, u; - while( priv.length() ) { - un_tlv(priv,t,tmp); - switch(t) { + while (priv.length()) { + un_tlv(priv, t, tmp); + switch (t) { case 1: n = tmp; break; case 2: e = tmp; break; case 3: d = tmp; break; @@ -608,26 +601,25 @@ void init_priv(pRSAPRIV r, string& priv) { // if ( !empty ); - r->pub_k = tlv(1,n)+tlv(2,e); + r->pub_k = tlv(1, n) + tlv(2, e); r->pub_s = ::hash(r->pub_k); - r->priv.Initialize(BinaryToInteger(n),BinaryToInteger(e), - BinaryToInteger(d),BinaryToInteger(p),BinaryToInteger(q), - BinaryToInteger(dp),BinaryToInteger(dq),BinaryToInteger(u)); + r->priv.Initialize(BinaryToInteger(n), BinaryToInteger(e), + BinaryToInteger(d), BinaryToInteger(p), BinaryToInteger(q), + BinaryToInteger(dp), BinaryToInteger(dq), BinaryToInteger(u)); } - -void init_pub(pRSADATA p, string& pub) { - +void init_pub(pRSADATA p, string& pub) +{ p->pub_k = pub; p->pub_s = ::hash(pub); int t; string tmp, n, e; - while( pub.length() ) { - un_tlv(pub,t,tmp); - switch(t) { + while (pub.length()) { + un_tlv(pub, t, tmp); + switch (t) { case 1: n = tmp; break; case 2: e = tmp; break; } @@ -635,37 +627,36 @@ void init_pub(pRSADATA p, string& pub) { // if ( !empty ); - p->pub.Initialize(BinaryToInteger(n),BinaryToInteger(e)); + p->pub.Initialize(BinaryToInteger(n), BinaryToInteger(e)); } - -void null_msg(HANDLE context, int type, int status) { +void null_msg(HANDLE context, int type, int status) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("null_msg: %02x", status); #endif - inject_msg(context,type,null); - imp->rsa_notify(context,status); + inject_msg(context, type, null); + imp->rsa_notify(context, status); } - -void rsa_timeout(HANDLE context, pRSADATA p) { +void rsa_timeout(HANDLE context, pRSADATA p) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_timeout"); #endif - p->state=0; p->time=0; -// null_msg(context,0x00,-7); - imp->rsa_notify(context,-7); // сессия разорвана по таймауту + p->state = 0; p->time = 0; + // null_msg(context,0x00,-7); + imp->rsa_notify(context, -7); // сессия разорвана по таймауту } - -int __cdecl rsa_encrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) { - +int __cdecl rsa_encrypt_file(HANDLE context, LPCSTR file_in, LPCSTR file_out) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state!=7) return 0; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); if (p->state != 7) return 0; try { - CBC_Mode::Encryption enc((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data()); - FileSource *f = new FileSource(file_in,true,new StreamTransformationFilter (enc,new FileSink(file_out))); + CBC_Mode::Encryption enc((PBYTE)p->aes_k.data(), p->aes_k.length(), (PBYTE)p->aes_v.data()); + FileSource *f = new FileSource(file_in, true, new StreamTransformationFilter(enc, new FileSink(file_out))); delete f; } catch (...) { @@ -675,14 +666,14 @@ int __cdecl rsa_encrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) { } -int __cdecl rsa_decrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) { - +int __cdecl rsa_decrypt_file(HANDLE context, LPCSTR file_in, LPCSTR file_out) +{ pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); if (p->state!=7) return 0; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); if (p->state != 7) return 0; try { - CBC_Mode::Decryption dec((PBYTE)p->aes_k.data(),p->aes_k.length(),(PBYTE)p->aes_v.data()); - FileSource *f = new FileSource(file_in,true,new StreamTransformationFilter (dec,new FileSink(file_out))); + CBC_Mode::Decryption dec((PBYTE)p->aes_k.data(), p->aes_k.length(), (PBYTE)p->aes_v.data()); + FileSource *f = new FileSource(file_in, true, new StreamTransformationFilter(dec, new FileSink(file_out))); delete f; } catch (...) { @@ -691,231 +682,235 @@ int __cdecl rsa_decrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) { return 1; } - -int __cdecl rsa_recv_thread(HANDLE context, string& msg) { - +int __cdecl rsa_recv_thread(HANDLE context, string& msg) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_recv_thread: %s", msg.c_str()); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); pRSAPRIV r = rsa_get_priv(ptr); string data; int type; - un_tlv(msg,type,data); - if ( type==-1 ) return 0; + un_tlv(msg, type, data); + if (type == -1) return 0; #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_recv_thread: %02x %d", type, p->state); #endif - int t[4]; - - switch( type ) { + int t[4], features; + switch (type) { case 0x10: - { - int features; string sha1,sha2; - un_tlv(un_tlv(un_tlv(data,t[0],features),t[1],sha1),t[2],sha2); - BOOL lr = (p->pub_s==sha1); BOOL ll = (r->pub_s==sha2); - switch((lr << 4) | ll) { - case 0x11: // оба паблика совпали - inject_msg(context,0x21,gen_aes_key_iv(ptr->mode,p,r)); - p->state = 5; - break; - case 0x10: // совпал удаленный паблик, нужен локальный - inject_msg(context,0x22,tlv(0,features)+tlv(1,r->pub_k)+tlv(2,r->pub_s)); - p->state = 3; - break; - case 0x01: // совпал локальный паблик, нужен удаленный - inject_msg(context,0x23,tlv(0,features)); - p->state = 3; - break; - case 0x00: // не совпали оба паблика - inject_msg(context,0x24,tlv(0,features)+tlv(1,r->pub_k)+tlv(2,r->pub_s)); - p->state = 3; - break; + { + string sha1, sha2; + un_tlv(un_tlv(un_tlv(data, t[0], features), t[1], sha1), t[2], sha2); + BOOL lr = (p->pub_s == sha1); BOOL ll = (r->pub_s == sha2); + switch ((lr << 4) | ll) { + case 0x11: // оба паблика совпали + inject_msg(context, 0x21, gen_aes_key_iv(ptr->mode, p, r)); + p->state = 5; + break; + case 0x10: // совпал удаленный паблик, нужен локальный + inject_msg(context, 0x22, tlv(0, features) + tlv(1, r->pub_k) + tlv(2, r->pub_s)); + p->state = 3; + break; + case 0x01: // совпал локальный паблик, нужен удаленный + inject_msg(context, 0x23, tlv(0, features)); + p->state = 3; + break; + case 0x00: // не совпали оба паблика + inject_msg(context, 0x24, tlv(0, features) + tlv(1, r->pub_k) + tlv(2, r->pub_s)); + p->state = 3; + break; + } } - } break; + break; case 0x22: // получили удаленный паблик, отправляем уже криптоключ - { - int features; string pub; - un_tlv(un_tlv(data,t[0],features),t[1],pub); - string sig = ::hash(pub); - if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(), (int)pub.length(),(PBYTE)sig.data(), (int)sig.length()) ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке - return 0; - } - init_pub(p,pub); - if ( p->state==0 ) { // timeout -// rsa_connect(context); - return -1; + { + string pub; + un_tlv(un_tlv(data, t[0], features), t[1], pub); + string sig = ::hash(pub); + if (!imp->rsa_check_pub(context, (PBYTE)pub.data(), (int)pub.length(), (PBYTE)sig.data(), (int)sig.length())) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке + return 0; + } + init_pub(p, pub); + if (p->state == 0) { // timeout + // rsa_connect(context); + return -1; + } + inject_msg(context, 0x32, gen_aes_key_iv(ptr->mode, p, r)); + p->state = 5; } - inject_msg(context,0x32,gen_aes_key_iv(ptr->mode,p,r)); - p->state=5; - } break; + break; case 0x23: // отправляем локальный паблик - { - int features; - un_tlv(data,t[0],features); - inject_msg(context,0x33,tlv(1,r->pub_k)+tlv(2,r->pub_s)); - p->state=4; - } break; + un_tlv(data, t[0], features); + inject_msg(context, 0x33, tlv(1, r->pub_k) + tlv(2, r->pub_s)); + p->state = 4; + break; case 0x24: // получили удаленный паблик, отправим локальный паблик - { - int features; string pub; - un_tlv(un_tlv(data,t[0],features),t[1],pub); - string sig = ::hash(pub); - if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(), (int)pub.length(),(PBYTE)sig.data(), (int)sig.length()) ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке - return 0; - } - init_pub(p,pub); - if ( p->state==0 ) { // timeout -// rsa_connect(context); - return -1; + { + string pub; + un_tlv(un_tlv(data, t[0], features), t[1], pub); + string sig = ::hash(pub); + if (!imp->rsa_check_pub(context, (PBYTE)pub.data(), (int)pub.length(), (PBYTE)sig.data(), (int)sig.length())) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке + return 0; + } + init_pub(p, pub); + if (p->state == 0) { // timeout + // rsa_connect(context); + return -1; + } + inject_msg(context, 0x34, tlv(1, r->pub_k) + tlv(2, r->pub_s)); + p->state = 4; } - inject_msg(context,0x34,tlv(1,r->pub_k)+tlv(2,r->pub_s)); - p->state=4; - } break; + break; case 0x33: // получили удаленный паблик, отправляем криптоключ case 0x34: - { - string pub; - un_tlv(data,t[0],pub); - string sig = ::hash(pub); - if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(), (int)pub.length(), (PBYTE)sig.data(), (int)sig.length()) ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке - return 0; - } - init_pub(p,pub); - if ( p->state==0 ) { // timeout -// rsa_connect(context); - return -1; + { + string pub; + un_tlv(data, t[0], pub); + string sig = ::hash(pub); + if (!imp->rsa_check_pub(context, (PBYTE)pub.data(), (int)pub.length(), (PBYTE)sig.data(), (int)sig.length())) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке + return 0; + } + init_pub(p, pub); + if (p->state == 0) { // timeout + // rsa_connect(context); + return -1; + } + inject_msg(context, 0x40, gen_aes_key_iv(ptr->mode, p, r)); + p->state = 5; } - inject_msg(context,0x40,gen_aes_key_iv(ptr->mode,p,r)); - p->state=5; - } break; + break; case 0x21: // получили криптоключ, отправляем криптотест case 0x32: case 0x40: - { - string key = decode_rsa(p,r,data); - if ( !key.length() ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке - return 0; + { + string key = decode_rsa(p, r, data); + if (!key.length()) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке + return 0; + } + un_tlv(key, t[0], p->aes_k); + un_tlv(key, t[1], p->aes_v); + PBYTE buffer = (PBYTE)alloca(RAND_SIZE); + GlobalRNG().GenerateBlock(buffer, RAND_SIZE); + inject_msg(context, 0x50, encode_msg(0, p, ::hash(buffer, RAND_SIZE))); + p->state = 6; } - un_tlv(key,t[0],p->aes_k); - un_tlv(key,t[1],p->aes_v); - PBYTE buffer=(PBYTE) alloca(RAND_SIZE); - GlobalRNG().GenerateBlock(buffer,RAND_SIZE); - inject_msg(context,0x50,encode_msg(0, p, ::hash(buffer,RAND_SIZE))); - p->state=6; - } break; + break; case 0x0D: // запрос паблика case 0xD0: // ответ пабликом - { - int features; string pub,sha; - un_tlv(un_tlv(un_tlv(data,t[0],features),t[1],pub),t[2],sha); - if ( p->pub_k!=pub ) { // пришел новый паблик - string sig = ::hash(pub); - if ( !imp->rsa_check_pub(context,(PBYTE)pub.data(), (int)pub.length(),(PBYTE)sig.data(), (int)sig.length()) ) { - p->state=0; p->time=0; - null_msg(context,0x00,-type); // сессия разорвана по ошибке - return 0; + { + string pub, sha; + un_tlv(un_tlv(un_tlv(data, t[0], features), t[1], pub), t[2], sha); + if (p->pub_k != pub) { // пришел новый паблик + string sig = ::hash(pub); + if (!imp->rsa_check_pub(context, (PBYTE)pub.data(), (int)pub.length(), (PBYTE)sig.data(), (int)sig.length())) { + p->state = 0; p->time = 0; + null_msg(context, 0x00, -type); // сессия разорвана по ошибке + return 0; + } + init_pub(p, pub); } - init_pub(p,pub); - } - if ( type == 0x0D ) { // нужно отправить мой паблик - inject_msg(context,0xD0,tlv(0,features)+tlv(1,r->pub_k)+tlv(2,p->pub_s)); - } - p->state=0; p->time=0; - } break; + if (type == 0x0D) // нужно отправить мой паблик + inject_msg(context, 0xD0, tlv(0, features) + tlv(1, r->pub_k) + tlv(2, p->pub_s)); + p->state = 0; p->time = 0; + } + break; } - if ( p->state != 0 && p->state != 7 ) + if (p->state != 0 && p->state != 7) p->time = gettime() + timeout; return 1; } - -void rsa_alloc( pCNTX ptr ) { +void rsa_alloc(pCNTX ptr) +{ pRSADATA p = new RSADATA; p->state = 0; p->time = 0; p->thread = p->event = NULL; p->thread_exit = 0; p->queue = new STRINGQUEUE; - ptr->pdata = (PBYTE) p; + ptr->pdata = (PBYTE)p; } - -void rsa_free( pCNTX ptr ) { - pRSADATA p = (pRSADATA) ptr->pdata; +int rsa_free(pCNTX ptr) +{ + pRSADATA p = (pRSADATA)ptr->pdata; if (p == NULL) - return; + return true; if (p->event) { p->thread_exit = 2; // отпускаем поток в свободное плавание - SetEvent( p->event ); + SetEvent(p->event); + return false; } - + delete p->queue; delete p; ptr->pdata = NULL; + return true; } -void rsa_free_thread( pRSADATA p ) { - if ( p->event ) { +void rsa_free_thread(pRSADATA p) +{ + if (p->event) { p->thread_exit = 1; - SetEvent( p->event ); + SetEvent(p->event); // ждем завершения потока WaitForSingleObject(p->thread, INFINITE); - CloseHandle( p->thread ); - CloseHandle( p->event ); + CloseHandle(p->thread); + CloseHandle(p->event); p->thread = p->event = NULL; p->thread_exit = 0; } p->time = 0; - clear_queue( p ); + clear_queue(p); } - -void clear_queue( pRSADATA p ) { - EnterCriticalSection(&localQueueMutex); - while( p->queue && !p->queue->empty() ) { - p->queue->pop(); - } - LeaveCriticalSection(&localQueueMutex); +void clear_queue(pRSADATA p) +{ + mir_cslock lck(localQueueMutex); + while (p->queue && !p->queue->empty()) + p->queue->pop(); } - // establish RSA/AES thread -unsigned __stdcall sttConnectThread( LPVOID arg ) { +unsigned __stdcall sttConnectThread(LPVOID arg) +{ + HANDLE context = (HANDLE)arg; - HANDLE context = (HANDLE) arg; + pCNTX ptr = get_context_on_id(context); + if (!ptr) + return 0; - pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); - while(1) { + while (true) { #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("sttConnectThread: WaitForSingleObject"); #endif WaitForSingleObject(p->event, INFINITE); // dwMsec rc==WAIT_TIMEOUT - if ( p->thread_exit == 1 ) return 0; - if ( p->thread_exit == 2 ) { + if (p->thread_exit == 1) return 0; + if (p->thread_exit == 2) { // мы в свободном плавании - освободим память и завершим трэд CloseHandle(p->thread); CloseHandle(p->event); @@ -923,46 +918,48 @@ unsigned __stdcall sttConnectThread( LPVOID arg ) { SAFE_DELETE(p); return 0; } + // дождались сообщения в очереди - while( !p->thread_exit && p->queue && !p->queue->empty() ) { + while (!p->thread_exit && p->queue && !p->queue->empty()) { // обработаем сообщения из очереди - if ( rsa_recv_thread(context, p->queue->front()) == -1 ) { + if (rsa_recv_thread(context, p->queue->front()) == -1) { // очистить очередь clear_queue(p); break; } - EnterCriticalSection(&localQueueMutex); + + mir_cslock lck(localQueueMutex); p->queue->pop(); - LeaveCriticalSection(&localQueueMutex); } } } - -int __cdecl rsa_export_keypair(short mode, LPSTR privKey, LPSTR pubKey, LPSTR passPhrase) { +int __cdecl rsa_export_keypair(short mode, LPSTR privKey, LPSTR pubKey, LPSTR passPhrase) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_export_keypair: %d", mode); #endif + pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0; - pRSAPRIV r = (pRSAPRIV) ptr->pdata; + pRSAPRIV r = (pRSAPRIV)ptr->pdata; - if ( pubKey ) { + if (pubKey) { string pub; - pub = tlv(3,r->pub_k) + tlv(4,r->pub_s); - pub = pub_beg + crlf + add_delim(base64encode(pub),crlf,65) + pub_end + crlf; + pub = tlv(3, r->pub_k) + tlv(4, r->pub_s); + pub = pub_beg + crlf + add_delim(base64encode(pub), crlf, 65) + pub_end + crlf; strcpy(pubKey, pub.c_str()); } - if ( privKey && passPhrase ) { + if (privKey && passPhrase) { string key = hash256(passPhrase); string iv = hash256(key); string priv = pad256(r->priv_k); string ciphered; try { - CBC_Mode::Encryption enc((PBYTE)key.data(),key.length(),(PBYTE)iv.data()); - StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered)); - cbcEncryptor.Put((PBYTE)priv.data(),priv.length()); + CBC_Mode::Encryption enc((PBYTE)key.data(), key.length(), (PBYTE)iv.data()); + StreamTransformationFilter cbcEncryptor(enc, new StringSink(ciphered)); + cbcEncryptor.Put((PBYTE)priv.data(), priv.length()); cbcEncryptor.MessageEnd(); } catch (...) { @@ -971,9 +968,9 @@ int __cdecl rsa_export_keypair(short mode, LPSTR privKey, LPSTR pubKey, LPSTR pa #endif return 0; } - - priv = tlv(1,ciphered) + tlv(2,::hash(ciphered)); - priv = priv_beg + crlf + add_delim(base64encode(priv),crlf,65) + priv_end + crlf; + + priv = tlv(1, ciphered) + tlv(2, ::hash(ciphered)); + priv = priv_beg + crlf + add_delim(base64encode(priv), crlf, 65) + priv_end + crlf; strcpy(privKey, priv.c_str()); } @@ -981,28 +978,29 @@ int __cdecl rsa_export_keypair(short mode, LPSTR privKey, LPSTR pubKey, LPSTR pa return 1; } +int __cdecl rsa_import_keypair(short mode, LPSTR privKey, LPSTR passPhrase) +{ + if (!passPhrase) + return 0; -int __cdecl rsa_import_keypair(short mode, LPSTR privKey, LPSTR passPhrase) { #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_import_keypair: %d", mode); #endif pCNTX ptr = get_context_on_id(hRSA4096); if (!ptr) return 0; - pRSAPRIV r = (pRSAPRIV) ptr->pdata; - - if ( !passPhrase ) return 0; + pRSAPRIV r = (pRSAPRIV)ptr->pdata; string priv; priv.assign(privKey); - del_delim(priv,crlf); + del_delim(priv, crlf); size_t found = priv.find(priv_beg); - if ( found != string::npos ) { - priv = priv.substr(found+priv_beg.length()); + if (found != string::npos) { + priv = priv.substr(found + priv_beg.length()); found = priv.find(priv_end); - if ( found != string::npos ) { - priv = base64decode(priv.substr(0,found)); + if (found != string::npos) { + priv = base64decode(priv.substr(0, found)); TLV k(priv); - if ( k.exist(1) && k.exist(2) && ::hash(k.get(1)) == k.get(2) ) { + if (k.exist(1) && k.exist(2) && ::hash(k.get(1)) == k.get(2)) { priv = k.get(1); string key = hash256(passPhrase); @@ -1010,19 +1008,19 @@ int __cdecl rsa_import_keypair(short mode, LPSTR privKey, LPSTR passPhrase) { string unciphered; try { - CBC_Mode::Decryption dec((PBYTE)key.data(),key.length(),(PBYTE)iv.data()); - StreamTransformationFilter cbcDecryptor(dec,new StringSink(unciphered)); - cbcDecryptor.Put((PBYTE)priv.data(),priv.length()); + CBC_Mode::Decryption dec((PBYTE)key.data(), key.length(), (PBYTE)iv.data()); + StreamTransformationFilter cbcDecryptor(dec, new StringSink(unciphered)); + cbcDecryptor.Put((PBYTE)priv.data(), priv.length()); cbcDecryptor.MessageEnd(); } - catch (...) { + catch (...) { #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_import_keypair: error bad_passphrase"); #endif return 0; } - init_priv(r,unciphered); + init_priv(r, unciphered); return 1; } } @@ -1031,52 +1029,50 @@ int __cdecl rsa_import_keypair(short mode, LPSTR privKey, LPSTR passPhrase) { return 0; } - -int __cdecl rsa_export_pubkey(HANDLE context, LPSTR pubKey) { +int __cdecl rsa_export_pubkey(HANDLE context, LPSTR pubKey) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_export_pubkey: %08x", context); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); - - if ( !p->pub_k.length() || !pubKey ) return 0; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); + if (!p->pub_k.length() || !pubKey) + return 0; string pub; - pub = tlv(3,p->pub_k) + tlv(4,p->pub_s); - pub = pub_beg + crlf + add_delim(base64encode(pub),crlf,65) + pub_end + crlf; + pub = tlv(3, p->pub_k) + tlv(4, p->pub_s); + pub = pub_beg + crlf + add_delim(base64encode(pub), crlf, 65) + pub_end + crlf; strcpy(pubKey, pub.c_str()); return 1; } - -int __cdecl rsa_import_pubkey(HANDLE context, LPSTR pubKey) { +int __cdecl rsa_import_pubkey(HANDLE context, LPSTR pubKey) +{ #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("rsa_import_pubkey: %08x", context); #endif pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - pRSADATA p = (pRSADATA) cpp_alloc_pdata(ptr); - - if ( !pubKey ) return 0; + pRSADATA p = (pRSADATA)cpp_alloc_pdata(ptr); + if (!pubKey) + return 0; string pub; pub.assign(pubKey); - del_delim(pub,crlf); + del_delim(pub, crlf); size_t found = pub.find(pub_beg); - if ( found != string::npos ) { - pub = pub.substr(found+pub_beg.length()); + if (found != string::npos) { + pub = pub.substr(found + pub_beg.length()); found = pub.find(pub_end); - if ( found != string::npos ) { - pub = base64decode(pub.substr(0,found)); + if (found != string::npos) { + pub = base64decode(pub.substr(0, found)); TLV k(pub); - if ( k.exist(3) && k.exist(4) && ::hash(k.get(3)) == k.get(4) ) { - init_pub(p,k.get(3)); + if (k.exist(3) && k.exist(4) && ::hash(k.get(3)) == k.get(4)) { + init_pub(p, k.get(3)); return 1; } - } - } + } + } return 0; } - -// EOF diff --git a/plugins/CryptoPP/src/cpp_rsam.h b/plugins/CryptoPP/src/cpp_rsam.h index 92c1143212..7ffdbe1579 100644 --- a/plugins/CryptoPP/src/cpp_rsam.h +++ b/plugins/CryptoPP/src/cpp_rsam.h @@ -35,7 +35,7 @@ void null_msg(HANDLE,int,int); void rsa_timeout(HANDLE,pRSADATA); void rsa_alloc(pCNTX); -void rsa_free(pCNTX); +int rsa_free(pCNTX); void rsa_free_thread(pRSADATA); void clear_queue(pRSADATA); diff --git a/plugins/CryptoPP/src/cpp_rsau.cpp b/plugins/CryptoPP/src/cpp_rsau.cpp index e9ad825dd0..b0913219fa 100644 --- a/plugins/CryptoPP/src/cpp_rsau.cpp +++ b/plugins/CryptoPP/src/cpp_rsau.cpp @@ -2,39 +2,41 @@ const string padding = "PADDING!PADDING!PADDING!PADDING!"; // 256 bit - -string pad256(string& str) { +string pad256(string& str) +{ string out = str; int pad = out.length() % 32; - if ( pad ) { // ­ ¤® ўла®ў­пвм ­  256 ЎЁв - if ( pad>3 ) { - out += tlv(0,padding.substr(0,32-3-pad)); - } - else { - if ( pad==3 ) out += string("\0\0\0"); - else - if ( pad==2 ) out += string("\0\0"); - else out += string("\0"); - } + if (pad) { // ­ ¤® ўла®ў­пвм ­  256 ЎЁв + if (pad > 3) { + out += tlv(0, padding.substr(0, 32 - 3 - pad)); + } + else { + if (pad == 3) out += string("\0\0\0"); + else + if (pad == 2) out += string("\0\0"); + else out += string("\0"); + } } return out; } -string& add_delim(string& str, const string& del, int len) { +string& add_delim(string& str, const string& del, int len) +{ string val; - for ( u_int i=0; i 3 ) { + if (b.length() > 3) { t = 0; - b.copy((char*)&t,3); - u_int l = t>>8; + b.copy((char*)&t, 3); + u_int l = t >> 8; t &= 0xFF; - if ( b.length() >= 3+l ) { - v = b.substr(3,l); - r = b.substr(3+l); + if (b.length() >= 3 + l) { + v = b.substr(3, l); + r = b.substr(3 + l); } } - if ( !v.length() ) { + if (!v.length()) { t = -1; } b = r; return b; } - -string& un_tlv(string& b, int& t, int& v) { +string& un_tlv(string& b, int& t, int& v) +{ string s; - un_tlv(b,t,s); + un_tlv(b, t, s); v = 0; - s.copy((char*)&v,s.length()); + s.copy((char*)&v, s.length()); return b; } - -int str2int(string& s) { +int str2int(string& s) +{ int v = 0; - if ( s.length()<=sizeof(int) ) - s.copy((char*)&v,s.length()); + if (s.length() <= sizeof(int)) + s.copy((char*)&v, s.length()); return v; } - string hash(string& b) { - return ::hash((PBYTE)b.data(),b.length()); + return ::hash((PBYTE)b.data(), b.length()); } - string hash(PBYTE b, int l) { BYTE h[RSA_KEYSIZE]; RSA_CalculateDigest(h, b, l); - string s; s.assign((char*)&h,RSA_KEYSIZE); + string s; s.assign((char*)&h, RSA_KEYSIZE); return s; } - string hash128(string& b) { - return hash128((PBYTE)b.data(),b.length()); + return hash128((PBYTE)b.data(), b.length()); } - string hash128(LPSTR b) { - return hash128((PBYTE)b,strlen(b)); + return hash128((PBYTE)b, strlen(b)); } - string hash128(PBYTE b, int l) { BYTE h[RIPEMD128::DIGESTSIZE]; RIPEMD128().CalculateDigest(h, b, l); - string s; s.assign((char*)&h,sizeof(h)); + string s; s.assign((char*)&h, sizeof(h)); return s; } - string hash256(string& b) { - return hash256((PBYTE)b.data(),b.length()); + return hash256((PBYTE)b.data(), b.length()); } - string hash256(LPSTR b) { - return hash256((PBYTE)b,strlen(b)); + return hash256((PBYTE)b, strlen(b)); } - string hash256(PBYTE b, int l) { -// BYTE h[SHA256::DIGESTSIZE]; -// SHA256().CalculateDigest(h, b, l); BYTE h[RIPEMD256::DIGESTSIZE]; RIPEMD256().CalculateDigest(h, b, l); - string s; s.assign((char*)&h,sizeof(h)); + string s; s.assign((char*)&h, sizeof(h)); return s; } - Integer BinaryToInteger(const string& data) { - StringSource ss(data, true, NULL); - SecByteBlock result(ss.MaxRetrievable()); - ss.Get(result, result.size()); - return Integer(result, result.size()); + StringSource ss(data, true, NULL); + SecByteBlock result(ss.MaxRetrievable()); + ss.Get(result, result.size()); + return Integer(result, result.size()); } - string IntegerToBinary(const Integer& value) { - SecByteBlock sbb(value.MinEncodedSize()); - value.Encode(sbb, sbb.size()); - string data; - StringSource(sbb, sbb.size(), true, new StringSink(data)); - return data; + SecByteBlock sbb(value.MinEncodedSize()); + value.Encode(sbb, sbb.size()); + string data; + StringSource(sbb, sbb.size(), true, new StringSink(data)); + return data; } -/* -RandomPool& GlobalRNG() -{ - static RandomPool randomPool; - return randomPool; -} -*/ - AutoSeededRandomPool& GlobalRNG() { static AutoSeededRandomPool randomPool; return randomPool; } - void GenerateRSAKey(unsigned int keyLength, string& privKey, string& pubKey) { RSAES_PKCS1v15_Decryptor priv(GlobalRNG(), keyLength); @@ -206,7 +191,6 @@ void GenerateRSAKey(unsigned int keyLength, string& privKey, string& pubKey) pubFile.MessageEnd(); } - string RSAEncryptString(const RSA::PublicKey& pubkey, const string& plaintext) { RSAES_PKCS1v15_Encryptor pub(pubkey); @@ -216,7 +200,6 @@ string RSAEncryptString(const RSA::PublicKey& pubkey, const string& plaintext) return result; } - string RSADecryptString(const RSA::PrivateKey& privkey, const string& ciphertext) { RSAES_PKCS1v15_Decryptor priv(privkey); @@ -225,13 +208,12 @@ string RSADecryptString(const RSA::PrivateKey& privkey, const string& ciphertext try { StringSource(ciphertext, true, new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))); } - catch (...) { + catch (...) { ; } return result; } - string RSASignString(const RSA::PrivateKey& privkey, const string& plaintext) { RSASSA_PKCS1v15_SHA_Signer priv(privkey); @@ -240,19 +222,15 @@ string RSASignString(const RSA::PrivateKey& privkey, const string& plaintext) try { StringSource(plaintext, true, new SignerFilter(GlobalRNG(), priv, new StringSink(result))); } - catch (...) { + catch (...) { ; } return result; } - BOOL RSAVerifyString(const RSA::PublicKey& pubkey, const string& plaintext, const string& sig) { - RSASSA_PKCS1v15_SHA_Verifier ver(pubkey); + RSASSA_PKCS1v15_SHA_Verifier ver(pubkey); - return ver.VerifyMessage((PBYTE)plaintext.data(), plaintext.length(), (PBYTE)sig.data(), sig.length()); + return ver.VerifyMessage((PBYTE)plaintext.data(), plaintext.length(), (PBYTE)sig.data(), sig.length()); } - - -// EOF diff --git a/plugins/CryptoPP/src/cpp_svcs.cpp b/plugins/CryptoPP/src/cpp_svcs.cpp index 07b4030633..01b95bc2d9 100644 --- a/plugins/CryptoPP/src/cpp_svcs.cpp +++ b/plugins/CryptoPP/src/cpp_svcs.cpp @@ -2,12 +2,11 @@ const unsigned char IV[] = "SIMhell@MIRANDA!"; - // encrypt string using KeyX, return encoded string as ASCII or NULL LPSTR __cdecl cpp_encrypt(pCNTX ptr, LPCSTR szPlainMsg) { ptr->error = ERROR_NONE; - pSIMDATA p = (pSIMDATA) ptr->pdata; + pSIMDATA p = (pSIMDATA)ptr->pdata; BYTE dataflag = 0; size_t slen = strlen(szPlainMsg); @@ -15,8 +14,8 @@ LPSTR __cdecl cpp_encrypt(pCNTX ptr, LPCSTR szPlainMsg) LPSTR szMsg; if (ptr->features & FEATURES_GZIP) { size_t clen; - szMsg = (LPSTR) cpp_gzip((BYTE*)szPlainMsg,slen,clen); - if (clen>=slen) { + szMsg = (LPSTR)cpp_gzip((BYTE*)szPlainMsg, slen, clen); + if (clen >= slen) { free(szMsg); szMsg = _strdup(szPlainMsg); } @@ -29,8 +28,8 @@ LPSTR __cdecl cpp_encrypt(pCNTX ptr, LPCSTR szPlainMsg) string ciphered; - CBC_Mode::Encryption enc(p->KeyX,Tiger::DIGESTSIZE,IV); - StreamTransformationFilter cbcEncryptor(enc,new StringSink(ciphered)); + CBC_Mode::Encryption enc(p->KeyX, Tiger::DIGESTSIZE, IV); + StreamTransformationFilter cbcEncryptor(enc, new StringSink(ciphered)); cbcEncryptor.Put((PBYTE)szMsg, slen); cbcEncryptor.MessageEnd(); @@ -40,14 +39,14 @@ LPSTR __cdecl cpp_encrypt(pCNTX ptr, LPCSTR szPlainMsg) unsigned clen = (unsigned)ciphered.length(); if (ptr->features & FEATURES_CRC32) { BYTE crc32[CRC32::DIGESTSIZE]; - memset(crc32,0,sizeof(crc32)); + memset(crc32, 0, sizeof(crc32)); CRC32().CalculateDigest(crc32, (BYTE*)ciphered.data(), clen); - ciphered.insert(0,(LPSTR)&crc32,CRC32::DIGESTSIZE); - ciphered.insert(0,(LPSTR)&clen,2); + ciphered.insert(0, (LPSTR)&crc32, CRC32::DIGESTSIZE); + ciphered.insert(0, (LPSTR)&clen, 2); } if (ptr->features & FEATURES_GZIP) - ciphered.insert(0,(LPSTR)&dataflag,1); - + ciphered.insert(0, (LPSTR)&dataflag, 1); + clen = (unsigned)ciphered.length(); if (ptr->features & FEATURES_BASE64) replaceStr(ptr->tmp, mir_base64_encode((PBYTE)ciphered.data(), clen)); @@ -65,25 +64,25 @@ LPSTR __cdecl cpp_decrypt(pCNTX ptr, LPCSTR szEncMsg) try { ptr->error = ERROR_SEH; - pSIMDATA p = (pSIMDATA) ptr->pdata; + pSIMDATA p = (pSIMDATA)ptr->pdata; unsigned clen = (unsigned)strlen(szEncMsg); if (ptr->features & FEATURES_BASE64) - ciphered = (LPSTR)mir_base64_decode(szEncMsg,&clen); + ciphered = (LPSTR)mir_base64_decode(szEncMsg, &clen); else - ciphered = base16decode(szEncMsg,&clen); + ciphered = base16decode(szEncMsg, &clen); LPSTR bciphered = ciphered; - BYTE dataflag=0; + BYTE dataflag = 0; if (ptr->features & FEATURES_GZIP) { dataflag = *ciphered; bciphered++; clen--; // cut GZIP flag } if (ptr->features & FEATURES_CRC32) { - int len = *( WORD* )bciphered; - bciphered+=2; clen-=2; // cut CRC32 length + int len = *(WORD*)bciphered; + bciphered += 2; clen -= 2; // cut CRC32 length if ((int)clen - CRC32::DIGESTSIZE < len) { // mesage not full #if defined(_DEBUG) || defined(NETLIB_LOG) @@ -94,11 +93,11 @@ LPSTR __cdecl cpp_decrypt(pCNTX ptr, LPCSTR szEncMsg) } BYTE crc32[CRC32::DIGESTSIZE]; - memset(crc32,0,sizeof(crc32)); + memset(crc32, 0, sizeof(crc32)); - CRC32().CalculateDigest(crc32, (PBYTE)(bciphered+CRC32::DIGESTSIZE), len); + CRC32().CalculateDigest(crc32, (PBYTE)(bciphered + CRC32::DIGESTSIZE), len); - if (memcmp(crc32,bciphered,CRC32::DIGESTSIZE)) { // message is bad crc + if (memcmp(crc32, bciphered, CRC32::DIGESTSIZE)) { // message is bad crc #if defined(_DEBUG) || defined(NETLIB_LOG) Sent_NetLog("cpp_decrypt: error bad_crc"); #endif @@ -111,15 +110,15 @@ LPSTR __cdecl cpp_decrypt(pCNTX ptr, LPCSTR szEncMsg) string unciphered; - CBC_Mode::Decryption dec(p->KeyX,Tiger::DIGESTSIZE,IV); - StreamTransformationFilter cbcDecryptor(dec,new StringSink(unciphered)); + CBC_Mode::Decryption dec(p->KeyX, Tiger::DIGESTSIZE, IV); + StreamTransformationFilter cbcDecryptor(dec, new StringSink(unciphered)); - cbcDecryptor.Put((PBYTE)bciphered,clen); + cbcDecryptor.Put((PBYTE)bciphered, clen); cbcDecryptor.MessageEnd(); if (dataflag & DATA_GZIP) { size_t clen2 = clen; - LPSTR res = (LPSTR)cpp_gunzip((PBYTE)unciphered.data(),unciphered.length(),clen2); + LPSTR res = (LPSTR)cpp_gunzip((PBYTE)unciphered.data(), unciphered.length(), clen2); replaceStr(ptr->tmp, mir_strndup(res, clen2)); free(res); } @@ -143,16 +142,16 @@ LPSTR __cdecl cpp_encodeA(HANDLE context, LPCSTR msg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) { ptr->error = ERROR_NO_KEYX; return NULL; } LPSTR szNewMsg = NULL; - LPSTR szOldMsg = (LPSTR) msg; + LPSTR szOldMsg = (LPSTR)msg; if (ptr->features & FEATURES_UTF8) { // ansi message: convert to unicode->utf-8 and encrypt. - int slen = (int)strlen(szOldMsg)+1; - LPWSTR wstring = (LPWSTR) alloca(slen*sizeof(WCHAR)); + int slen = (int)strlen(szOldMsg) + 1; + LPWSTR wstring = (LPWSTR)alloca(slen*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, szOldMsg, -1, wstring, slen*sizeof(WCHAR)); // encrypt szNewMsg = cpp_encrypt(ptr, utf8encode(wstring)); @@ -171,11 +170,11 @@ LPSTR __cdecl cpp_encodeU(HANDLE context, LPCSTR msg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) { ptr->error = ERROR_NO_KEYX; return NULL; } LPSTR szNewMsg = NULL; - LPSTR szOldMsg = (LPSTR) msg; + LPSTR szOldMsg = (LPSTR)msg; if (ptr->features & FEATURES_UTF8) { // utf8 message: encrypt. @@ -184,8 +183,8 @@ LPSTR __cdecl cpp_encodeU(HANDLE context, LPCSTR msg) else { // utf8 message: convert to ansi and encrypt. LPWSTR wstring = utf8decode(szOldMsg); - int wlen = (int)wcslen(wstring)+1; - LPSTR astring = (LPSTR) alloca(wlen); + int wlen = (int)wcslen(wstring) + 1; + LPSTR astring = (LPSTR)alloca(wlen); WideCharToMultiByte(CP_ACP, 0, (LPWSTR)szOldMsg, -1, astring, wlen, 0, 0); szNewMsg = cpp_encrypt(ptr, astring); } @@ -198,11 +197,11 @@ LPSTR __cdecl cpp_encodeW(HANDLE context, LPWSTR msg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) { ptr->error = ERROR_NO_KEYX; return NULL; } LPSTR szNewMsg = NULL; - LPSTR szOldMsg = (LPSTR) msg; + LPSTR szOldMsg = (LPSTR)msg; if (ptr->features & FEATURES_UTF8) { // unicode message: convert to utf-8 and encrypt. @@ -210,8 +209,8 @@ LPSTR __cdecl cpp_encodeW(HANDLE context, LPWSTR msg) } else { // unicode message: convert to ansi and encrypt. - int wlen = (int)wcslen((LPWSTR)szOldMsg)+1; - LPSTR astring = (LPSTR) alloca(wlen); + int wlen = (int)wcslen((LPWSTR)szOldMsg) + 1; + LPSTR astring = (LPSTR)alloca(wlen); WideCharToMultiByte(CP_ACP, 0, (LPWSTR)szOldMsg, -1, astring, wlen, 0, 0); szNewMsg = cpp_encrypt(ptr, astring); } @@ -225,7 +224,7 @@ LPSTR __cdecl cpp_decode(HANDLE context, LPCSTR szEncMsg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) { ptr->error = ERROR_NO_KEYX; return NULL; } LPSTR szNewMsg = NULL; @@ -235,19 +234,19 @@ LPSTR __cdecl cpp_decode(HANDLE context, LPCSTR szEncMsg) if (ptr->features & FEATURES_UTF8) { // utf8 message: convert to unicode -> ansii LPWSTR wstring = utf8decode(szOldMsg); - int wlen = (int)wcslen(wstring)+1; + int wlen = (int)wcslen(wstring) + 1; szNewMsg = (LPSTR)mir_alloc(wlen*(sizeof(WCHAR)+2)); // work.zy@gmail.com WideCharToMultiByte(CP_ACP, 0, wstring, -1, szNewMsg, wlen, 0, 0); - memcpy(szNewMsg+strlen(szNewMsg)+1, wstring, wlen*sizeof(WCHAR)); // work.zy@gmail.com + memcpy(szNewMsg + strlen(szNewMsg) + 1, wstring, wlen*sizeof(WCHAR)); // work.zy@gmail.com } else { // ansi message: convert to unicode - int slen = (int)strlen(szOldMsg)+1; + int slen = (int)strlen(szOldMsg) + 1; szNewMsg = (LPSTR)mir_alloc(slen*(sizeof(WCHAR)+1)); - memcpy(szNewMsg,szOldMsg,slen); - WCHAR* wstring = (LPWSTR) alloca(slen*sizeof(WCHAR)); + memcpy(szNewMsg, szOldMsg, slen); + WCHAR* wstring = (LPWSTR)alloca(slen*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, szOldMsg, -1, wstring, slen*sizeof(WCHAR)); - memcpy(szNewMsg+slen,wstring,slen*sizeof(WCHAR)); + memcpy(szNewMsg + slen, wstring, slen*sizeof(WCHAR)); } } replaceStr(ptr->tmp, szNewMsg); @@ -259,7 +258,7 @@ LPSTR __cdecl cpp_decodeU(HANDLE context, LPCSTR szEncMsg) { pCNTX ptr = get_context_on_id(context); if (!ptr) return NULL; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) { ptr->error = ERROR_NO_KEYX; return NULL; } LPSTR szNewMsg = NULL; @@ -272,8 +271,8 @@ LPSTR __cdecl cpp_decodeU(HANDLE context, LPCSTR szEncMsg) } else { // ansi message: convert to utf8 - int slen = (int)strlen(szOldMsg)+1; - LPWSTR wstring = (LPWSTR) alloca(slen*sizeof(WCHAR)); + int slen = (int)strlen(szOldMsg) + 1; + LPWSTR wstring = (LPWSTR)alloca(slen*sizeof(WCHAR)); MultiByteToWideChar(CP_ACP, 0, szOldMsg, -1, wstring, slen*sizeof(WCHAR)); szNewMsg = mir_strdup(utf8encode(wstring)); } @@ -282,16 +281,16 @@ LPSTR __cdecl cpp_decodeU(HANDLE context, LPCSTR szEncMsg) return szNewMsg; } -int __cdecl cpp_encrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) +int __cdecl cpp_encrypt_file(HANDLE context, LPCSTR file_in, LPCSTR file_out) { pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) return 0; - try{ - CBC_Mode::Encryption enc(p->KeyX,Tiger::DIGESTSIZE,IV); - FileSource *f = new FileSource(file_in,true,new StreamTransformationFilter (enc,new FileSink(file_out))); + try { + CBC_Mode::Encryption enc(p->KeyX, Tiger::DIGESTSIZE, IV); + FileSource *f = new FileSource(file_in, true, new StreamTransformationFilter(enc, new FileSink(file_out))); delete f; } catch (...) { @@ -300,16 +299,16 @@ int __cdecl cpp_encrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) return 1; } -int __cdecl cpp_decrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) +int __cdecl cpp_decrypt_file(HANDLE context, LPCSTR file_in, LPCSTR file_out) { pCNTX ptr = get_context_on_id(context); if (!ptr) return 0; - cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA) ptr->pdata; + cpp_alloc_pdata(ptr); pSIMDATA p = (pSIMDATA)ptr->pdata; if (!p->KeyX) return 0; - try{ - CBC_Mode::Decryption dec(p->KeyX,Tiger::DIGESTSIZE,IV); - FileSource *f = new FileSource(file_in,true,new StreamTransformationFilter (dec,new FileSink(file_out))); + try { + CBC_Mode::Decryption dec(p->KeyX, Tiger::DIGESTSIZE, IV); + FileSource *f = new FileSource(file_in, true, new StreamTransformationFilter(dec, new FileSink(file_out))); delete f; } catch (...) { @@ -317,6 +316,3 @@ int __cdecl cpp_decrypt_file(HANDLE context,LPCSTR file_in,LPCSTR file_out) } return 1; } - - -// EOF diff --git a/plugins/CryptoPP/src/dllloader.cpp b/plugins/CryptoPP/src/dllloader.cpp deleted file mode 100644 index 160e5d98c4..0000000000 --- a/plugins/CryptoPP/src/dllloader.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/* -* Loading dll from memory -* -* Written by Vitaliy Shitts (vit@shittz.ru) -* Copyright (c) 2004 Vitaliy Shittz. -* -* THIS CODE IS PROVIDED "AS IS". NO WARRANTY OF ANY KIND IS EXPRESSED -* OR IMPLIED. YOU USE AT YOUR OWN RISK. THE AUTHOR ACCEPTS NO LIABILITY -* IF IT CAUSES ANY DAMAGE TO YOU OR YOUR COMPUTER WHATSOEVER. -* -* Beware of bugs. -*/ - -#include "commonheaders.h" - -#ifdef DLL_FROM_RESOURCE - -#ifndef MIN -# define MIN(a,b) ((a)<(b)?(a):(b)) -#endif - -typedef BOOL (WINAPI *DLLMAIN)(HINSTANCE,DWORD,LPVOID); - -#pragma warning (push) -#pragma warning (disable: 4311; disable: 4312; disable: 4018) - -DWORD GetSectionProtection(DWORD sc) -{ - DWORD dwResult=0; - if (sc & IMAGE_SCN_MEM_NOT_CACHED) - dwResult |= PAGE_NOCACHE; - - if (sc & IMAGE_SCN_MEM_EXECUTE) - { - if (sc & IMAGE_SCN_MEM_READ) - { - if (sc & IMAGE_SCN_MEM_WRITE) - dwResult |= PAGE_EXECUTE_READWRITE; - else - dwResult |= PAGE_EXECUTE_READ; - } - else - { - if (sc & IMAGE_SCN_MEM_WRITE) - dwResult |= PAGE_EXECUTE_WRITECOPY; - else - dwResult |= PAGE_EXECUTE; - } - } - else - { - if (sc & IMAGE_SCN_MEM_READ) - { - if (sc & IMAGE_SCN_MEM_WRITE) - dwResult|=PAGE_READWRITE; - else - dwResult|=PAGE_READONLY; - } - else - { - if (sc & IMAGE_SCN_MEM_WRITE) - dwResult|=PAGE_WRITECOPY; - else - dwResult|=PAGE_NOACCESS; - } - } - - return dwResult; -} - -inline BOOL IsImportByOrdinal(DWORD ImportDescriptor) -{ - return (ImportDescriptor & IMAGE_ORDINAL_FLAG32)!=0; -} - - -HMODULE MemLoadLibrary(PBYTE data) -{ - IMAGE_FILE_HEADER *pFileHeader = NULL; - IMAGE_OPTIONAL_HEADER *pOptionalHeader = NULL; - IMAGE_SECTION_HEADER *pSectionHeader = NULL; - IMAGE_IMPORT_DESCRIPTOR *pImportDscrtr = NULL; - USHORT e_lfanew = *((USHORT*)(data+0x3c)); - PCHAR ImageBase = NULL; - PCHAR SectionBase = NULL; - - DWORD dwSize, dwOldProt, ImageBaseDelta; - int i; - - pFileHeader = (IMAGE_FILE_HEADER *)(data+e_lfanew+4); - pOptionalHeader = (IMAGE_OPTIONAL_HEADER *)(data+e_lfanew+4+sizeof(IMAGE_FILE_HEADER)); - if (pOptionalHeader->Magic!=IMAGE_NT_OPTIONAL_HDR32_MAGIC) - return NULL; - - // Let's try to reserv memory - ImageBase = (PCHAR)VirtualAlloc( - (PVOID)pOptionalHeader->ImageBase, - pOptionalHeader->SizeOfImage, - MEM_RESERVE,PAGE_NOACCESS); - - if (ImageBase==NULL) - { - ImageBase=(PCHAR)VirtualAlloc(NULL, - pOptionalHeader->SizeOfImage, - MEM_RESERVE,PAGE_NOACCESS); - if (ImageBase==NULL) - return NULL; - } - - // copy the header - SectionBase=(PCHAR)VirtualAlloc(ImageBase, - pOptionalHeader->SizeOfHeaders, - MEM_COMMIT,PAGE_READWRITE); - memcpy(SectionBase,data,pOptionalHeader->SizeOfHeaders); - // Do headers read-only (to be on the safe side) - VirtualProtect(SectionBase,pOptionalHeader->SizeOfHeaders,PAGE_READONLY,&dwOldProt); - - // find sections ... - pSectionHeader = (IMAGE_SECTION_HEADER *)(pOptionalHeader+1); - for (i=0; iNumberOfSections; i++) - { - SectionBase = (PCHAR)VirtualAlloc( - ImageBase+pSectionHeader[i].VirtualAddress, - pSectionHeader[i].Misc.VirtualSize, - MEM_COMMIT,PAGE_READWRITE); - if (SectionBase==NULL) - { - VirtualFree(ImageBase, 0, MEM_RELEASE); - return NULL; - } - // ... and copy initialization data - SectionBase = ImageBase+pSectionHeader[i].VirtualAddress; - dwSize = MIN(pSectionHeader[i].SizeOfRawData,pSectionHeader[i].Misc.VirtualSize); - memcpy(SectionBase, data+pSectionHeader[i].PointerToRawData,dwSize); - } - - // check addersses - ImageBaseDelta = (DWORD)ImageBase-pOptionalHeader->ImageBase; - if (ImageBaseDelta!=0 && - pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress!=0 - ) - { - IMAGE_BASE_RELOCATION *pBaseReloc = (IMAGE_BASE_RELOCATION *)(ImageBase+ - pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress); - IMAGE_BASE_RELOCATION *pBaseReloc0 = pBaseReloc; - WORD *wPointer = NULL; - DWORD dwModCount; - int i; - - while ((DWORD)pBaseReloc0-(DWORD)pBaseReloc < pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size) - { - dwModCount = (pBaseReloc0->SizeOfBlock-sizeof(pBaseReloc))/2; - wPointer = (WORD *)(pBaseReloc+1); - for (i=0; iVirtualAddress+((*wPointer)&0xfff)); - (*pdw)+=ImageBaseDelta; - } - pBaseReloc = (IMAGE_BASE_RELOCATION *)wPointer; - } - } - else if (ImageBaseDelta!=0) - { - VirtualFree(ImageBase, 0, MEM_RELEASE); - return NULL; - } - - pImportDscrtr = (IMAGE_IMPORT_DESCRIPTOR *)(ImageBase+ - pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); - - for (;pImportDscrtr->Name!=0; pImportDscrtr++) - { - PCHAR pLibName = (PCHAR)(ImageBase+pImportDscrtr->Name); - PCHAR pImortName = NULL; - HMODULE hLibModule = LoadLibrary(pLibName); - DWORD *pImport = NULL, - *pAddress = NULL; - DWORD ProcAddress; - - pAddress=(DWORD *)(ImageBase+pImportDscrtr->/*Original*/FirstThunk); - if (pImportDscrtr->TimeDateStamp==0) - pImport=(DWORD *)(ImageBase+pImportDscrtr->FirstThunk); - else - pImport=(DWORD *)(ImageBase+pImportDscrtr->OriginalFirstThunk); - for (i=0; pImport[i]!=0; i++) - { - if (IsImportByOrdinal(pImport[i])) - ProcAddress=(DWORD)GetProcAddress(hLibModule, (PCHAR)(pImport[i]&0xFFFF)); - else // import by name - { - pImortName=(PCHAR)(ImageBase+(pImport[i])+2); - ProcAddress=(DWORD)GetProcAddress(hLibModule, pImortName); - } - pAddress[i]=ProcAddress; - } - } - - // set section protection - for (i=0; iNumberOfSections; i++) - VirtualProtect((PVOID)(ImageBase+pSectionHeader[i].VirtualAddress), - pSectionHeader[i].Misc.VirtualSize, - GetSectionProtection(pSectionHeader[i].Characteristics), - &dwOldProt); - - // call DLLMain - if (pOptionalHeader->AddressOfEntryPoint!=0) - { - DLLMAIN dllMain=(DLLMAIN)(ImageBase+pOptionalHeader->AddressOfEntryPoint); - if (!dllMain((HMODULE)ImageBase, DLL_PROCESS_ATTACH, NULL)) - { - VirtualFree(ImageBase, 0, MEM_RELEASE); - return NULL; - } - } - - return (HMODULE)ImageBase; -} - - -BOOL MemFreeLibrary(HMODULE hDll) -{ - PIMAGE_DOS_HEADER pDosHeader = NULL; - PIMAGE_FILE_HEADER pFileHeader = NULL; - PIMAGE_OPTIONAL_HEADER pOptionalHeader = NULL; - - pDosHeader=(PIMAGE_DOS_HEADER)hDll; - pFileHeader=(PIMAGE_FILE_HEADER)(((PBYTE)hDll)+pDosHeader->e_lfanew+4); - pOptionalHeader=(PIMAGE_OPTIONAL_HEADER)(pFileHeader+1); - -// Call to DllMain - if (pOptionalHeader->AddressOfEntryPoint!=0) - { - DLLMAIN dllMain=(DLLMAIN)((PBYTE)hDll+pOptionalHeader->AddressOfEntryPoint); - dllMain(hDll, DLL_PROCESS_DETACH, NULL); - } -// free loaded librares - PIMAGE_IMPORT_DESCRIPTOR pImportDscrtr = (IMAGE_IMPORT_DESCRIPTOR *)((PBYTE)hDll+ - pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress); - for (;pImportDscrtr->Name!=0; pImportDscrtr++) - { - PCHAR pLibName = (PCHAR)((PBYTE)hDll+pImportDscrtr->Name); - HMODULE hLib = GetModuleHandle(pLibName); - FreeLibrary(hLib); - } - - return VirtualFree((PVOID)hDll, 0, MEM_RELEASE); -} - -FARPROC MemGetProcAddress(HMODULE hDll, LPCTSTR fname) -{ - PIMAGE_DOS_HEADER pDosHeader = NULL; - PIMAGE_FILE_HEADER pFileHeader = NULL; - PIMAGE_OPTIONAL_HEADER pOptionalHeader = NULL; - - pDosHeader=(PIMAGE_DOS_HEADER)hDll; - pFileHeader=(PIMAGE_FILE_HEADER)(((PBYTE)hDll)+pDosHeader->e_lfanew+4); - pOptionalHeader=(PIMAGE_OPTIONAL_HEADER)(pFileHeader+1); - - DWORD dwExpRVA = pOptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; - PBYTE pb = (PBYTE)hDll; - PIMAGE_EXPORT_DIRECTORY pExportDir=(PIMAGE_EXPORT_DIRECTORY)(pb+dwExpRVA); - PDWORD pNamesRVA=(PDWORD)(pb+pExportDir->AddressOfNames); - PDWORD pFuncRVA=(PDWORD)(pb+pExportDir->AddressOfFunctions); - PWORD ord=(PWORD)(pb+pExportDir->AddressOfNameOrdinals); - - DWORD dwFunc=pExportDir->NumberOfNames; - for (int i=0; i> 6) &0x3f); + szOut[i++] = 0xc0 | (((*w) >> 6) & 0x3f); szOut[i++] = 0x80 | ((*w) & 0x3f); } else { @@ -43,18 +42,19 @@ LPSTR __cdecl utf8encode(LPCWSTR str) { return szOut; } -LPWSTR __cdecl utf8decode(LPCSTR str) { +LPWSTR __cdecl utf8decode(LPCSTR str) +{ int i, len; LPSTR p; -// LPWSTR wszOut; + // LPWSTR wszOut; if (str == NULL) return NULL; - len = strlen(str)+1; + len = strlen(str) + 1; SAFE_FREE(wszOut); - if ((wszOut = (LPWSTR) malloc(len*sizeof(WCHAR))) == NULL) + if ((wszOut = (LPWSTR)malloc(len*sizeof(WCHAR))) == NULL) return NULL; p = (LPSTR)str; i = 0; @@ -83,9 +83,10 @@ LPWSTR __cdecl utf8decode(LPCSTR str) { // Returns true if the buffer only contains 7-bit characters. -int __cdecl is_7bit_string(LPCSTR str) { - while( *str ) { - if ( *str & 0x80 ) { +int __cdecl is_7bit_string(LPCSTR str) +{ + while (*str) { + if (*str & 0x80) { return FALSE; break; } @@ -98,52 +99,51 @@ int __cdecl is_7bit_string(LPCSTR str) { //Copyright (C) 2001, 2002 Peter Verthez //under GNU LGPL -int __cdecl is_utf8_string(LPCSTR str) { - int expect_bytes = 0; - - if (!str) return 0; - - while (*str) { - if ((*str & 0x80) == 0) { - /* Looks like an ASCII character */ - if (expect_bytes) - /* byte of UTF-8 character expected */ - return 0; - else { - /* OK, ASCII character expected */ - str++; - } - } - else { - /* Looks like byte of an UTF-8 character */ - if (expect_bytes) { - /* expect_bytes already set: first byte of UTF-8 char already seen */ - if ((*str & 0xC0) == 0x80) { - /* OK, next byte of UTF-8 character */ - /* Decrement number of expected bytes */ - expect_bytes--; - str++; +int __cdecl is_utf8_string(LPCSTR str) +{ + int expect_bytes = 0; + + if (!str) return 0; + + while (*str) { + if ((*str & 0x80) == 0) { + /* Looks like an ASCII character */ + if (expect_bytes) + /* byte of UTF-8 character expected */ + return 0; + else { + /* OK, ASCII character expected */ + str++; + } } else { - /* again first byte ?!?! */ - return 0; + /* Looks like byte of an UTF-8 character */ + if (expect_bytes) { + /* expect_bytes already set: first byte of UTF-8 char already seen */ + if ((*str & 0xC0) == 0x80) { + /* OK, next byte of UTF-8 character */ + /* Decrement number of expected bytes */ + expect_bytes--; + str++; + } + else { + /* again first byte ?!?! */ + return 0; + } + } + else { + /* First byte of the UTF-8 character */ + /* count initial one bits and set expect_bytes to 1 less */ + char ch = *str; + while (ch & 0x80) { + expect_bytes++; + ch = (ch & 0x7f) << 1; + } + expect_bytes--; + str++; + } } - } - else { - /* First byte of the UTF-8 character */ - /* count initial one bits and set expect_bytes to 1 less */ - char ch = *str; - while (ch & 0x80) { - expect_bytes++; - ch = (ch & 0x7f) << 1; - } - expect_bytes--; - str++; - } - } - } + } - return (expect_bytes == 0); + return (expect_bytes == 0); } - -// EOF -- cgit v1.2.3