"Spikinsson" <no*@gonna.tell.ya> wrote in message news:<7D******************@afrodite.telenet-ops.be>...
I'm looking for a good decrypt/encrypt function, all I want is a function in this form:
char* encrypt(char* normal)
{
...
return encrypted;
}
and
char* decrypt(char* encrypted)
{
...
return normal;
}
I realize there would be memory allocation and I would have to free() or delete [] after
running the functions.
My problem is I don't know the first thing about any encryption method, so actually I'm
searching for already made functions that are similar to the two mentioned above. I have
really tried to use google to find such functions but I failed, I would very much
appreciate if anybody could post a function, an usefull tutorial or a link to some
source...
What kind of encryption are you looking for? The function could be as
simple as
char* encrypt(const char* plaintext)
{
int len = strlen(plaintext);
char* cyphertext = new char[len+1];
for(int i=0 ; i<len ; ++i)
{
cyphertext[i] = plaintext[i] + 1;
}
cyphertext[len] = 0; // to null-terminate...
return cyphertext;
}
(Of course, this would ideally be done with std::string and such.) To
decrypt simply change the +1 to a -1; you could even pass this in as
an argument and use one function for both encrypting or decrypting.
I'm think that this will wrap around ) right, but I'm not sure. In any
case, if you're just using text, as long as you don't shift it more
than 64 spaces you should be OK.
Here's a slightly more elaborate function (actually two of them, but
ROT13 provides the interface for what you use); it will both encode
and decode, but only letters. (These could be put into a class to keep
them together and the scope nice.)
char rot13letter(char c)
{
if(!isalpha(c)) return c; // non-letters are returned
if(c<='M') return c+13; // A through M maps to N through Z
if(c<='Z') return c-13; // N through Z maps to A through M
if(c<='m') return c+13; // and the same thing for lowercase
if(c<='z') return c-13; // ""
throw SomthingWentHorriblyAndTerriblyWrongException;
}
char* ROT13(const char* plaintext)
{
int len = strlen(plaintext);
char* cyphertext = new char[len+1];
for(int i=0 ; i<len ; ++i)
{
cyphertext[i] = rot13letter(plaintext[i]);
}
cyphertext[len] = 0; // to null-terminate...
return cyphertext;
}
Note also that I'm guessing these would conventionally be implemented
as void functions that operate directly on plaintext rather than
passing out a whole other string. This has severl advantages:
*Often you won't need access to plaintext after you encrypt it, so
reusing that space is preferred (so you don't waste either the space
it would occupy or the allocation time)
*It gives your client function a better idea of what memory is in use,
which makes it less likely that you'll forget to delete[] the return.
*It takes away no flexibility, as the client function can always
duplicate the plaintext string itself before passing it in.