C++ 简单字符串加解密(转载)
#include <iostream.h> #include <windows.h> #include <tchar.h> void EncodeString(LPCTSTR lpszText, LPTSTR *lpszReturn, LPCTSTR lpszKey) { int nTextLen = 0; char *cPos = NULL; char *pDest = NULL; if(!lpszReturn) // 加密 { nTextLen = ::_tcslen(lpszText); pDest = (LPTSTR)lpszText; } else // 解密 { // 查找自定的中止标记 cPos = (LPTSTR)lpszText; while(true) // 从这里可以看到,除非搜索到我们自定的中止标记,否则会一直搜索下去 { if(*cPos == '=') if(cPos[1] == '=') if(cPos[2] == '\0') break; cPos++; } if(!cPos) // 没有找到结束标记,也不是加密 return; nTextLen = cPos - lpszText; pDest = new char[nTextLen + 3]; // ==\0 } int nKeyLen = ::_tcslen(lpszKey); int i = 0; int k = 0; for(; i < nTextLen; i++) { pDest[i] = lpszText[i] ^ lpszKey[k]; k++; if(k >= nKeyLen) k = 0; } if(!cPos) memcpy(pDest + nTextLen, _T("==\0"), 3 * sizeof(TCHAR)); else { memset(pDest + nTextLen, _T('\0'), sizeof(TCHAR)); *lpszReturn = pDest; } } int main(int argc, char* argv[]) { char strText[] = "Hello world! I'm zimmerk. I'm a boy. What's your name?"; char *lpszDest = NULL; cout<<strText<<endl; cout<<"========================================"<<endl; EncodeString(strText , NULL, "Zimmerk"); // 加密 cout<<strText<<endl; cout<<"========================================"<<endl; EncodeString(strText, &lpszDest, "Zimmerk"); // 解密 if(*lpszDest) { cout<<lpszDest<<endl; delete [] lpszDest; } else cout<<_T("(NULL)")<<endl; return 0; }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步