forked from bellshade/Javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
affine.js
73 lines (63 loc) · 1.97 KB
/
affine.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
Implementasi metode Affine Cipher
Affine Cipher adalah jenis cipher substitusi monoalphabetic , di mana setiap huruf dalam alfabet dipetakan ke padanan numeriknya, dienkripsi menggunakan fungsi matematika sederhana, dan dikonversi kembali menjadi huruf.
Rumus enkripsi
C = aP + b mod n
Rumus dekripsi
P = a^-1 * (C - b) mod n
Keterangan:
a = bilangan bulat relatif prima dengan "n"
P = letak alphabet
b = jumlah pergeseran
n = jumlah alphabet (26)
m^-1 = invers m mod n
Baca selengkapnya
https://en.m.wikipedia.org/wiki/Affine_cipher
*/
function affineCipher(method, string) {
let a = 5;
let b = 7;
let n = 26;
function encrypt(char, isUpperCase) {
const p = char.charCodeAt() - 97;
const c = ((a * p + b) % n) + 97;
return isUpperCase
? String.fromCharCode(c).toUpperCase()
: String.fromCharCode(c);
}
function decrypt(char, isUpperCase) {
let multinverse = 1;
for (let i = 1; i <= 25; i = i + 2) {
if ((a * i) % n === 1) {
multinverse = i;
}
}
const c = char.charCodeAt() - 97;
const p = ((multinverse * Math.abs(c + n - b)) % n) + 97;
return isUpperCase
? String.fromCharCode(p).toUpperCase()
: String.fromCharCode(p);
}
let isUpperCase = false;
if (method === "encrypt" || method === "decrypt") {
if (string) {
return [...string]
.map((char) => {
if (char.match(/[a-zA-Z]/)) {
isUpperCase = char === char.toUpperCase();
return method === "encrypt"
? encrypt(char.toLowerCase(), isUpperCase)
: decrypt(char.toLowerCase(), isUpperCase);
}
return char;
})
.join("");
}
return "Text not found!";
}
return "Method not found!";
}
const encrypted = affineCipher("encrypt", "abcdefghijklmnopqrstuvwxyz");
const decrypted = affineCipher("decrypt", encrypted);
console.log(encrypted);
console.log(decrypted);