凯撒加密算法(最简单的对称加密) 您所在的位置:网站首页 凯撒密码对应表内容 凯撒加密算法(最简单的对称加密)

凯撒加密算法(最简单的对称加密)

2023-12-25 07:31| 来源: 网络整理| 查看: 265

凯撒算法 概述

凯撒密码是罗马扩张时期朱利斯• 凯撒(Julius Caesar)创造的,用于加密通过信使传递的作战命令。它将字母表中的字母移动一定位置而实现加密。例如如果向右移动 2 位,则 字母 A 将变为 C,字母 B 将变为 D,…,字母 X 变成 Z,字母 Y 则变为 A,字母 Z 变为 B。

凯撒加密,右移2位对应结果图

因此,假如有个明文字符串“Hello”用这种方法加密的话,将变为密文: “Jgnnq” 。而如果要解密,则只要将字母向相反方向移动同样位数即可。如密文“Jgnnq”每个字母左移两位 变为“Hello” 。这里,移动的位数“2”是加密和解密所用的密钥。

示例 /** * 凯撒加密 * @author jijs */ public class CaesarDemo { public static String caesar(String s, int offset) throws Exception { String cipher = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c >= 'a' && c 'z') c -= 26; // 向右超界 } else if (c >= 'A' && c 'Z') c -= 26; } cipher += c; } return cipher; } public static void main(String args[]) throws Exception { String cipher = caesar("Hello", 2); String text = caesar(cipher, -2); System.out.println("原文:Hello\r\n加密后:" + cipher + "\r\n解密后:" + text); } }

该程序既可用于加密又可用于解密。只要传入明文和偏移量即可加密,解密需要传入密文和负的偏移量就可以解密。

输出的结果:

原文:Hello 加密后:Jgnnq 解密后:Hello

安全性

凯撒密码由于加解密比较简单,密钥总共只有 26 个,攻击者得到密文后即使不知道密钥,也可一个一个地试过去,最多试 26 次就可以得到明文。

凯撒变种 /** * 凯撒加密 * @author jijs */ public class CaesarDemo2 { public static String caesar(String s, int offset) throws Exception { String cipher = ""; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // 是小写字母 if (c >= 'a' && c 0) { // 这里不光根据 offset 进行加密,还添加了该元素的下标进行加密。 c += (offset + i) % 26; } else { // 这里不光根据 offset 进行加密,还添加了该元素的下标进行加密。 c += (offset - i) % 26; } if (c < 'a') c += 26; // 向左超界 if (c > 'z') c -= 26; // 向右超界 } // 是大写字母 else if (c >= 'A' && c 0) { // 这里不光根据 offset 进行加密,还添加了该元素的下标进行加密。 c += (offset + i) % 26; } else { // 这里不光根据 offset 进行加密,还添加了该元素的下标进行加密。 c += (offset - i) % 26; } if (c < 'A') c += 26; if (c > 'Z') c -= 26; } cipher += c; } return cipher; } public static void main(String args[]) throws Exception { String cipher = caesar("Hello", 2); String text = caesar(cipher, -2); System.out.println("原文:Hello\r\n加密后:" + cipher + "\r\n解密后:" + text); } }

这里不光根据 offset 偏移进行加密,还加上了字符所在的下标进行混合加密。

输出的结果:

原文:Hello 加密后:Jhpqu 解密后:Hello

想了解更多精彩内容请关注我的公众号 本人简书blog地址:http://www.jianshu.com/u/1f0067e24ff8     点击这里快速进入简书 GIT地址:http://git.oschina.net/brucekankan/ 点击这里快速进入GIT



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有