← 목록으로

C# DES 알고리즘으로 문자열 암호화 및 복호화 구현하기

애플리케이션을 개발하다 보면 비밀번호, 인증 정보 또는 중요한 데이터를 안전하게 저장하거나 전송해야 하는 경우가 있습니다. 이번 포스팅에서는 C#에서 DES(Data Encryption Standard) 알고리즘을 활용하여 문자열을 암호화(Encrypt)하고 복호화(Decrypt)하는 방법을 소개합니다.

참고: DES는 오래된 암호화 방식으로 현재는 보안상 AES 사용이 권장됩니다. 다만 기존 시스템 유지보수나 레거시 환경에서는 아직 사용되는 경우가 있습니다.

DES란?

DES(Data Encryption Standard)는 대칭키(Symmetric Key) 암호화 알고리즘입니다.

특징

  • 암호화와 복호화에 동일한 키 사용
  • 키 길이: 8Byte(64Bit)
  • 구현이 간단함
  • 현재는 보안상 취약점이 발견되어 신규 개발에서는 AES 권장

DES 암호화/복호화 클래스 구현

아래 클래스는 문자열을 DES 방식으로 암호화 및 복호화하는 기능을 제공합니다.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Security.Cryptography; 
using System.IO; 

/// <summary>
/// Summary description for Des 
/// </summary>
public class Des 
{ 
    byte[] key = null; 
    protected Des() 
    { 
    } 

    public Des(byte[] desKey) 
    { 
        this.key = desKey; 
    } 

    public string Encrypt(string plain_text) 
    { 
        if (string.IsNullOrEmpty(plain_text)) 
        { 
            throw new ArgumentException("The string which needs to be encrypted can not be null."); 
        } 
        if (key.Length != 8) 
        { 
            throw (new Exception("Invalid key. Key length must be 8 byte.")); 
        } 
        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); 
        MemoryStream memoryStream = new MemoryStream(); 
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write); 
        StreamWriter writer = new StreamWriter(cryptoStream); 
        writer.Write(plain_text); 
        writer.Flush(); 
        cryptoStream.FlushFinalBlock(); 
        writer.Flush(); 
        string cypher_text = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length); 
        return cypher_text; 
    } 

    public string Decrypt(string cypher_text) 
    { 
        if (String.IsNullOrEmpty(cypher_text)) 
        { 
            throw new ArgumentNullException("The string which needs to be decrypted can not be null."); 
        } 

        if (key.Length != 8) 
        { 
            throw (new Exception("Invalid key. Key length must be 8 byte.")); 
        } 

        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); 
        MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(cypher_text)); 
        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(key, key), CryptoStreamMode.Read); 
        StreamReader reader = new StreamReader(cryptoStream); 
        string plain_text = reader.ReadToEnd(); 
        return plain_text; 
    } 
}

사용 방법

먼저 8Byte 길이의 DES 키를 준비합니다.

using System.Text;

static byte[] desKey =
    ASCIIEncoding.ASCII.GetBytes("DES_KEY1");

DES 객체를 생성한 후 암호화 및 복호화를 수행합니다.

Des des = new Des(desKey);

// 암호화
string encryptedText =
    des.Encrypt("암호화할 문장");

Console.WriteLine(encryptedText);

// 복호화
string decryptedText =
    des.Decrypt(encryptedText);

Console.WriteLine(decryptedText);

코드 설명

Encrypt()

Encrypt() 메서드는 다음 순서로 동작합니다.

  1. 입력 문자열 검증
  2. DES 키 길이 확인
  3. DES 암호화 객체 생성
  4. 문자열 암호화 수행
  5. Base64 문자열로 변환 후 반환

Decrypt()

Decrypt() 메서드는 다음 순서로 동작합니다.

  1. Base64 문자열을 Byte 배열로 변환
  2. DES 복호화 객체 생성
  3. 문자열 복호화 수행
  4. 원본 문자열 반환

주의 사항

현재 예제에서는 아래 코드가 사용됩니다.

cryptoProvider.CreateEncryptor(key, key);

여기서 키(Key)와 IV(초기화 벡터)를 동일하게 사용하고 있습니다.

실제 운영 환경에서는 보안 강화를 위해 다음 사항을 권장합니다.

  • Key와 IV를 분리하여 사용
  • DES 대신 AES 사용
  • 암호화 키를 소스 코드에 직접 저장하지 않기
  • 키 관리 시스템 활용

마무리

이번 포스팅에서는 C#에서 DES 알고리즘을 이용한 문자열 암호화 및 복호화 구현 방법을 살펴보았습니다. 구현 자체는 매우 간단하지만, DES는 현재 보안성이 낮아 신규 프로젝트에서는 AES 사용을 권장합니다. 다만 레거시 시스템과의 연동이나 기존 솔루션 유지보수 시에는 유용하게 활용할 수 있습니다.

향후에는 AES를 사용한 안전한 문자열 암호화 구현 방법도 함께 소개해보겠습니다.