I'm trying to encrypt file by adding some int (a key selected randomly) for every char on it . for instance if the file contain the string "abcde" ,with key=2 the encrypted string will be "cdefg" the problem is that im using the encryption algorithm a lot of time and than im over the ascii table(over 255) . I tried to think in a way of modulo but it didn't help. anyone has an idea ?
- 1A simple substitution cipher doesn't really warrant the 'encryption' tag, or description.user207421– user2074212014-01-26 07:31:36 +00:00Commented Jan 26, 2014 at 7:31
- 2This is called a Caesar cipher.Jesper– Jesper2014-01-26 08:12:28 +00:00Commented Jan 26, 2014 at 8:12
Add a comment |
1 Answer
When you go over the ascii table value of 255, wrap it to 0 onwards. Something like:
int randomKey = 2; //However you want to assign the value - do it. ... //This is how you "encrypt" a character. Example character is 'a'. int character = 'a'; int encryptedChar = character + randomKey; if (encryptedChar > 255) { encryptedChar -= 255; } When "decrypt"ing follow the reverse logic.
However this is a very weak "encryption". A cryptanalyst will break it in no time!
Also note java char is 16 bit. Value can be more than 255. You should ensure input characters are in the range 0-255. Reject values beyond that.
3 Comments
Raman
The OP mentioned modulo didn't work?
int encryptedChar = (character + randomKey) % 255; should work fine, and the if can be removed.Harel Levy
The modulo won't work because one of the algorithms is the multiple the value of the char in the key. but if i'm adding he key it shoul work fine.