C++ string字符串如何加密

2025-03-06 22:16:13
推荐回答(5个)
回答1:

C++ string类重载了[]运算符,因此,可以象数组一样方便的引用string中的每一个元素,进行数据修改。如,字符串简单加密方法,A-B, B-C, C-D。。。Z-A的实现代码如下:

#include 
#include 
using namespace std ;
int main()
{
    string s;
    cin >> s ; //输入字符串
    for( int i=0;i    {
        if ( s[i] >='A' && s[i] <'Z' ) //处理A-Y
            s[i]+=1;
        else if ( s[i]=='Z' ) //处理Z
            s[i]='A' ;
        //非大写字符,不处理
    }
    cout << s <    return 0;
}
运行结果:
AsDfGXyZ
BsEfHYyA

回答2:

字符串是可以如此加密的,当然在文件里加密字符串还是一样道理的
#include
#include
using namespace std;

void main()
{
string str;
char ch;
int i;
cin >> str;
for (i = 0; i != str.length(); ++i)
{
ch = str.at(i);
if (ch >= 'A' && ch <= 'Y')
{
ch += 1;
str.insert(i, 1, ch);
str.erase(i + 1, 1);
}
else if (ch == 'Z')
{
ch -= 25;
str.insert(i, 1, ch);
str.erase(i + 1, 1);
}
}
cout << str << endl;
}

回答3:

有时候加密是转化为2进制。字母的2进制应该是乱码、

回答4:

#include
#define MAX 100//字符串的最大长度
using namespace std;

void encrypter ( char *, int );
void decrypter (char *, int);

int main()
{
char string[MAX] = "\0";
int key;

/* Encrypter */
cout<<"**** ENCRIPTER ****"< cout<<"Insert the secret sentence: ";
gets(string);//读取字符串

cout<<"Insert the incripting code : ";
cin>>key;//读取加密码

encrypter ( string, key );//加密
cout<<"The incrypted sentence is: "<
/* Decrypter */
cout<<"**** DECRYPTER ****"< cout<<"Insert the code: ";
cin>>key;//输入加密码

decrypter( string, key );//解密
cout<<"The decrypted sentence is: "<
return 0;
}

/* 加密函数 */
void encrypter ( char *pstr, int key )
{
while ( *pstr != '\0' )
{
*pstr += key;
pstr++;
}

}

/* 解密函数 */
void decrypter ( char *pstr, int key )
{
while ( *pstr != '\0' )
{
*pstr -= key;
pstr++;
}
}

回答5:

网络上搜索md5,用md5加密是最常用的。简单实现如下
#include "iostream"
#include "string.h"
using namespace std;
void encode(string& srcstr)
{
for(int i = 0;i {
if (srcstr[i]>='A' && srcstr[i]<='Z')
{
if (srcstr[i]!='Z')
{
srcstr[i] = srcstr[i]+1;
}
else
{
srcstr[i] = 'A';
}
}
}
}
void main()
{
string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
encode(str);
cout<}