JS实现维吉尼亚加解密
一、原理:
二、加密方法:
加密公式:C = (P + K)%26
C:密文
P:原文
K:第几套加密方式
使用第几套加密方式是通过约定一个规则来确定的,这个规则就是“密钥”。
解密方法:
解密公式:P = (C - K)%26
C:密文
P:原文
K:第几套加密方式
如果P<0,P+26取得正序
三、代码实践
一、加密:
//加密
function wiginiya_encrypt() {
//C = P + K (mod 26). 获取偏移量索引
let key = document.wiginiya.key.value;
let plaintext = document.wiginiya.plaintext.value;
let ciphertext = "";
// do the encoding
let kpos = 0;
for( let i = 0; i < plaintext.length; i ++ ) {
let Kcode = key.charCodeAt( kpos % key.length );
let Pcode = plaintext.charCodeAt( i );
let Ccode = Pcode;
if ( Pcode >= 65 && Pcode <= 90 ) {
if ( Kcode >= 65 && Kcode <= 90 ) {
Ccode = ( ( Kcode - 65 ) + ( Pcode - 65 ) ) % 26 + 65;
}
if ( Kcode >= 97 && Kcode <= 122 ) {
Ccode = ( ( Kcode - 97 ) + ( Pcode - 65 ) ) % 26 + 65;
}
kpos ++; //伴随长度变化
}
if ( Pcode >= 97 && Pcode <= 122 ) {
if ( Kcode >= 65 && Kcode <= 90 ) {
Ccode = ( ( Kcode - 65 ) + ( Pcode - 97 ) ) % 26 + 97;
}
if ( Kcode >= 97 && Kcode <= 122 ) {
Ccode = ( ( Kcode - 97 ) + ( Pcode - 97 ) ) % 26 + 97;
}
kpos ++;
}
ciphertext += String.fromCharCode(Ccode);
}
document.wiginiya.ciphertext.value = ciphertext;
}
二、解密:
//解密
function wiginiya_decrypt() {
//P = C - K (mod 26). 模逆运算求索引
let key = document.wiginiya.key.value;
let ciphertext = document.wiginiya.ciphertext.value;
let plaintext = "";
// do the encoding
let kpos = 0;
for( let i = 0; i < ciphertext.length; i ++ ) {
let Kcode = key.charCodeAt( kpos % key.length );
var Ccode = ciphertext.charCodeAt( i );
var Pcode = Ccode;
if ( Ccode >= 65 && Ccode <= 90 ) {
if (Kcode >= 65 && Kcode <= 90) {
Pcode = ( ( Ccode - 65 ) - ( Kcode - 65 ) + 26 ) % 26 + 65;
}
if ( Kcode >= 97 && Kcode <= 122 ) {
Pcode = ( ( Ccode - 65 ) - ( Kcode - 97 ) + 26 ) % 26 + 65;
}
kpos ++;
}
if ( Ccode >= 97 && Ccode <= 122 ) {
if ( Kcode >= 65 && Kcode <= 90 ) {
Pcode = ( ( Ccode - 97 ) - ( Kcode - 65 ) + 26 ) % 26 + 97;
}
if ( Kcode >= 97 && Kcode <= 122) {
Pcode = ( ( Ccode - 97 ) - ( Kcode - 97 ) + 26 ) % 26 + 97;
}
kpos ++;
}
plaintext += String.fromCharCode(Pcode);
}
document.wiginiya.plaintext.value = plaintext;
}