c# 암호화 복호화 예제

EncryptString(암호키, 암호화할 문자열);

 

        private static string EncryptString(string InputText, string KeyString)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
            byte[] PlainText = Encoding.Unicode.GetBytes(InputText);
            byte[] Salt = Encoding.ASCII.GetBytes(KeyString.Length.ToString());
            PasswordDeriveBytes SecureKey = new PasswordDeriveBytes(KeyString, Salt);

            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecureKey.GetBytes(32), SecureKey.GetBytes(16));
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);

            cryptoStream.Write(PlainText, 0, PlainText.Length);
            cryptoStream.FlushFinalBlock();
            byte[] CipherBytes = memoryStream.ToArray();

            memoryStream.Close();
            cryptoStream.Close();

            string EncryptedData = Convert.ToBase64String(CipherBytes);

            return EncryptedData;
        }

 

 

DecryptString(암호키, 복호화할문자열);

        private static string DecryptString(string InputText, string KeyString)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            byte[] EncryptedData = Convert.FromBase64String(InputText);
            byte[] Salt = Encoding.ASCII.GetBytes(KeyString.Length.ToString());

            PasswordDeriveBytes SecureKey = new PasswordDeriveBytes(KeyString, Salt);

            ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecureKey.GetBytes(32), SecureKey.GetBytes(16));
            MemoryStream memoryStream = new MemoryStream(EncryptedData);
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

            byte[] PlainText = new byte[EncryptedData.Length];

            int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);

            memoryStream.Close();
            cryptoStream.Close();

            string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);

            return DecryptedData;
        }