펌:
http://www.codeproject.com/KB/cs/NET_Encrypt_Decrypt.aspx
C#으로 구현된 DES 알고리즘에 대해서 찾다가..
Code project에 구현되어있는 내용을 가져왔다.
Console.ReadLine()을 통해서 암호화할 문자를 가져와 Encrypt에서 암호화를 하고 Decrypt에서 복호화를 진행한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace EncryptAndDecrypt
{
class Program
{
static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("ZeroCool");
static void Main(string[] args)
{
try
{
while (true)
{
Console.WriteLine("Original String: ");
string originalString = Console.ReadLine();
string cryptedString = Encrypt(originalString);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\nEncrypt Result: {0}", cryptedString);
Console.WriteLine("Decrypt Result: {0}", Decrypt(cryptedString));
}
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("From: {0}.\nDetail: {1}", ex.Source, ex.Message);
}
finally
{
Console.ReadLine();
}
}
public static string Encrypt(string originalString)
{
if (String.IsNullOrEmpty(originalString))
{
throw new ArgumentNullException("The string which needs to be encrypted can not be null.");
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write(originalString);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
public static string Decrypt(string cryptedString)
{
if (String.IsNullOrEmpty(cryptedString))
{
throw new ArgumentNullException("The string which needs to be decrypted can not be null.");
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString));
CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cryptoStream);
return reader.ReadToEnd();
}
}
}