加密算法类:
#include "RDcoder.h"
using namespace std;
//构造函数,传入密钥
RDcoder::RDcoder(std::string _str_key)
{
str_key = _str_key;
if (str_key.empty())
{
str_key = "giat_mvlab";
}
}
RDcoder:: ~RDcoder()
{
}
/*
* Comments:对原文进行转换
* Param in_byte:输入的原文
* Param shift_code: 转换码
* Param bLeft: 左移标志,否则右移
* @Return 返回转换后的密文
*/
BYTE RDcoder::ShiftByte(BYTE in_byte, unsigned int shift_code, bool bLeft)
{
//平移转换码,只能0~7
shift_code = shift_code % 8; //3
shift_code = bLeft ? (8 - shift_code) : shift_code;
//10001101 -> 10110001 右移3位
BYTE low_byte = in_byte & ((1 << shift_code) - 1); // 101
BYTE high_byte = in_byte >> shift_code; //1001
BYTE ret_byte = low_byte * (1 << (8 - shift_code)) + high_byte; //10110001
return ret_byte;
}
/*
* Comments:对原文进行加密
* Param plain_text:输入的原文
* @Return 返回加密后的密文
*/
string RDcoder::encode(const std::string plain_text)
{
//加密->转16进制->填充或截取为长度32
//加密
string shift_text;
for (int i = 0; i < plain_text.length(); i++)
{
shift_text += ShiftByte(plain_text[i], str_key[i%str_key.length()]);
}
//转16进制
string hex_text = Utils::ByteToHexString((const BYTE*)shift_text.c_str(), shift_text.length());
//截取长度
hex_text.resize(BLOCK_LEN, '#');
return hex_text;
}
/*
* Comments:对密文进行解密
* Param cipher_text:输入的密文,如果长度超过32则会截取
* @Return 返回解密后的原文
*/
string RDcoder::decode(const std::string cipher_text)
{
//去掉#->反转16进制->解密
//去掉#
string sub_text = cipher_text.substr(0, cipher_text.find('#'));
if (sub_text.length() > BLOCK_LEN)
{
sub_text.resize(BLOCK_LEN);
}
//反转16进制
BYTE out_bytes[BLOCK_LEN] = { 0 };
int ret_len = Utils::HexStringToByte(sub_text, out_bytes);
//解密
string shift_text;
for (int i = 0; i < ret_len; i++)
{
shift_text += ShiftByte(out_bytes[i], str_key[i%str_key.length()], true);
}
return shift_text;
}
字节转换方法:
const string hex_code = "0123456789abcdef";
/*
* Comments:byte数组转成16进制字符串(小写字母)
* Param bytes:输入的数组
* Param len: bytes的长度
* @Return 成功则返回转化后的字符串
*/
string Utils::ByteToHexString(const BYTE *bytes, int len)
{
if (bytes == NULL || len < 1)
{
cout << "ByteToHexString: bytes is empty." << endl;
return "";
}
string hex_str = "";
for (int i = 0; i < len; i++)
{
hex_str += hex_code[bytes[i] / 16];
hex_str += hex_code[bytes[i] % 16];
}
return hex_str;
}
/*
* Comments:16进制字符串转成byte数组
* Param hex: 输入的16进制字符串,长度必需为偶数,否则最后一个字符会丢掉
* Param bytes:输出的数组
* @Return 返回转化后的数组长度
*/
int Utils::HexStringToByte(const std::string hex, BYTE *bytes)
{
//hex先转成小写字母
string low_hex;
for (int i = 0; i < hex.length(); i++)
{
low_hex += tolower(hex[i]);
}
//如果长度是偶数,去掉最后一字符
if (low_hex.length() % 2)
{
low_hex.resize(low_hex.length() - 1);
}
int j = 0;
for (int i = 0; i < low_hex.length(); )
{
bytes[j] = hex_code.find(low_hex[i]) * 16;
bytes[j] += hex_code.find(low_hex[i + 1]);
i += 2;
j += 1;
}
return j;
}