1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
namespace MyCrypt
{
const char *DEFAULT_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=<>?,./\\|[]{}`~";
const int eTable[] = { 85,170,-17, 68,153, 17,136, 34,-136, 51,-136, -51,-153, -51,-170 }; // split char value into 15 divisions, tables indicate value to offset
const int dTable[] = { 136, 17,136,153,170,-85,-17,-68, 51,-34, 51,-170, -51,-153,-136 }; // same as above but reverses offset to original
const float chapters = 17.0; // 15 * 17 = 255
unsigned char cenc(const unsigned char cVal)
{
return (cVal + eTable[((int)ceil(cVal/chapters))-1]); // divide char val by 17, take ceiling, subtract 1 to get index in eTable
}
unsigned char cdec(const unsigned char cVal)
{
return (cVal + dTable[((int)ceil(cVal/chapters))-1]); // same as eTable, but for decryption
}
std::string encrypt(std::string s, std::string k = DEFAULT_KEY)
{
std::string sret;
for(std::string::size_type i=0; i < s.size(); ++i)
{
unsigned char ci = s.at(i), ck = k.at(i % (k.size()-1)); // rotate key index for length of string
sret += (cenc(ci)^ck); // get new value for s[i] from cenc(), XOR with key value from k[i]
}
return sret; // return encrypted string
}
std::string decrypt(std::string s, std::string k = DEFAULT_KEY)
{
std::string sret;
for(std::string::size_type i=0; i < s.size(); ++i)
{
unsigned char ci = s.at(i), ck = k.at(i % (k.size()-1)); // rotate key index for length of string
sret += cdec(ci^ck); // XOR s[i] with key value from k[i], get original value from cdec();
}
return sret; // return decrypted string
}
};
|