c# - Encrypt and Decrypt a string to fixed length -


i looked many examples , tried several articles. none of them solved issue.

i want encrypt primary column value in database(integer value) , show in url. want url simple , readable, don't want lengthy encryption values. mostly, looking around 5 7 characters in length.

is possible ? if so, best approach ?

encrypt , decrypt string

http://www.codeproject.com/tips/306620/encryption-decryption-function-in-net-using-md-cry

as per requirements, integers have no more 6 chars (999999) , encoding should max 7 chars, xor of 24 bits it:

beware method esily reversible bruteforce attack, hide real numbers majority of mortals.

first use 3 byte key (the values examples, take ones most:

byte[] thekey = new byte[]{ 34, 56, 98 };  

then encode integer take first 3 bytes (the fourth byte not necessary int not use it, 20 bits can store 1m, nearest byte count three) , xor each 1 correpsonding byte @ key:

int cyphered = ((thevalue & 0xff) ^ thekey[0]) |                 ((((thevalue >> 8) & 0xff) ^ thekey[1]) << 8) |                 ((((thevalue >> 16) & 0xff) ^ thekey[2]) << 16); 

and finally, make url's homogeneous convert string , pad zeroes:

string finalvalue = cyphered.tostring().padleft(7, '0'); 

to reverse value xor again key:

int cyphered = int.parse(thestringyoureceived);  int decyphered = ((cyphered & 0xff) ^ thekey[0]) |                   ((((cyphered >> 8) & 0xff) ^ thekey[1]) << 8)|                   ((((cyphered >> 16) & 0xff) ^ thekey[2]) << 16); 

as say, it's not precissely aes256 security cipher (:d) @ least hide numbers curious.

edit: here test case, works expected:

            byte[] thekey = new byte[] { 34, 56, 98 };              int thevalue = 1413;              int cyphered = ((thevalue & 0xff) ^ thekey[0]) |            ((((thevalue >> 8) & 0xff) ^ thekey[1]) << 8) |            ((((thevalue >> 16) & 0xff) ^ thekey[2]) << 16);              string finalvalue = cyphered.tostring().padleft(7, '0');              int scyphered = int.parse(finalvalue);              int decyphered = ((scyphered & 0xff) ^ thekey[0]) |                              ((((scyphered >> 8) & 0xff) ^ thekey[1]) << 8) |                              ((((scyphered >> 16) & 0xff) ^ thekey[2]) << 16); 

Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -