hill cipher in matlab

Here is an example of how to implement the Hill cipher encryption and decryption in MATLAB:

main.m
% Hill Cipher Encryption and Decryption

% Function to get the inverse mod 26
function invModVal = inverseMod(modValue)
    invModVal = -1;
    for i = 1:26
        if mod(modValue * i, 26) == 1
            invModVal = i;
            break;
        end
    end
end

% Function to encrypt using Hill cipher
function cipherText = hillCipherEncrypt(plainText, keyMatrix)
    % Convert the plain text to numbers (A => 0, B => 1, etc.)
    plainText = upper(plainText) - 'A';
    
    % Pad the plain text with 'X' if its length is not a multiple of the key matrix size
    if mod(length(plainText), size(keyMatrix, 1)) ~= 0
        plainText = [plainText; repmat(23, size(keyMatrix, 1) - mod(length(plainText), size(keyMatrix, 1)), 1)];
    end
    
    % Reshape the plain text into a matrix
    plainTextMatrix = reshape(plainText, size(keyMatrix, 1), []);
    
    % Encrypt each block of the plain text
    cipherTextMatrix = mod(keyMatrix * plainTextMatrix, 26);
    
    % Convert the cipher text to characters
    cipherText = char(cipherTextMatrix + 'A');
end

% Function to decrypt using Hill cipher
function plainText = hillCipherDecrypt(cipherText, keyMatrix)
    % Convert the cipher text to numbers (A => 0, B => 1, etc.)
    cipherText = upper(cipherText) - 'A';
    
    % Reshape the cipher text into a matrix
    cipherTextMatrix = reshape(cipherText, size(keyMatrix, 1), []);
    
    % Compute the inverse of the key matrix mod 26
    keyMatrixInvMod = mod(round(det(keyMatrix) * inverseMod(round(det(keyMatrix)))), 26) * inv(keyMatrix);
    
    % Decrypt each block of the cipher text
    plainTextMatrix = mod(keyMatrixInvMod * cipherTextMatrix, 26);
    
    % Convert the plain text to characters
    plainText = char(plainTextMatrix + 'A');
end

% Example usage
plainText = 'HELLO';                                % Plain text
keyMatrix = [6, 24, 1; 13, 16, 10; 20, 17, 15];      % Key matrix

cipherText = hillCipherEncrypt(plainText, keyMatrix);         % Encrypt the plain text
decryptedText = hillCipherDecrypt(cipherText, keyMatrix);     % Decrypt the cipher text

disp(['Plain Text:    ', plainText]);
disp(['Cipher Text:   ', cipherText]);
disp(['Decrypted Text:', decryptedText]);
2210 chars
62 lines

In the example above, the plain text "HELLO" is encrypted using a key matrix [6, 24, 1; 13, 16, 10; 20, 17, 15]. The resulting cipher text is then decrypted back to the original plain text using the same key matrix.

Note: The key matrix should be invertible modulo 26 for the Hill cipher to work correctly.

Please note that this implementation assumes that the input plain text only contains uppercase letters and does not account for spaces or other special characters. You can modify the code to handle these cases as per your requirements.

I hope this helps!

gistlibby LogSnag