Home >Web Front-end >JS Tutorial >JS Virginia Cipher Algorithm Implementation Code_javascript skills

JS Virginia Cipher Algorithm Implementation Code_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:16:381252browse
Copy code The code is as follows:

var Vigenere = {
_strCpr: 'abcdefghijklmnopqrstuvwxyz_12345 67890.ABCDEFGHIJKLMNOP QRSTUVWXYZ' ,//You can disrupt the order of this string, or add more characters
_strKey: function(strK,str){//Generate a key string, strK is the key, str is plain text or cipher text
var lenStrK = strK.length;
var lenStr = str.length;
if(lenStrK != lenStr){//If the key length is different from str, you need to generate the key string
if(lenStrK < lenStr){//If the key length is shorter than str, generate the key string by continuously repeating the key
while(lenStrK < lenStr){
strK = strK strK ;
lenStrK = 2 * lenStrK;
}
}//At this time, the length of the key string is greater than or equal to the length of str
strK = strK.substring(0,lenStr);// Truncate the key string into a string of the same length as str
}
return strK;
}
}

Vigenere.lenCpr = Vigenere._strCpr.length;

Vigenere.Encrypt = function(K,P){//Encryption algorithm, K is the key, P is the plaintext
K = Vigenere._strKey(K,P);
var lenK = K. length;
var rlt = '';
var loop = 0;
for(loop=0; loopvar iP = Vigenere._strCpr.indexOf(P.charAt (loop));
if(iP==-1) return 'This algorithm cannot currently encrypt the character: ' P.charAt(loop) ';
var iK = Vigenere._strCpr.indexOf(K .charAt(loop));
if(iK==-1) return 'The key contains illegal characters:' K.charAt(loop);
var i = (iP iK) % Vigenere.lenCpr;
rlt = rlt Vigenere._strCpr.charAt(i);
}
return rlt;
};

Vigenere.DisEncrypt = function(K,C){
K = Vigenere._strKey(K,C);
var lenK = K.length;
var rlt = '';
var loop = 0;
for(loop=0; loopvar iK = Vigenere._strCpr.indexOf(K.charAt(loop));
if(iK==-1) return 'The key contains illegal characters:' K.charAt(loop );
var iC = Vigenere._strCpr.indexOf(C.charAt(loop));
if(iK > iC){
rlt = Vigenere._strCpr.charAt(iC Vigenere.lenCpr - iK );
}
else{
rlt = Vigenere._strCpr.charAt(iC - iK);
}
}
return rlt;
};
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn