为了解密和仿射给定 a 和 b 的密码,您需要使用 Dk = a^-1(y-b) mod m 其中 m 取决于您当前使用的字母表(英语 26、意大利语 21...)、a^-1 = m-a 和 k = (a, b)。
例如,a=7 和 b=8 的 vczkh 被解密为 nqlmh 给定a^-1 = m - a = 26 - 7 = 19
所以对于v,因为v 在英文字母表中的位置21:
v -> 19(21-8) mod 26 -> 247 mod 26 -> 13 对应于n
Here's 我写的 Javascript 脚本
//Getting Args from console
var args = {
"operation" : process.argv[2],
"a" : parseInt(process.argv[3]),
"b" : parseInt(process.argv[4]),
"word" : process.argv[5]
};
var encryptedWord = [];
var decryptedWord = [];
if(!args.operation || !args.a || !args.b || !args.word){
console.log("Arguments are missing, please, use: node \"encrypt/decrypt\" a b word");
return;
} else {
if(typeof args.a === 'number' || typeof args.b === 'number'){
if(typeof args.word !== 'string'){
console.log("Word must be a string");
return;
} else {
// If a and m are coprimes
if(gcdCalc(args.a, 26) === 1){
if(args.operation === "encrypt"){
encryptWord().then(function(encrWord){
console.log("Word "+args.word+" got encrypted into "+encrWord);
});
} else if(args.operation === "decrypt"){
decryptWord().then(function(decrWord){
console.log("Ciphetext "+args.word+" got decrypted into "+decrWord);
});
} else {
console.log("Invalid operation specified. Use encrypt or decrypt.");
return;
}
} else {
console.log("a "+args.a+ " and m 26 are not coprimes");
return;
}
}
} else {
console.log("You must assign an Integer number to a and b. Remember that a must be coprime with m (26)");
return;
}
}
function gcdCalc(a, b) {
if (b) {
return gcdCalc(b, a % b);
} else {
return Math.abs(a);
}
};
function encryptWord(){
return new Promise( function(resolve){
var chars = args.word.split("");
var currInt = 0;
var currEnc = "";
chars.forEach( function( currChar){
currInt = parseInt(currChar, 36) - 10;
// E(a,b)(n) = an + b mod 26
currEnc = mod((args.a * currInt + args.b), 26);
encryptedWord.push(String.fromCharCode(97 + currEnc));
});
return resolve(encryptedWord.join(""));
});
}
function decryptWord(){
return new Promise( function(resolve){
var chars = args.word.split("");
var currInt = 0;
var currEnc = "";
//a^-1 = m - a
var a_1 = 26 - args.a;
chars.forEach( function( currChar){
currInt = parseInt(currChar, 36) - 10;
// D(y) = a^-1 * (y - b) mod 26
currEnc = mod((a_1 * (currInt - args.b)), 26);
decryptedWord.push(String.fromCharCode(97 + currEnc));
});
return resolve(decryptedWord.join(""));
});
}
function mod(n, m) {
var remain = n % m;
return Math.floor(remain >= 0 ? remain : remain + m);
};
要运行它,你需要node,然后,你可以使用它:
- 加密:
node affine-cipher.js encrypt 5 8 affine 变为 ihhwvc
- 解密:
node affine-cipher.js decrypt 5 8 ihhwvc 变成 affine
注意a 和m 必须互质。例如gcd(a, m) 必须为 1。
可能的键总数为312,因为a 可能与12 不同的数字不同,这些数字与26 互质,b 可能在所有26 不同的数字中都不同,所以12*26=312 .
希望我对您有所帮助。