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;
    }
  • 相关阅读:
    Rotation Kinematics
    离职 mark
    PnP 问题方程怎么列?
    DSO windowed optimization 代码 (4)
    Adjoint of SE(3)
    IMU 预积分推导
    DSO windowed optimization 代码 (3)
    DSO windowed optimization 代码 (2)
    OKVIS 代码框架
    DSO windowed optimization 代码 (1)
  • 原文地址:https://www.cnblogs.com/xuandi/p/5855669.html
Copyright © 2011-2022 走看看