java实现”凯撒密码“的加密解密

文章介绍了凯撒密码的基本原理,提供了一个Java代码实现,用于加密和解密文本,以及对密文进行25种可能的偏移量解密,以破解凯撒密码。
摘要由CSDN通过智能技术生成

一、前言

凯撒密码,最早是由古罗马将军凯撒发明,用于军队中传递信息,是一种位移加密的密文算法。由于英文是26个字母,所以最多解密出现25种情况,用程序来讲还是很少的例举,比较简单。所以用代码实践,实现凯撒密码的加解密,简单破译凯撒密码

二、逻辑实现


    private final static String codeRefer="ABCDEFGHIJKLMNOPQRSTUVWXYZ";//对照码
	
	/**
	 * 凯撒密码加密解密
	 * @param text 文本
	 * @param offset 偏移量
	 */
	public static String KSMMEncryptionDecrypt(String text,int offset) {
		String result="";
		for(int i=0; i<text.length(); i++) {
		    String code=text.substring(i,i+1);
		    int index=codeRefer.indexOf(code);
		    if(index!=-1){
		    	result+=KSMMDecryptToCode(index,offset);
		    }else {
		    	result+=code;
		    }
		}	
		return result;
	}
	
	
	/**
	 * 凯撒密码解密
	 * @param ciphertext 密文
	 */
	public static List KSMMDecrypt(String ciphertext) {
		List resultList=new ArrayList<>();
		for(int j=1; j<codeRefer.length(); j++) {
			String result="";
			for(int i=0; i<ciphertext.length(); i++) {
			    String code=ciphertext.substring(i,i+1);
			    int index=codeRefer.indexOf(code);
			    if(index!=-1){
			    	result+=KSMMDecryptToCode(index,j);
			    }else {
			    	result+=code;
			    }
			}
			resultList.add(result);
		}	
		return resultList;
	}
	
	/**
	 * 凯撒密码单个字符解密
	 * @param index 字符下标
	 * @param offset 偏移量
	 * @return
	 */
	public static String KSMMDecryptToCode(int index,int offset) {
		String code="";
		index+=offset;
		if(index>=codeRefer.length()) {
			index%=codeRefer.length();
		}
		code=codeRefer.substring(index, index+1);
		return code;
	}

三、程序运行

public static void main(String[] args) throws Exception {
	// TODO Auto-generated method stub
	String text="我想说:what are you doing!";
	String ciphertext=KSMMEncryptionDecrypt(text.toUpperCase(),23);
	System.out.println("---密文:"+ciphertext);
	List<String> list=KSMMDecrypt(ciphertext.toUpperCase());
	for(String str:list) {
		System.out.println("---:"+str.toLowerCase());
	}
}

打印输出
ok,终了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值