简体   繁体   中英

Correct use of for loop, substring, and conversion of hexadecimal ascii code to character?

I am trying to create my own java encryption program that encrypts a string: It takes a string and converts each character to its hexadecimal ascii representation. My encryption is to add a random number and random letter on each side of the two numbers that represent the hexadecimal ascii for each character. This will return a 6 character string for each character that is encrypted. Eg (help -> h -> 68 -> 3+6+g+1+8+f) I am trying to implement using four functions (encryptMessage, encryptCharacter, decryptMessage, decryptCharacter). I searched the site and could not find any posts that helped me. Could you possibly help me identify why I can't decrypt my message successfully using the decryptCharacter/decryptMessage methods? I am running just one character through right now and it is not returning the same character that I enter initially. 1. Am I using my for loops correctly in the decryptMessage and decryptCharacter methods? 2. In method decryptCharacter am I correctly converting the ascii hexadecimal representation back into its respective character? If not could someone explain how I could correct my code?

I have my program posted on pastebin: http://pastebin.com/6QMFYrKD

Any help is appreciated! I am new to java and I am trying to write the program to better understand how to use these methods that are called upon by the main program!

In your code, the DecryptCharacter method is not decrypting properly. You are adding the random char and number to each digit of the hexadecimal representation of the character. so, You should be doing this

String hexRep = encryptedCharacter.substring(1, 2) + encryptedCharacter.substring(4, 5) 

instead of

String hexRep = encryptedCharacter.substring(1, 4);

Also,

There is a bug in DecryptMessage method

The if condition if (i >= encryptedText.length() - 6) { wont work because it will always return false till the last 6 chars of the encrypted message, so, you can try something as below.

if (encryptedText.length() > 0 && encryptedText.length() % 6 == 0) {

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