본문 바로가기

알고리즘 & 자료구조/암호화 알고리즘

[암호학] 단일치환 암호_ROT13 암호

- 알파벳 문자를 13번 Shift 하여 암/복호화를 수행하는 방식

- Shift Key가 13인 시저암호

- A~Z 문자에 대해 NOPQRTUVWXYZABCDEFGHIJKLM 인 매핑텡이블을 갖는다.

    public class ROT13Cipher
    {
        // ROT13 매핑테이블
        private static string ROT = "NOPQRSTUVWXYZABCDERGHIJKLM";

        public static string Encrypt(string message) {
            return Rotate(message);
        }

        public static string Decrypt(string cipher) {
            return Rotate(cipher);
        }

        private static string Rotate(string str)
        {
            char[] a = str.ToCharArray();

            for (int i = 0; i < a.Length; i++) {
                a[i] = (a[i] == ' ') ? ' ' : ROT[a[i] - 'A'];
            }

            return new string(a);
        }

        internal static void HowToTest() {
            string message = "ATTACK WEST CASTLE";
            string cipher = ROT13Cipher.Encrypt(message);
            string plain = ROT13Cipher.Decrypt(cipher);

            Console.WriteLine($"{message}, {cipher}, {plain}");
            Debug.Assert(message == plain);
        }
    }

- 메인메소드

        static void Main(string[] args)
        {
            // 시저 암호
            CaesarCipher caesarCipher = new CaesarCipher();
            var encryptStr = caesarCipher.Encrypt("HELLO");
            var decryptStr = caesarCipher.Decrypt(encryptStr);

            Console.WriteLine("Caesar 암호화:" + encryptStr);
            Console.WriteLine("Caesar 복호화:" + decryptStr);

            var encryptRot13Str = ROT13Cipher.Encrypt("HELLO");
            var decryptRot13Str = ROT13Cipher.Decrypt(encryptStr);

            Console.WriteLine("ROT13 암호화:" + encryptRot13Str);
            Console.WriteLine("ROT13 복호화:" + decryptRot13Str);
        }

- 결과