C++ 简单字符串加解密(转载)

本文介绍了一种基于字符异或操作实现的简单字符串加密解密算法。该算法使用密钥循环进行加密,并通过特定标记完成解密过程。文章提供了一个C++实现示例,包括加密与解密函数及主函数演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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;
}

 

转载于:https://www.cnblogs.com/xuandi/p/5855669.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值