復制代碼 代碼如下:
var Vigenere = {
_strCpr: 'abcdefghijklmnopqrstuvwxyz_12345 67890.ABCDEFGHIJKLMNOPQRSTUVWXYZ',//可以將此字符串的順序打亂點,或者添加更多字符
_strKey: function(strK,str){//生成密鑰字符串,strK為密鑰,str為明文或者密文
var lenStrK = strK.length;
var lenStr = str.length;
if(lenStrK != lenStr){//如果密鑰長度與str不同,則需要生成密鑰字符串
if(lenStrK < lenStr){//如果密鑰長度比str短,則以不斷重復密鑰的方式生成密鑰字符串
while(lenStrK < lenStr){
strK = strK + strK;
lenStrK = 2 * lenStrK;
}
}//此時,密鑰字符串的長度大於或等於str長度
strK = strK.substring(0,lenStr);//將密鑰字符串截取為與str等長的字符串
}
return strK;
}
}
Vigenere.lenCpr = Vigenere._strCpr.length;
Vigenere.Encrypt = function(K,P){//加密算法,K為密鑰,P為明文
K = Vigenere._strKey(K,P);
var lenK = K.length;
var rlt = '';
var loop = 0;
for(loop=0; loop<lenK; loop++){
var iP = Vigenere._strCpr.indexOf(P.charAt(loop));
if(iP==-1) return '本算法暫時不能對字符:' + P.charAt(loop) + '進行加密';
var iK = Vigenere._strCpr.indexOf(K.charAt(loop));
if(iK==-1) return '密鑰中包含非法字符:' + 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; loop<lenK; loop++){
var iK = Vigenere._strCpr.indexOf(K.charAt(loop));
if(iK==-1) return '密鑰中包含非法字符:' + 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;
};