Skip to content

Instantly share code, notes, and snippets.

@kyle-go
Last active December 14, 2015 00:59
Show Gist options
  • Save kyle-go/5002805 to your computer and use it in GitHub Desktop.
Save kyle-go/5002805 to your computer and use it in GitHub Desktop.
jgg2 encrypt
/*!
jgg encrypt
*/
#include <string>
#include <assert.h>
#define JGG_CONST_STRING " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
//#define CONST_STRING " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n\t"
#define JGG_SIZE (sizeof(JGG_CONST_STRING)-1)
struct JGG_KEY
{
int x;
int y;
char m[JGG_SIZE+1];
};
JGG_KEY jggSetup(const unsigned char * key, int len);
JGG_KEY jggSetup(const std::string& key);
bool jggEncrypt(JGG_KEY &jk, unsigned char * data, int ilen, bool enc);
std::string jggEncrypt(JGG_KEY &jk, const std::string &src, bool enc);
JGG_KEY jggSetup(const unsigned char * key, int len)
{
int i=0, j=0, k=0;
JGG_KEY jk = {0, 0, JGG_CONST_STRING};
for( i=0; i<JGG_SIZE; i++ )
{
j = (unsigned char)(j + jk.m[i] + key[k])%JGG_SIZE;
if (i != j)
{
char tmp = jk.m[i];
jk.m[i] = jk.m[j];
jk.m[j] = tmp;
}
if( ++k >= len)
k = 0;
}
return jk;
}
JGG_KEY jggSetup(const std::string& key)
{
return jggSetup((const unsigned char *)key.c_str(), (int)key.length());
}
bool jggEncrypt(JGG_KEY &rk, unsigned char * data, int ilen, bool enc)
{
int i, j, x, y, k;
bool bFind = false;
x = rk.x;
y = rk.y;
for( i = 0; i < ilen; i++ )
{
//check
bFind = false;
for (j=0; j< JGG_SIZE; j++)
{
if (JGG_CONST_STRING[j] == data[i])
{
bFind = true;
}
}
if (bFind == false)
{
return false;
}
//fuck
for( k=0,j=0; j<JGG_SIZE; j++ )
{
x = (unsigned char) ( x + 1 )%JGG_SIZE;
y = (unsigned char) ( y + rk.m[x] )%JGG_SIZE;
if (x != y)
{
rk.m[x] ^= rk.m[y];
rk.m[y] ^= rk.m[x];
rk.m[x] ^= rk.m[y];
}
if( ++k >= ilen)
k = 0;
}
//encrypt
if (enc)
{
for (j=0; j<JGG_SIZE; j++)
{
if (data[i] == rk.m[j])
{
break;
}
}
data[i] = JGG_CONST_STRING[j];
}
//decrypt
else
{
for (j=0; j<JGG_SIZE; j++)
{
if (data[i] == JGG_CONST_STRING[j])
{
break;
}
}
data[i] = rk.m[j];
}
}
rk.x = x;
rk.y = y;
return true;
}
std::string jggEncrypt(JGG_KEY &jk, const std::string &src, bool enc)
{
auto ret = src;
if (jggEncrypt(jk, (unsigned char *)ret.c_str(), (int)ret.length(), enc))
return ret;
return "";
}
int main()
{
std::string src = "***hello github!!!***";
auto dst = jggEncrypt(jggSetup("i am a key..."), src, true);
printf("src:%s\n", src.c_str());
printf("dst:%s\n", dst.c_str());
printf("src:%s\n", jggEncrypt(jggSetup("i am a key..."), dst, false).c_str());
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment