2015년 8월 10일 월요일

C# AES 암호화 적용

공개키 암호화가 아무리 보안에 좋다지만, 상호 통신이 아닌 데이터 저장용이라면 역시 간단한 암호화가 편하다.


요렇게 화면을 간단히 구성.


대충 요런 형태가 되고.

소스는 이렇게...

[Encrypt.aspx.cs]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.IO;
using System.Security.Cryptography;
using System.Text;

public partial class web_member_Encrypt : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {    }
    
    protected void btnEncrypt_Click(object sender, EventArgs e)
    {
        txtResult.Text = Encrypt_AES(txtInput.Text, "---This is Key Value---");
    }

    protected void btnDecrypt_Click(object sender, EventArgs e)
    {
        txtDecrypt.Text = Decrypt_AES(txtResult.Text, "---This is Key Value---");
    }


    public String Encrypt_AES(String InputText, String setKey)
    {
        RijndaelManaged aes = new RijndaelManaged();
        byte[] Salt = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        byte[] prcText = System.Text.Encoding.Unicode.GetBytes(InputText);

        Rfc2898DeriveBytes SecretKey = new Rfc2898DeriveBytes(setKey, Salt, 100);
        ICryptoTransform Encryptor = aes.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(prcText, 0, prcText.Length);
        cryptoStream.FlushFinalBlock();

        byte[] CipherBytes = memoryStream.ToArray();
        string EncryptedData = Convert.ToBase64String(CipherBytes);

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

        return EncryptedData;
    }

    public String Decrypt_AES(String InputText, String setKey)
    {
        RijndaelManaged aes = new RijndaelManaged();
        byte[] Salt = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
        byte[] EncryptedData = Convert.FromBase64String(InputText);
        byte[] prcText = new byte[EncryptedData.Length];

        Rfc2898DeriveBytes SecretKey = new Rfc2898DeriveBytes(setKey, Salt, 100);
        ICryptoTransform Decryptor = aes.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

        MemoryStream memoryStream = new MemoryStream(EncryptedData);
        CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

        int DecryptedCount = cryptoStream.Read(prcText, 0, prcText.Length);
        string DecryptedData = Encoding.Unicode.GetString(prcText, 0, DecryptedCount);

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

        return DecryptedData;
    }  
}

하면....


위에 암호화 할 문자열을 넣고, "암호화" 를 클릭하면...


저렇게 암호화 된 문자열이 나오고, 여기서 다시 "복호화" 버튼을 클릭하면...


이렇게 원래 문자열이 다시 나온다.