凯撒密码的 js 实现

最近看到了凯撒密码,挺适合编程实现的。比如有一个密文是:PELCGBTENCUL,那他表示的明文是什么呢?

let code = 'PELCGBTENCUL'
decode(code)

function decode(code) {
    let charCodeOfZ = 'Z'.charCodeAt(0)
    let charCodeOfa = 'a'.charCodeAt(0)
    
    for(let i = 0; i <= 25; i++) { // 凯撒密码的密钥是平移字母
        let real = ''
        
        for(let c of code) {
            let cCode = c.charCodeAt(0)
            let toZ = (charCodeOfZ - cCode + 1) // 当前字母距离 Z 的距离
    
            if (i < toZ) {
                real += String.fromCharCode(cCode + 32 + i)
            } else {
                real += String.fromCharCode(charCodeOfa + i - toZ)
            }
        }

        console.log(real)
    
    }
}

上面编码的输出是:

pelcgbtencul
qfmdhcufodvm
rgneidvgpewn
shofjewhqfxo
tipgkfxirgyp
ujqhlgyjshzq
vkrimhzktiar
wlsjnialujbs
xmtkojbmvkct
ynulpkcnwldu
zovmqldoxmev
apwnrmepynfw
bqxosnfqzogx
cryptography // 可以看到这是我们想要的
dszquphsbqiz
etarvqitcrja
fubswrjudskb
gvctxskvetlc
hwduytlwfumd
ixevzumxgvne
jyfwavnyhwof
kzgxbwozixpg
lahycxpajyqh
mbizdyqbkzri
ncjaezrclasj
odkbfasdmbtk

上面是解密的过程,那加密的过程是怎样的呢?我们想对字符串:youarehired,进行加密,那加密后的密文是?

function encode(code) {
    let charCodeOfz = 'z'.charCodeAt(0)
    let charCodeOfA = 'A'.charCodeAt(0)
    
    for(let i = 0; i <= 25; i++) {
        let real = ''
        
        for(let c of code) {
            let cCode = c.charCodeAt(0)
            let toZ = (charCodeOfz - cCode + 1)        
    
            if (i < toZ) {
                real += String.fromCharCode(cCode - 32 + i)
            } else {
                real += String.fromCharCode(charCodeOfA + i - toZ)
            }
        }

        console.log(real)
    
    }
}

用上述代码,当我们执行:encode(‘youarehired’) 时,有 26 个输出,我们随便取一个:HXDJANQRANM,再解码这个密文,就能得到明文了。

Author: 曾小乱

喜欢写点有意思的东西

Leave a Reply

Your email address will not be published. Required fields are marked *