zoukankan      html  css  js  c++  java
  • 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] == '')
                            break;
                cPos++;
            }
            if(!cPos)   // 没有找到结束标记,也不是加密
                return;
            nTextLen = cPos - lpszText;
            pDest = new char[nTextLen + 3]; // ==
        }
     
        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("=="), 3 * sizeof(TCHAR));
        else
        {
            memset(pDest  + nTextLen, _T(''), 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;
    }
  • 相关阅读:
    multipath路径残留导致虚拟机无法重启
    multipath配置错误导致的云平台虚拟机挂载云硬盘失败
    kubernetes v1.8.3安装coredns
    helm安装chart----percona-xtradb-cluster实践记录
    elasticsearch性能调优相关
    nova hypervisor-list无法执行,其他api均正常
    珍爱面经
    猫眼面经
    头条面经
    阿里秋招面经
  • 原文地址:https://www.cnblogs.com/xuandi/p/5855669.html
Copyright © 2011-2022 走看看