C#, 문자열 암호화, 복호화 예제

C#, 문자열 암호화, 복호화 예제

 

     C# 에서 제공하는 클래스로 간단하게 DES 암호화, 복호화가 가능합니다.

참고로 암호화/복호화에 사용되는 키는 8글자여야 합니다.

 

 

 

public partial class Form1 : Form

{

//암호화 복호화 키 8글자 (필히 8자리여야 함)

WATCrypt m_crypt = new WATCrypt(“11111111”);

public Form1()

{

InitializeComponent();

}

 

private void btnInDES_Click(object sender, EventArgs e)

{

// 암호화

txbOutput.Text = m_crypt.Encrypt(txbInput.Text);

}

 

private void btnDeDES_Click(object sender, EventArgs e)

{

// 복호화

txbDeDES.Text = m_crypt.Decrypt(txbOutput.Text);

}

 

 

}

class WATCrypt

{

byte[] Skey = new byte[8];

public WATCrypt(string strKey)

{

Skey = ASCIIEncoding.ASCII.GetBytes(strKey);

}

 

public string Encrypt(string p_data)

{

if (Skey.Length != 8)

{

throw (new Exception(“Invalid key. Key length must be 8 byte.”));

}

 

DESCryptoServiceProvider rc2 = new DESCryptoServiceProvider();

 

rc2.Key = Skey;

rc2.IV = Skey;

 

MemoryStream ms = new MemoryStream();

CryptoStream cryStream = new CryptoStream(ms, rc2.CreateEncryptor(), CryptoStreamMode.Write);

byte[] data = Encoding.UTF8.GetBytes(p_data.ToCharArray());

 

cryStream.Write(data, 0, data.Length);

cryStream.FlushFinalBlock();

 

return Convert.ToBase64String(ms.ToArray());

}

 

public string Decrypt(string p_data)

{

DESCryptoServiceProvider rc2 = new DESCryptoServiceProvider();

 

rc2.Key = Skey;

rc2.IV = Skey;

 

MemoryStream ms = new MemoryStream();

CryptoStream cryStream = new CryptoStream(ms, rc2.CreateDecryptor(), CryptoStreamMode.Write);

byte[] data = Convert.FromBase64String(p_data);

 

cryStream.Write(data, 0, data.Length);

cryStream.FlushFinalBlock();

 

return Encoding.UTF8.GetString(ms.GetBuffer());

}

}

 

 

 

 


Leave a Comment