0

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 ?

2
  • 1
    A simple substitution cipher doesn't really warrant the 'encryption' tag, or description. Commented Jan 26, 2014 at 7:31
  • 2
    This is called a Caesar cipher. Commented Jan 26, 2014 at 8:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The OP mentioned modulo didn't work? int encryptedChar = (character + randomKey) % 255; should work fine, and the if can be removed.
By the way, this is a very weak encrypting algorithm. You should think of stronger algorithms, such as Rijindael.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.