Search code examples
javaencryptioncharstring-length

Program to Encrypt Text Depending on the Length of a Word


I wanted to make a program to encrypt text depending on its length. For example if the word was "test", then because "test" has 4 letters, it will shift each letter in the word to the 4th next letter. This would make "test" to "xiwx". I have made part of my program already. Here is it:

public static void main(String[] args){
    string.toLowerCase();
    int charPos = 0;
    int length = 0;

    for(int i = 0; i < string.length(); i++){
        charPos = 0;
        length = 0;
        while(!(string.charAt(i) == ' ')){
            length = charPos;
            charPos++;
        }
        length--;
        for(int j = 0; j<=length; j++){
            char cha =string.charAt(i);

            //HERE IS WHERE THE CHAR ADDING WILL HAPPEN

        }
        i++;

    }

}//end

Solution

  • There is a simpler way to achieve this type of encryption just by using one loop.

    Encryption:

    String str = "test"; // normal string
    
    String encryptedStr = ""; // start empty then add characters
    
    for (char ch : str.toCharArray()) // loop through each character in str
    
        encryptedStr += (char) (ch + str.length()); // need to cast addition to char
    
    System.out.println("Encrypted String: " + encryptedStr); // output encrypted string
    

    So the idea is to use the length() method to get the length of the string, as that's what you're adding to each character. Because each character has an ASCII integer value, we can perform math operations on them (so in this case, adding the length to each character). Then, since the result will be an integer, we must add a (char) cast to the result to convert it back to a character. Then we can concatenate this character to the empty string. If we do this with each character in the original string (by using a for loop and converting the string to a char array), we'll eventually get the encrypted string at the end.

    The same idea works with Decryption:

    String str = "xiwx"; // encrypted string
    
    String decryptedStr = ""; // start empty then add characters
    
    for (char ch : str.toCharArray()) // loop through each character in str
    
        decryptedStr += (char) (ch - str.length()); // need to cast subtraction to char
    
    System.out.println("Decrypted String: " + decryptedStr); // output decrypted string
    

    Except we subtract the length from each character.

    Hope this helped :)