欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA编写一个加密及解密程序

程序员文章站 2022-07-13 13:38:46
...

加密解密程序
思想加密,先得到明文和**,判断明文的每个字符是小写字母还是大写字母,在根据**进行取模移位。解密的思想跟加密类似。
加密:

package com.company;
import java.util.Scanner;
public class Encrypt {
    public static void Encrypt() {
        System.out.println("请输入明文:");
        Scanner scanner1 = new Scanner(System.in);
        String str1 = scanner1.nextLine();
        System.out.println("请输入**:");
        Scanner scanner = new Scanner(System.in);
        int key1 = scanner.nextInt();
        String string="";
		for(int i=0;i<str1.length();i++) {
        char c=str1.charAt(i);
        if(c>='a'&&c<='z')
        {
            c+=key1%26;
            if(c<'a') c+=26;

            if(c>'z') c-=26;
        }else if(c>='A'&&c<='Z')
        {
            c+=key1%26;
            if(c<'A') c+=26;
            if(c>'Z') c-=26;
        }
        string =string+c;
    }
		System.out.println("加密后为:"+string);
}
}

解密:

package com.company;
import java.util.Scanner;
public class Decrypt {
    public  void Decrypt() {
        System.out.println("请输入密文:");
        Scanner scanner1 = new Scanner(System.in);
        Scanner scanner = new Scanner(System.in);
        String str2 = scanner1.nextLine();
        System.out.println("请输入**:");
        int key2 = scanner.nextInt();
        key2 = -key2;
        String string="";
        for(int i=0;i<str2.length();i++) {
            char c=str2.charAt(i);
            if(c>='a'&&c<='z')
            {
                c+=key2%26;
                if(c<'a') c+=26;
                if(c>'z') c-=26;
            }else if(c>='A'&&c<='Z')
            {
                c+=key2%26;
                if(c<'A') c+=26;
                if(c>'Z') c-=26;
            }
            string =string+c;
        }
        System.out.println("解密后为:"+string);
    }
}

实现:

package com.company;
import java.util.Scanner;
public class Application {
    public static void main(String[] args) {
        int c;
        do {
            System.out.println("选择功能:1:加密功能  2:解密功能 3:退出");
            Scanner scanner = new Scanner(System.in);
             c = scanner.nextInt();
            switch (c) {
                case 1: {
                    Encrypt encrypt = new Encrypt();
                    encrypt.Encrypt();
                    break;
                }
                case 2: {
                    Decrypt decrypt = new Decrypt();
                    decrypt.Decrypt();
                }
            }
        }
        while (c !=3);
        if(c == 3) System.out.println("欢迎再次使用");
    }
}

运行结果:
JAVA编写一个加密及解密程序