信息安全概论
凯撒密码算法 ----Javascript实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>古典算法</title>
<script src="./index.js"></script>
</head>
<body>
<div class="all">
<div class="one">
<ul>
<li class="first">
凯撒密码
</li>
<li> <span>输入密匙:</span> <input type="text" name="" id="secretKeyId"></li>
<li> <span>输入明文:</span> <input type="text" name="" id="expressId"></li>
<li> <span>输出密文:</span> <input type="text" name="" id="secretId" disabled></li>
<li><button onclick="caesar()">加密</button> </li>
</ul>
</div>
</div>
<style>
* {
margin: 0;
padding: 0;
list-style: none;
}
html,
body,
.all {
height: 100%;
}
.all {
position: relative;
}
.one {
width: 270px;
height: 150px;
background-color: rgb(138, 138, 138, 0.5);
position: absolute;
left: 50%;
top: 100px;
transform: translate(-50%, -50%);
border-radius: 10px;
}
span {
display: inline-block;
font-size: 10px;
}
.first {
text-align: center;
margin: 8px 0px;
}
li {
padding: 0 10px;
}
li>button {
float: right;
margin-top: 15px;
margin-right: 25px;
}
</style>
</body>
</html>
function caesar() {
var secretKey, expressWords, secretWords;
expressWords = document.getElementById("expressId").value;
secretKey = document.getElementById("secretKeyId").value;
//这里记得把拿到的密钥值从字符串类型转为Number类型
secretKeyNum = Number(secretKey);
var start1 = "A".charCodeAt(0);
var end1 = "Z".charCodeAt(0);
var start2 = "a".charCodeAt(0);
var end2 = "z".charCodeAt(0);
var strList = expressWords.split("");
var judge, replace;
for (var i = 0; i < expressWords.length; i++) {
judge = strList[i].charCodeAt(0);
if (judge <= end1 && judge >= start1) {
replace = start1 + (judge - start1 + secretKeyNum) % 26;
strList[i] = String.fromCharCode(replace);
}
else if (judge <= end2 && judge >= start2) {
replace = start2 + (judge - start2 + secretKeyNum) % 26;
strList[i] = String.fromCharCode(replace);
}
}
secretWords = strList.join("");
document.getElementById('secretId').value = secretWords
}