实施“凯撒密码加密”算法

时间:2020-10-10 05:23:54

标签: java algorithm encryption caesar-cipher

我刚刚为“凯撒密码加密”算法编写了代码。谁能检查我实施的方式是否错误?预先谢谢你。

这基本上有3个类,分别称为“ Main”,“ Alphabet”,“ EncryptionAlgorithm”和“ DecryptionAlgorithm”。

代码工作正常,但是我想在此程序中减少代码。

我还对每一行进行了评论,以便其他人可以轻松地参考。

请让我知道您的想法,以使代码更高效并帮助我了解我做错了什么。谢谢。

import java.util.Scanner; // Import java utility input/output scanner library.

public class Main { // Main class begins here.

public static void main(String[] args) { // Main method begins here.
    
    Scanner get = new Scanner(System.in); // Creating an object for the scanner class.
    
    System.out.println("\n$$$$$$$$$$ Welcome to Caesar Cipher Encryption Algorithm $$$$$$$$$$\n"); // Display welcome message of the program.
    
    System.out.println("Note : MUST USE BLOCK CAPITAL LETTERS.\n"); // Notice to prevent from errors.
    
    System.out.println("Please Select an Operation.\n");
    
    System.out.println("1 - Encrypt a Message");
    System.out.println("2 - Decrypt a Message");
    
    System.out.print("\nEnter Your Choice : ");
    int choice = Integer.parseInt(get.nextLine());
    
    switch (choice)
    {
        case 1: 
            System.out.println("\n\n------------------------ Message Encryption ------------------------\n\n");
            EncryptionAlgorithm EM = new EncryptionAlgorithm();
            EM.encryption();
            break;
            
        case 2: 
            System.out.println("\n\n------------------------ Message Decryption ------------------------\n\n");
            DecryptionAlgorithm DM = new DecryptionAlgorithm();
            DM.decryption();
            break;
            
            default:
                System.out.println("\nWRONG INPUT! PLEASE TRY AGAIN.\n");
                break;
    }
    
    get.close();
    
} // Main method ends here.
} // Main class ends here.


public class Alphabet { // Alphabet class begins here.

char[] alphabetCharactersArray = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; // Declaring an array called 'alphabetCharactersArray' which contains 26 alphabetic charters.
} // Alphabet class ends here.


import java.util.Scanner; // Import java utility input/output scanner library.

public class EncryptionAlgorithm extends Alphabet{

Scanner get = new Scanner(System.in); // Creating an object for the scanner class.

// cipherTextArray[indexNo] = plainTextArray[indexNo] + keyArray[indexNo]; // Encryption Formula //
void encryption()
{
    System.out.print("Enter a Message to Encrypt : "); // ask user to enter the message to be encrypted.
    String message = get.nextLine(); // Initialize the message to a variable called 'message'.
    
    char[] charactersOfMessageArray = message.toCharArray(); // Convert the message string into char and put it in an array called 'charactersOfMessageArray'.
    
    System.out.print("\nGenerate a Decryption Key  : "); // ask user to generate a decryption key. //Example - 'WEAPON'
    String decryptionKey = get.nextLine(); // Initialize the decryption key to a variable called 'decryptionKey'.
    
    get.close(); // Close the scanner.
    
    char[] charactersOfDecryptionKeyArray = decryptionKey.toCharArray(); // Convert decryption key string into char and put it in an array called 'charactersOfDecryptionKeyArray'.
    
    int[] plainTextArray  = new int [charactersOfMessageArray.length]; // This array consist of intended numbers for each character of the plain text.
    int[] cipherTextArray = new int [charactersOfMessageArray.length]; // This array consist of intended numbers for each character of the cipher text.
    int[] keyArray        = new int [charactersOfMessageArray.length]; // This array consist of intended numbers for each character of the decryption key text.
    
    // Creating the Plain Text Array in indented numbers relevant to each character of the message.
    for(int beginingIndexNoOfMessagearray = 0; beginingIndexNoOfMessagearray < charactersOfMessageArray.length; beginingIndexNoOfMessagearray++) // This for loop runs until it checks all the characters of the encrypted MSG with intended numbers that each alphabetic number has.
    {
        for(int begingIndexOfAlpabetArray = 0; begingIndexOfAlpabetArray < alphabetCharactersArray.length; begingIndexOfAlpabetArray++) // This loop runs until it reaches the end of the array called 'alphabetCharactersArray'.
        {
            if(charactersOfMessageArray[beginingIndexNoOfMessagearray] == alphabetCharactersArray[begingIndexOfAlpabetArray]) // This if loop checks the intended numbers of each character of the encrypted message string.
            {
                plainTextArray[beginingIndexNoOfMessagearray] = begingIndexOfAlpabetArray; // This line of code will store each intended number accordingly in the Plain Text Array.
            } // Condition ends here.
        } // Nested for loop ends here.
    } // Main for loop ends here.
    
    // Creating the Key Array in indented numbers relevant to each character of the decryption key.
    for(int beginingIndexNoOfKeyarray = 0; beginingIndexNoOfKeyarray < charactersOfDecryptionKeyArray.length; beginingIndexNoOfKeyarray++) // This for loop runs until it checks all the characters of the encrypted MSG with intended numbers that each alphabetic number has.
    {
        for(int begingIndexOfAlpabetArray = 0; begingIndexOfAlpabetArray < alphabetCharactersArray.length; begingIndexOfAlpabetArray++) // This loop runs until it reaches the end of the array called 'alphabetCharactersArray'.
        {
            if(charactersOfDecryptionKeyArray[beginingIndexNoOfKeyarray] == alphabetCharactersArray[begingIndexOfAlpabetArray]) // This if loop checks the intended numbers of each character of the encrypted message string.
            {
                keyArray[beginingIndexNoOfKeyarray] = begingIndexOfAlpabetArray; // This line of code will store each intended number accordingly in the cipherTextArray.                       }
            } // Condition ends here.
        } // Nested for loop ends here.
    } // Main for loop ends here.
    
    int j = 0; // 'j' is the beginning index number of decryption key array.
    
    for(int i = 0; i < (charactersOfMessageArray.length - charactersOfDecryptionKeyArray.length); i++) // This for loop runs length of the Message array - length of the decryption key array length times.
    {
        keyArray[charactersOfDecryptionKeyArray.length + i] = keyArray[j]; // This line of code will store the intended values for each character in the length of Message array for the key array.
        
        j++; // beginning index number of decryption key array will be incremented by 1.
        
        if(j == charactersOfDecryptionKeyArray.length) // This condition checks if the last index value of the decryption key array is assigned to the intended value in the key array and helps to repeat the process until it reaches the last index of the key array.
        {
            j = 0; // When the last index value of decryption key array is assigned to the intended value in the key array, this will reset the value of 'j' to 0 and helps to repeat the process.
        } // Condition ends here.
    } // for loop ends here.
    
    for(int i = 0; i < charactersOfMessageArray.length; i++) // This for loop runs the length of the MSG array times.
    {
        int value = (plainTextArray[i] + keyArray[i]) % 26; // Formula of the Encryption.
        
        if(value >= 0) // If the value is 0 or positive value, it will map with the alphabet array values and find the exact character.
        {
            cipherTextArray[i] = value; // After finding the exact character, it will then be stored in another array called 'cipherTextArray'.
        } // Condition ends here.
        
        else // If the value isn't 0 and negative value, it will be deducted from 26 and get a positive value which can map with the alphabet array values in order to find the exact character.
        {
            cipherTextArray[i] = 26 + value;    // After finding the exact character, it will then be stored in array called 'cipherTextArray'.
        } // Conditions ends here.
        
    } // for loop ends here.
    
    // Optional lines of code to display more details of the values. 
       /*System.out.println("\n$$$$ P[i] $$$\n");
            
       for(int i = 0; i < plainTextArray.length; i++)
       {
           System.out.println("P["+(i)+"] = "+plainTextArray[i]);
       }
            
       System.out.println("\n$$$$ KEY $$$\n");
            
       for(int i = 0; i < keyArray.length; i++)
       {
            System.out.println("K["+(i)+"] = "+keyArray[i]);
       }*/
    
    System.out.print("\n\nEncrypted Message          : "); // Display the output.
    
    for(int i = 0; i < charactersOfMessageArray.length; i++) // This loop runs the length of the MSG array times.
    {
        System.out.print(alphabetCharactersArray[cipherTextArray[i]]); // This will display/output the exact characters which were mapped with the values of plain text array.
    } // for loop ends here.
} // encryption() method ends here.
} // EncryptionAlgorithm class ends here.


import java.util.Scanner; // Import java utility input/output scanner library.

public class DecryptionAlgorithm extends Alphabet{

Scanner get = new Scanner(System.in); // Creating an object for the scanner class.

// plainTextArray[indexNo] = cipherTextArray[indexNo] - keyArray[indexNo]; // Decryption Formula //
void decryption()
{
    System.out.print("Enter Encrypted MSG  : "); // ask user to enter the encrypted message.
    String encryptedMSG = get.nextLine(); // Initialize the encrypted message to a variable called 'encryptedMSG'.
    
    char[] charactersOfEncryptedMSGArray = encryptedMSG.toCharArray(); // Convert encrypted message string into char and put it in an array called 'charactersOfEncryptedMSGArray'.
    
    System.out.print("\nEnter Decryption Key : "); // ask user to enter the decryption key.
    String decryptionKey = get.nextLine(); // Initialize the decryption key to a variable called 'decryptionKey'.
    
    get.close(); // Close the scanner.

    char[] charactersOfDecryptionKeyArray = decryptionKey.toCharArray(); // Convert decryption key string into char and put it in an array called 'charactersOfDecryptionKeyArray'.
    
    int[] plainTextArray  = new int [charactersOfEncryptedMSGArray.length]; // This array consist of intended numbers for each character of the plain text.
    int[] cipherTextArray = new int [charactersOfEncryptedMSGArray.length]; // This array consist of intended numbers for each character of the cipher text.
    int[] keyArray        = new int [charactersOfEncryptedMSGArray.length]; // This array consist of intended numbers for each character of the decryption key text.
    
    // Creating the Cipher Text Array in indented numbers relevant to each character of the encrypted message.
    for(int beginingIndexNoOfMSGarray = 0; beginingIndexNoOfMSGarray < charactersOfEncryptedMSGArray.length; beginingIndexNoOfMSGarray++) // This for loop runs until it checks all the characters of the encrypted MSG with intended numbers that each alphabetic number has.
    {
        for(int begingIndexOfAlpabetArray = 0; begingIndexOfAlpabetArray < alphabetCharactersArray.length; begingIndexOfAlpabetArray++) // This loop runs until it reaches the end of the array called 'alphabetCharactersArray'.
        {
            if(charactersOfEncryptedMSGArray[beginingIndexNoOfMSGarray] == alphabetCharactersArray[begingIndexOfAlpabetArray]) // This if loop checks the intended numbers of each character of the encrypted message string.
            {
                cipherTextArray[beginingIndexNoOfMSGarray] = begingIndexOfAlpabetArray; // This line of code will store each intended number accordingly in the cipherTextArray.
            } // Condition ends here.
        } // Nested for loop ends here.
    } // Main for loop ends here.
        
    // Creating the Key Array in indented numbers relevant to each character of the decryption key.
    for(int beginingIndexNoOfKeyarray = 0; beginingIndexNoOfKeyarray < charactersOfDecryptionKeyArray.length; beginingIndexNoOfKeyarray++) // This for loop runs until it checks all the characters of the encrypted MSG with intended numbers that each alphabetic number has.
    {
        for(int begingIndexOfAlpabetArray = 0; begingIndexOfAlpabetArray < alphabetCharactersArray.length; begingIndexOfAlpabetArray++) // This loop runs until it reaches the end of the array called 'alphabetCharactersArray'.
        {
            if(charactersOfDecryptionKeyArray[beginingIndexNoOfKeyarray] == alphabetCharactersArray[begingIndexOfAlpabetArray]) // This if loop checks the intended numbers of each character of the encrypted message string.
            {
                keyArray[beginingIndexNoOfKeyarray] = begingIndexOfAlpabetArray; // This line of code will store each intended number accordingly in the cipher Text Array.
            } // Condition ends here.
        } // Nested for loop ends here.
    } // Main for loop ends here.
    
    int j = 0; // 'j' is the beginning index number of decryption key array.
    
    for(int i = 0; i < (charactersOfEncryptedMSGArray.length - charactersOfDecryptionKeyArray.length); i++) // This for loop runs length of the MSG array - length of the decryption key array length times.
    {
        keyArray[charactersOfDecryptionKeyArray.length + i] = keyArray[j]; // This line of code will store the intended values for each character in the length of MSG array for the key array.
        
        j++; // beginning index number of decryption key array will be incremented by 1.
        
        if(j == charactersOfDecryptionKeyArray.length) // This condition checks if the last index value of the decryption key array is assigned to the intended value in the key array and helps to repeat the process until it reaches the last index of the key array.
        {
            j = 0; // When the last index value of decryption key array is assigned to the intended value in the key array, this will reset the value of 'j' to 0 and helps to repeat the process.
        } // Condition ends here.
    } // for loop ends here.
    
    for(int i = 0; i < charactersOfEncryptedMSGArray.length; i++) // This for loop runs the length of the MSG array times.
    {
        int value = (cipherTextArray[i] - keyArray[i]) % 26; // Formula of the Encryption.
        
        if(value >= 0) // If the value is 0 or positive value, it will map with the alphabet array values and find the exact character.
        {
            plainTextArray[i] = value; // After finding the exact character, it will then be stored in another array called 'plainTextArray'.
        } // Condition ends here.
        
        else // If the value isn't 0 and negative value, it will be deducted from 26 and get a positive value which can map with the alphabet array values in order to find the exact character.
        {
            plainTextArray[i] = 26 + value; // After finding the exact character, it will then be stored in array called 'plainTextArray'.
        } // Conditions ends here.
        
    } // for loop ends here.
    
    // Optional lines of code to display more details of the values. 
       /*System.out.println("\n$$$$ C[i] $$$\n");
            
       for(int i = 0; i < cipherTextArray.length; i++)
       {
           System.out.println("C["+(i)+"] = "+cipherTextArray[i]);
       }
            
       System.out.println("\n$$$$ KEY $$$\n");
            
       for(int i = 0; i < keyArray.length; i++)
       {
            System.out.println("K["+(i)+"] = "+keyArray[i]);
       }*/
    
    System.out.print("\n\nDecrypted MSG        :"); // Display the output.
    
    for(int i = 0; i < charactersOfEncryptedMSGArray.length; i++) // This loop runs the length of the MSG array times.
    {
        System.out.print(" "+alphabetCharactersArray[plainTextArray[i]]); // This will display/output the exact characters which were mapped with the values of plain text array.
    } // for loop ends here.
} // decryption() method ends here.
} // DecryptionAlgorithm class ends here.

0 个答案:

没有答案
相关问题