您的位置:首页 > 编程语言 > C语言/C++

c++ byte和字符串简单加密变形

2015-04-23 15:40 239 查看
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;

typedef unsigned char byte;
//typedef unsigned char BYTE; //这个宏

typedef unsigned char BYTE;

//http://www.52ij.com/jishu/cpp/cbyte/5620.html
//c++ byte转int
int bytesToInt(byte* bytes,int size = 4)

{

int a = bytes[0] & 0xFF;

a |= ((bytes[1] << 8) & 0xFF00);

a|= ((bytes[2] << 16) & 0xFF0000);

a |= ((bytes[3] << 24) & 0xFF000000);

return a;

}
/*
构造两个参数,一个是BYTE数组,一个是BYTE数组对应的长度,目的是方便后续的for循环进行遍历而不用再此判断。
*/
//http://www.52ij.com/jishu/cpp/cbyte/

string* byteToHexStr(unsigned char byte_arr[], int arr_len)
{
string* hexstr=new string();
for (int i=0;i<arr_len;i++)
{
char hex1;
char hex2;
/*借助C++支持的unsigned和int的强制转换,把unsigned char赋值给int的值,那么系统就会自动完成强制转换*/
int value=byte_arr[i];
int S=value/16;
int Y=value % 16;
//将C++中unsigned char和int的强制转换得到的商转成字母
if (S>=0&&S<=9)
hex1=(char)(48+S);
else
hex1=(char)(55+S);
//将C++中unsigned char和int的强制转换得到的余数转成字母
if (Y>=0&&Y<=9)
hex2=(char)(48+Y);
else
hex2=(char)(55+Y);
//最后一步的代码实现,将所得到的两个字母连接成字符串达到目的
*hexstr=*hexstr+hex1+hex2;
}
return hexstr;

}
//加密信息并输出,要指定长度,字串结尾'\0'也可以被加密。再次调用即解密。
void EnCodeLen(char* pStr,unsigned int len)
{
for(unsigned int i=0;i<len;i++)
{
pStr[i]=~(pStr[i]^0x7e);
}
//打印加密后字串
//PrintHexLen(pStr,len);
}

void test001()
{

char *chs="1234";
unsigned int len=strlen(chs);
byte *hehe;
hehe=(byte*)malloc(sizeof(byte)*len);
memset(hehe,0,len);
for (unsigned int i=0;i<len;i++)
{
printf("%d\n",chs[i]);
hehe[i]=chs[i];

}
hehe[len]='\0';
cout<<hehe<<endl;

int result=bytesToInt(hehe);
cout<<result<<endl;
string* str=byteToHexStr(hehe,len);
cout<<str<<endl;

}
int main( int argc, char* argv[] )
{
//test001();

//c++ byte和字符串简单加密变形
//char dd[]="123456789";
if(argc<2)
{

printf("error arg: %s input.txt",argv[0]);
return -1;
}
if(strcmp("result.txt",argv[1])==0)
{
printf("input file cannot be result.txt",argv[0]);
return -1;

}
ifstream input(argv[1]);
ofstream output("result.txt");
char line[1024];
int flag=0;
if(argc>2)
{

flag=1;
}

while(input.getline(line,1024)!=NULL)
{

string str=string(line);
if(str.empty())
{
continue ;

}
EnCodeLen(line,strlen(line));
//printf("%s\n",line);

if(flag)
{
output<<str<<"==>"<<string(line)<<endl;

}else{
output<<string(line)<<endl;
}

}

output.close();
system("notepad result.txt");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: