Skip to content

Instantly share code, notes, and snippets.

@yantze
Created October 19, 2018 01:09
Show Gist options
  • Save yantze/3632ceb3db5bf3fa8833c0d842637664 to your computer and use it in GitHub Desktop.
Save yantze/3632ceb3db5bf3fa8833c0d842637664 to your computer and use it in GitHub Desktop.
简单的凯撒加解密,移位算法
/**
* 凯撒加解密
*/
// 这里的 26 是必须的,否则导致解密溢出
const num = ~~(Math.random() * 100) % 26
const event = "simple world!"
const MIN = "A".charCodeAt(0)
const MAX = "Z".charCodeAt(0)
let eventR = String.fromCharCode.apply(
null,
event
.toUpperCase()
.split("")
.map(e => {
const charCode = e.charCodeAt(0)
if (charCode >= MIN && charCode <= MAX) {
return ((charCode + num - MIN) % 26) + MIN
} else {
return charCode
}
}),
)
console.log("eventR:", eventR)
let ret = String.fromCharCode.apply(
null,
eventR
.toUpperCase()
.split("")
.map(e => {
const charCode = e.charCodeAt(0)
if (charCode >= MIN && charCode <= MAX) {
// charCode = 65
return ((charCode - MIN - num * 1 + 26) % 26) + MIN
} else {
return charCode
}
}),
)
console.log("ret:", ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment