代码改变世界

课后作业加密

2015-10-24 13:28  逆光而行  阅读(163)  评论(0编辑  收藏  举报

源代码:

package test2;

import java.util.Scanner;

public class Caeser {
    private String table; // 定义密钥字母表
    private int key; // 定义密钥key
    public Caeser(String table, int key) {
        // 根据不同的字母表和不同的密钥生成一个新的凯撒算法,达到通用的目的
        super();
        this.table = table;
        this.key = key;
    }
    public String encrypt(String from) {
        //凯撒加密算法,传入明文字符串,返回一个密文字符串
        String to = "";
        for (int i = 0; i < from.length(); i++) {
            to += table.charAt((table.indexOf(from.charAt(i))+key)%table.length());
        }
        return to;
    }
    
    public static void main(String[] args) {
        Caeser caeser = new  Caeser("abcdefghijklmnopqrstuvwxyz", 3);
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要加密的字符串");
        String str =scanner.nextLine(); //输入字符串 security
        String result = caeser.encrypt(str); //调用加密方法进行加密
        System.out.print(result); // 可得结果 vhfxulwb
    }
}

截图: