加解密程序,代替算法(JAVA实现)

  • Post author:
  • Post category:java


import java.util.Scanner;
class Encryption{
public void Encryption() {
    char c;
    System.out.print("请输入要加密的明文:"); 
    Scanner input = new Scanner(System.in);
    String str1 = input.nextLine();
    System.out.print("请输入要加密的密钥:");
    int k = input.nextInt();  
    System.out.print("加密后的明文为: ");
    for(int i = 0 ; i < str1.length() ; i ++) { 
       int n = (int)(str1.charAt(i));
       if(n >= 97 && n <= 122) { 
           n = (n - 97 + k) % 26;  
           c = (char)(n + 97); 
           str1=str1.substring(0, i)+c+str1.substring(i+1); 
       } 
    } 
    System.out.println(str1);
} 
} 
class Decrypt{ 
public void Decrypt() { 
    char c ;
    System.out.print("请输入需要解密的密文:"); 
    Scanner input = new Scanner(System.in); 
    String str3 = input.nextLine(); 
    System.out.print("请输入解密的密钥:"); 
    int k = input.nextInt(); 
    System.out.print("解密的明文是: "); 
    for(int i = 0 ; i < str3.length() ; i ++) { 
       int n = (int)(str3.charAt(i));        
       if(n >= 97 && n <= 122) { 
           n = (n - 97 - k); 
           if(n < 0) 
              n += 26; 
                     n = n % 26;
           c = (char)(n + 97); 
           str3=str3.substring(0, i)+c+str3.substring(i+1);
       } 
    } 
    System.out.println(str3);
} 
} 
public class Main { 
    public static void main(String[] args) {
    	boolean n=true;
       while(n) { 
           System.out.println("\n选择功能"); 
           System.out.println("1. 加密功能"); 
           System.out.println("2. 解密功能"); 
           System.out.println("3. 退出");
           Scanner input = new Scanner(System.in); 
           int c = input.nextInt(); 
           switch(c) {            
              case 1 :{ 
               Encryption encryption= new Encryption();
               encryption.Encryption();
               break; 
              } 
              case 2 : { 
                  Decrypt decrypt = new Decrypt(); 
                  decrypt.Decrypt(); 
                  break; 
              }
              case 3:{
            	  n=false;
            	  System.out.println("已退出");
            	  break;
              }
           } 
       } 
    } 
}

在这里插入图片描述



版权声明:本文为shaoNianABin123原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。