Name: Aaima Faisal Seat No: B21110106001
Hill Cipher Algorithm
Hill cipher is a polygraphic substitution cipher based on linear algebra.Each letter is represented
by a number modulo 26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used, but this is not
an essential feature of the cipher. To encrypt a message, each block of n letters (considered as
an n-component vector) is multiplied by an invertible n × n matrix, against modulus 26. To
decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
The matrix used for encryption is the cipher key, and it should be chosen randomly from the set
of invertible n × n matrices (modulo 26).
Name: Aaima Faisal Seat No: B21110106001
Practical # 7
Objective:
Write a program for Hill Cipher.
Source Code:
document.getElementById('process-btn').addEventListener('click', function() {
const message = document.getElementById('message').value.replace(/[^a-zA-Z]/g,
'').toUpperCase();
const keyInput = document.getElementById('key').value;
const keyMatrix = parseKeyMatrix(keyInput);
const encodeMode = document.getElementById('encode-mode').checked;
if (message.length === 0 || keyMatrix === null) {
alert('Please enter a valid message and a valid 2x2 key matrix.');
return;
}
const result = encodeMode ? hillEncrypt(message, keyMatrix) : hillDecrypt(message,
keyMatrix);
document.getElementById('output').value = result;
});
function parseKeyMatrix(key) {
const values = key.split(',').map(Number);
if (values.length !== 4 || values.some(isNaN)) return null;
return [[values[0], values[1]], [values[2], values[3]]];
}
Name: Aaima Faisal Seat No: B21110106001
function hillEncrypt(text, key) {
let result = '';
const mod = 26;
for (let i = 0; i < text.length; i += 2) {
const char1 = text.charCodeAt(i) - 65;
const char2 = (i + 1 < text.length) ? text.charCodeAt(i + 1) - 65 : 0;
const encrypted1 = (char1 * key[0][0] + char2 * key[0][1]) % mod;
const encrypted2 = (char1 * key[1][0] + char2 * key[1][1]) % mod;
result += String.fromCharCode(encrypted1 + 65) + String.fromCharCode(encrypted2 + 65);
}
return result;
function hillDecrypt(text, key) {
const det = (key[0][0] * key[1][1] - key[0][1] * key[1][0]) % 26;
const modInverse = modInverse26(det);
if (modInverse === -1) {
alert("Key matrix is not invertible under modulo 26.");
return '';
const invKey = [
[(key[1][1] * modInverse) % 26, (-key[0][1] * modInverse) % 26],
[(-key[1][0] * modInverse) % 26, (key[0][0] * modInverse) % 26]
].map(row => row.map(v => (v + 26) % 26));
Name: Aaima Faisal Seat No: B21110106001
return hillEncrypt(text, invKey);
}
function modInverse26(n) {
for (let i = 1; i < 26; i++) {
if ((n * i) % 26 === 1) return i;
return -1;
Output:
Name: Aaima Faisal Seat No: B21110106001