简体   繁体   中英

Encrypting file in java

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM