2017-11-27 5 views
0

나는이 질문들을 여기서 보았지만 아무도 대답을 내 문제를 해결할 수 없었다. 나는 우리 서버 중 하나에 앉아 Socket과 대화하여 민감한 데이터를 해독하기위한 암호화 키를 얻기 위해 다른 프로그램을 사용하도록 작성했습니다. 아래는 제 코드입니다.AES 암호를 해독하면 "패딩이 유효하지 않으므로 제거 할 수 없습니다." 오류

소켓 서버 :

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

namespace Netgen_Encryption_Socket 
{ 
    class Program 
    { 
     private static IPAddress ip = IPAddress.Parse("127.0.0.1"); 
     private static string encryptionKey = "2387429837498279832"; 
     private static byte[] IV = new byte[] { 23, 243, 29, 26, 78, 67, 23, 62, 81, 93, 12, 205, 217, 10, 216, 13 }; 
     private static byte[] salt = new byte[] { 21, 10, 3, 26, 10, 3, 1, 49, 55, 171, 1, 51, 75, 16, 27, 14, 23, 29, 70, 16, 55, 18, 12, 2, 4, 29, 77, 52, 5, 44, 127, 164 }; 
     private static string masterPassword = "SecretPassword"; 
     private static bool connectionAccepted = true; 

     static void Main(string[] args) => Listen(); 

     static void Listen() 
     { 
      TcpListener serverSocket = new TcpListener(IPAddress.Any, 9843); 
      TcpClient clientSocket = default(TcpClient); 

      int requestCount = 0; 

      serverSocket.Start(); 
      clientSocket = serverSocket.AcceptTcpClient(); 

      if (((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address.ToString() == ip.ToString()) 
      { 
       SendMessage(clientSocket, serverSocket, $"Accepted Connection from {((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address}"); 
       connectionAccepted = true; 
      } 
      else 
      { 
       SendMessage(clientSocket, serverSocket, $"Rejected Connection from {((IPEndPoint)clientSocket.Client.RemoteEndPoint).Address}"); 
       Restart(clientSocket, serverSocket); 
      } 

      while (connectionAccepted) 
      { 
       try 
       { 
        requestCount += 1; 

        if (requestCount >= 4) 
         Restart(clientSocket, serverSocket); 

        string data = GetMessage(clientSocket, serverSocket); 

        if (data == masterPassword) 
        { 
         SendMessage(clientSocket, serverSocket, encryptionKey); 
        } 
        else 
        { 
         SendMessage(clientSocket, serverSocket, $"Invalid master password. {3 - requestCount} attempts remaining!"); 

         if (3 - requestCount <= 0) 
          SendMessage(clientSocket, serverSocket, Environment.NewLine + $"Too many incorrect attempts. Connection terminated!"); 
        } 
       } 
       catch 
       { 
        Restart(clientSocket, serverSocket); 
       } 
      } 

      Stop(clientSocket, serverSocket); 
     } 

     static void Restart(TcpClient client, TcpListener listener) 
     { 
      client.Close(); 
      listener.Stop(); 

      Listen(); 
     } 

     static void Stop(TcpClient client, TcpListener listener) 
     { 
      client.Close(); 
      listener.Stop(); 
     } 

     static string GetMessage(TcpClient client, TcpListener listener) 
     { 
      NetworkStream networkStream = client.GetStream(); 

      byte[] bytesFrom = new byte[client.ReceiveBufferSize]; 
      networkStream.Read(bytesFrom, 0, (int)client.ReceiveBufferSize); 

      string data = Decrypt(bytesFrom); 
      data = data.Substring(0, data.IndexOf("$")); 

      return data; 
     } 

     static void SendMessage(TcpClient client, TcpListener listener, string message) 
     { 
      NetworkStream networkStream = client.GetStream(); 

      byte[] sendBytes = Encrypt(message); 
      networkStream.Write(sendBytes, 0, sendBytes.Length); 
      networkStream.Flush(); 
     } 

     static byte[] Encrypt(string stringToEncrypt) 
     { 
      byte[] encryptedBytes; 

      using(Aes AES = Aes.Create()) 
      { 
       AES.Key = salt; 
       AES.IV = IV; 

       AES.Mode = CipherMode.CBC; 
       AES.Padding = PaddingMode.PKCS7; 

       var encryptor = AES.CreateEncryptor(AES.Key, AES.IV); 

       using(MemoryStream ms = new MemoryStream()) 
       { 
        using(CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) 
        { 
         using(StreamWriter sw = new StreamWriter(cs)) 
         { 
          sw.Write(stringToEncrypt); 
         } 

         encryptedBytes = ms.ToArray(); 

         if (!cs.HasFlushedFinalBlock) 
          cs.FlushFinalBlock(); 
        } 
       } 
      } 

      var combined = new byte[IV.Length + encryptedBytes.Length]; 
      Array.Copy(IV, 0, combined, 0, IV.Length); 
      Array.Copy(encryptedBytes, 0, combined, IV.Length, encryptedBytes.Length); 

      return combined; 
     } 

     static string Decrypt(byte[] bytesToDecrypt) 
     { 
      string decryptedString = null; 

      using(Aes AES = Aes.Create()) 
      { 
       AES.Key = salt; 

       byte[] cipherText = new byte[bytesToDecrypt.Length - IV.Length]; 

       Array.Copy(bytesToDecrypt, IV, IV.Length); 
       Array.Copy(bytesToDecrypt, IV.Length, cipherText, 0, cipherText.Length); 

       AES.IV = IV; 

       AES.Mode = CipherMode.CBC; 
       AES.Padding = PaddingMode.PKCS7; 

       var decryptor = AES.CreateDecryptor(AES.Key, AES.IV); 

       using(MemoryStream ms = new MemoryStream(cipherText)) 
       { 
        using(CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) 
        { 
         using(StreamReader sr = new StreamReader(cs)) 
         { 
          decryptedString = sr.ReadToEnd(); 
         } 
        } 
       } 
      } 

      return decryptedString; 
     } 
    } 
} 

소켓 클라이언트 : 나는 다른 유사한 게시물의 제안의 대부분을 시도

using System; 
using System.Text; 
using System.Windows.Forms; 
using System.Net.Sockets; 
using System.Net; 
using System.IO; 
using System.Security.Cryptography; 

namespace Client_Socket_Tester 
{ 
    public partial class Form1 : Form 
    { 
     TcpClient clientSocket = new TcpClient(); 
     private static byte[] IV = new byte[] { 23, 243, 29, 26, 78, 67, 23, 62, 81, 93, 12, 205, 217, 10, 216, 13 }; 
     private static byte[] salt = new byte[] { 21, 10, 3, 26, 10, 3, 1, 49, 55, 171, 1, 51, 75, 16, 27, 14, 23, 29, 70, 16, 55, 18, 12, 2, 4, 29, 77, 52, 5, 44, 127, 164 }; 

     public Form1() => InitializeComponent(); 

     private void Form1_Load(object sender, EventArgs ev) 
     { 
      try 
      { 
       clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 9843); 
       AppendClientMessage(" >> Connection established"); 
      } 
      catch (Exception e) 
      { 
       AppendClientMessage($" >> Client Error: {e.Message}"); 
      } 
     } 

     private void AppendClientMessage(string msg) 
     { 
      richTextBox1.Text += Environment.NewLine + msg; 
     } 

     private void SendMessage(string msg) 
     { 
      try 
      { 
       byte[] outStream = Encrypt($"{msg}$"); 

       NetworkStream serverStream = clientSocket.GetStream(); 
       serverStream.Write(outStream, 0, outStream.Length); 
       serverStream.Flush(); 

       byte[] inStream = new byte[clientSocket.ReceiveBufferSize]; 
       serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize); 

       string returnData = Decrypt(inStream); 
       AppendClientMessage(returnData); 
       richTextBox2.Text = ""; 
       richTextBox2.Focus(); 
      } 
      catch (Exception e) 
      { 
       AppendClientMessage($" >> Client Error: {e.Message}"); 
      } 
     } 

     private void button1_Click(object sender, EventArgs ev) 
     { 
      try 
      { 
       SendMessage(richTextBox2.Text); 
      } 
      catch (Exception e) 
      { 
       AppendClientMessage($" >> Client Error: {e.Message}"); 
      } 
     } 

     static byte[] Encrypt(string stringToEncrypt) 
     { 
      byte[] encryptedBytes; 

      using (Aes AES = Aes.Create()) 
      { 
       AES.Key = salt; 
       AES.IV = IV; 

       AES.Mode = CipherMode.CBC; 
       AES.Padding = PaddingMode.PKCS7; 

       var encryptor = AES.CreateEncryptor(AES.Key, AES.IV); 

       using (MemoryStream ms = new MemoryStream()) 
       { 
        using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) 
        { 
         using (StreamWriter sw = new StreamWriter(cs)) 
         { 
          sw.Write(stringToEncrypt); 
         } 

         encryptedBytes = ms.ToArray(); 

         if (!cs.HasFlushedFinalBlock) 
          cs.FlushFinalBlock(); 
        } 
       } 
      } 

      var combined = new byte[IV.Length + encryptedBytes.Length]; 
      Array.Copy(IV, 0, combined, 0, IV.Length); 
      Array.Copy(encryptedBytes, 0, combined, IV.Length, encryptedBytes.Length); 

      return combined; 
     } 

     static string Decrypt(byte[] bytesToDecrypt) 
     { 
      string decryptedString = null; 

      using (Aes AES = Aes.Create()) 
      { 
       AES.Key = salt; 

       byte[] cipherText = new byte[bytesToDecrypt.Length - IV.Length]; 

       Array.Copy(bytesToDecrypt, IV, IV.Length); 
       Array.Copy(bytesToDecrypt, IV.Length, cipherText, 0, cipherText.Length); 

       AES.IV = IV; 

       AES.Mode = CipherMode.CBC; 
       AES.Padding = PaddingMode.PKCS7; 

       var decryptor = AES.CreateDecryptor(AES.Key, AES.IV); 

       using (MemoryStream ms = new MemoryStream(cipherText)) 
       { 
        using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) 
        { 
         using (StreamReader sr = new StreamReader(cs)) 
         { 
          decryptedString = sr.ReadToEnd(); 
         } 
        } 
       } 
      } 

      return decryptedString; 
     } 
    } 
} 

. 패딩 모드 변경 및/또는 Base64 로의 변환을 포함합니다. 최종 결과는 항상 인코딩이 엉망이되어 일련의 임의의 문자가 튀어 나오거나 "패딩이 유효하지 않으므로 제거 할 수 없습니다."라는 메시지가 나타납니다. 암호를 해독 할 때 오류가 발생합니다 (클라이언트 측).

도움이 될 것입니다.

감사합니다.

+0

확인이 : https://stackoverflow.com/questions/8583112/padding-is-invalid-and-can not-will-removed-will-do- 제거 할 수 없음 – Sunil

+0

'networkStream.Read (bytesFrom, 0, (int) client.ReceiveBufferSize);'- 귀하의 probl이 아닐 수도 있습니다 하지만이 함수의 반환 값을 무시해서는 안됩니다. 요청한 바이트 수보다 적을 수 있습니다. –

+0

@DylanNicholson 필자는 암호화 된 값이 항상 64 바이트이므로 64 바이트로 하드 코딩하는 것으로 되돌 렸습니다. 클라이언트 측에서이 문제를 해결했지만 지금은 서버 측에서 문제가 발생했습니다. 문제는 다음과 같은 결과 일 수 있다고 생각합니다. 'byte [] cipherText = new byte [bytesToDecrypt.Length - IV.Length]; Array.Copy (bytesToDecrypt, IV, IV.Length); 배열의 길이를 64 바이트에서 48 바이트로 변경하기 때문에 (Init Vector가 16 바이트 길이입니다) –

답변

0

다음 코드는 작업중인 프로젝트에서 가져온 것입니다. 먼저 (단위) 테스트 또는 콘솔 프로젝트를 만드는 것이 좋습니다. 따라서 오버 헤드없이 암호화/암호 해독을 테스트 할 수 있습니다.

데이터 도우미 클래스 :

public class CryptData 
{ 
    private byte[]    _buffer; 
    private System.Text.Encoding _textEncoding; 
    private int     _numPaddingBytes; 

    public static readonly System.Text.Encoding DefaultTextEncoding = System.Text.Encoding.GetEncoding("Windows-1252"); 

    public CryptData() 
    { 
    _textEncoding = DefaultTextEncoding; 
    _buffer   = null; 
    _numPaddingBytes = 0; 
    } 

    public CryptData(byte[] buffer) 
    { 
    _textEncoding = DefaultTextEncoding; 
    _buffer   = buffer; 
    _numPaddingBytes = 0; 
    } 

    public CryptData(System.Text.Encoding textEncoding) 
    { 
    if (textEncoding == null) 
     throw new ArgumentNullException("textEncoding"); 

    _textEncoding = textEncoding; 
    _buffer   = null; 
    _numPaddingBytes = 0; 
    } 

    public CryptData(System.Text.Encoding textEncoding, string text) 
    { 
    if (textEncoding == null) 
     throw new ArgumentNullException("textEncoding"); 

    _textEncoding = textEncoding; 
    this.Text  = text; 
    _numPaddingBytes = 0; 
    } 

    public CryptData(string text) : this(DefaultTextEncoding, text) 
    { 
    } 

    public bool IsEmpty 
    { 
    get { return (_buffer == null || _buffer.Length < 1); } 
    } 

    public byte[] Buffer 
    { 
    get { return _buffer; } 
    set { _buffer = value; } 
    } 

    public int BufferLength 
    { 
    get { return _buffer != null ? _buffer.Length : 0; } 
    } 

    public int NumPaddingBytes 
    { 
    get { return _numPaddingBytes; } 
    set { _numPaddingBytes = value; } 
    } 

    public System.Text.Encoding TextEncoding 
    { 
    get { return _textEncoding; } 
    set 
    { 
     if (value == null) 
     throw new ArgumentNullException("TextEncoding"); 

     _textEncoding = value; 
    } 
    } 

    public string Text 
    { 
    get 
    { 
     return (_buffer != null ? _textEncoding.GetString(_buffer) : null); 
    } 
    set 
    { 
     _buffer = (value != null ? _textEncoding.GetBytes(value) : null); 
    } 
    } 

    public string Base64Text 
    { 
    get 
    { 
     return (_buffer != null ? Convert.ToBase64String(_buffer) : null); 
    } 
    set 
    { 
     _buffer = (value != null ? Convert.FromBase64String(value) : null); 
    } 
    } 
} 

AES 래퍼 클래스 :

/// <summary> 
/// This class wraps the AES encryption algorithm (RijndaelManaged class) and can be used to encrypt and decrypt data. 
/// The passphrases hash value is used to set the key and initialization vector of the algorithm. Internally, SHA384 
/// is used to create a 192 bits key and a 128 bits initialization vector. 
/// </summary> 
public class SymmetricEncryptionHelper : IDisposable 
{ 
    private RijndaelManaged _algorithm = null; 
    private byte[]   _iv = null; // initialization vector 
    private byte[]   _key = null; // key 
    private string   _passPhrase = string.Empty; 
    private int    _streamBufferLength = 2048; 
    private PaddingMode  _padding; 

    /// <summary> 
    /// Creates a SymmetricEncryptionHelper object. 
    /// </summary> 
    /// <param name="passPhrase">The passphrase.</param> 
    public SymmetricEncryptionHelper(string passPhrase) 
    : this(passPhrase, PaddingMode.PKCS7) 
    { 
    } 

    /// <summary> 
    /// Creates a SymmetricEncryptionHelper object. 
    /// </summary> 
    /// <param name="passPhrase">The passphrase.</param> 
    /// <param name="padding">The padding mode to use.</param> 
    public SymmetricEncryptionHelper(string passPhrase, PaddingMode padding) 
    { 
    this.PassPhrase = passPhrase; 
    _padding  = padding; 
    } 

    /// <summary> 
    /// Sets the required passphrase 
    /// </summary> 
    public string PassPhrase 
    { 
    set 
    { 
     if (value == null) 
     throw new ArgumentNullException("PassPhrase"); 
     if (value.Length < 1) 
     throw new ArgumentException("PassPhrase.Length < 1", "PassPhrase"); 

     _passPhrase = value; 
     InitializeKeys(); 
     _algorithm = null; // reset algorithm, because the passphrase has changed 
    } 
    } 

    /// <summary> 
    /// Gets or sets the internal buffer length used for encryption/decryption if streams are used. 
    /// Range [16...4096]. 
    /// </summary> 
    public int StreamBufferLength 
    { 
    get { return _streamBufferLength; } 
    set 
    { 
     if (value < 16) 
     throw new ArgumentOutOfRangeException("StreamBufferLength", value, "StreamBufferLength < 16"); 
     if (value > 4096) 
     throw new ArgumentOutOfRangeException("StreamBufferLength", value, "StreamBufferLength > 4096"); 

     _streamBufferLength = value; 
    } 
    } 

    /// <summary> 
    /// Creates 
    /// </summary> 
    /// <param name="data"></param> 
    /// <returns></returns> 
    private CryptData CreateSHA384Hash(CryptData data) 
    { 
    CryptData hash = new CryptData(); 

    using (var algorithm = new SHA384Managed()) 
    { 
     hash.Buffer = algorithm.ComputeHash(data.Buffer); 
    } 

    return hash; 
    } 

    /// <summary> 
    /// Initializes the key and initialization vector using the passphrases hash value. 
    /// </summary> 
    protected virtual void InitializeKeys() 
    { 
    // create a 48 byte hash value used to initialize the initialization vector and the key 
    CryptData hashValue = CreateSHA384Hash(new CryptData(_passPhrase)); 

    // create the key and initialization vector 
    this._key = new byte[24]; // 192 bits 
    this._iv = new byte[16]; // 128 bits 

    // copy the results 
    Array.Copy(hashValue.Buffer, _key, _key.Length); 
    Array.Copy(hashValue.Buffer, _key.Length, _iv, 0, _iv.Length); 
    } 

    /// <summary> 
    /// Initializes the internal RijndaelManaged algorithm, assigns the key and 
    /// initialization vector. If the object already exists, nothing is done. 
    /// </summary> 
    protected virtual void InitializeAlgorithm() 
    { 
    if (_algorithm == null) 
    { 
     _algorithm   = new RijndaelManaged(); 
     _algorithm.Key  = _key; 
     _algorithm.IV  = _iv; 
     _algorithm.Padding = _padding; 
    } 
    } 

    /// <summary> 
    /// Encrypts the given data. 
    /// </summary> 
    /// <param name="data">The data to encrypt.</param> 
    /// <returns>Returns the encrypted data.</returns> 
    public CryptData Encrypt(CryptData data) 
    { 
    if (data == null) 
     throw new ArgumentNullException("data"); 
    if (data.Buffer == null) 
     throw new ArgumentNullException("data.Buffer"); 
    if (data.BufferLength < 1) 
     throw new ArgumentException("data.BufferLength < 1", "data.Buffer"); 

    ICryptoTransform transform = null; 
    MemoryStream memStream = null; 
    CryptoStream cryptoStream = null; 
    CryptData resultData = null; 

    try 
    { 
     InitializeAlgorithm(); 
     transform = _algorithm.CreateEncryptor(); 
     memStream = new MemoryStream(); 
     cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write); 
     cryptoStream.Write(data.Buffer, 0, data.BufferLength); 
     cryptoStream.FlushFinalBlock(); 

     resultData = new CryptData(memStream.ToArray()); 
     resultData.NumPaddingBytes = resultData.BufferLength - data.BufferLength; 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine("SymmetricEncryptionHelper.Encrypt exception: " + ex); 
     throw; 
    } 
    finally 
    { 
     if (transform != null) 
     transform.Dispose(); 
     if (memStream != null) 
     memStream.Close(); 
     if (cryptoStream != null) 
     cryptoStream.Dispose(); 
    } 

    return resultData; 
    } 

    /// <summary> 
    /// Encrypts the given data. 
    /// </summary> 
    /// <param name="stream">The stream to encrypt.</param> 
    /// <returns>Returns the encrypted data.</returns> 
    public CryptData Encrypt(System.IO.Stream stream) 
    { 
    if (stream == null) 
     throw new ArgumentNullException("stream"); 
    if (stream.Length < 1) 
     throw new ArgumentException("stream.Length < 1", "stream"); 

    ICryptoTransform transform = null; 
    MemoryStream memStream = null; 
    CryptoStream cryptoStream = null; 
    CryptData resultData = null; 
    byte[] buffer; 
    int writtenBytes; 

    try 
    { 
     InitializeAlgorithm(); 
     transform = _algorithm.CreateEncryptor(); 
     memStream = new MemoryStream(); 
     cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Write); 

     buffer = new byte[_streamBufferLength]; 
     stream.Position = 0; 
     while (0 < (writtenBytes = stream.Read(buffer, 0, buffer.Length))) 
     { 
     cryptoStream.Write(buffer, 0, writtenBytes); 
     } 
     cryptoStream.FlushFinalBlock(); 

     resultData = new CryptData(memStream.ToArray()); 
     resultData.NumPaddingBytes = resultData.BufferLength - (int)stream.Length; 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine("SymmetricEncryptionHelper.Encrypt exception: " + ex); 
     throw; 
    } 
    finally 
    { 
     if (transform != null) 
     transform.Dispose(); 
     if (memStream != null) 
     memStream.Close(); 
     if (cryptoStream != null) 
     cryptoStream.Dispose(); 
    } 

    return resultData; 
    } 

    /// <summary> 
    /// Decrypts the given data. 
    /// </summary> 
    /// <param name="encryptedData">The encrypted data.</param> 
    /// <returns>Returns the decrypted data.</returns> 
    public CryptData Decrypt(CryptData encryptedData) 
    { 
    if (encryptedData == null) 
     throw new ArgumentNullException("encryptedData"); 
    if (encryptedData.Buffer == null) 
     throw new ArgumentNullException("encryptedData.Buffer"); 
    if (encryptedData.BufferLength < 1) 
     throw new ArgumentException("encryptedData.BufferLength < 1", "encryptedData.Buffer"); 

    ICryptoTransform transform = null; 
    MemoryStream memStream = null; 
    CryptoStream cryptoStream = null; 
    CryptData resultData = null; 
    byte[] decryptedBuffer; 

    try 
    { 
     InitializeAlgorithm(); 
     transform = _algorithm.CreateDecryptor(); 
     memStream = new MemoryStream(encryptedData.Buffer); 
     cryptoStream = new CryptoStream(memStream, transform, CryptoStreamMode.Read); 

     // create result buffer and read the data from the crypto stream (do decryption) 
     decryptedBuffer = new byte[encryptedData.BufferLength]; 
     cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length); 

     // create the result data 
     if (encryptedData.NumPaddingBytes > 0) 
     { // remove padded bytes if neccessary 
     byte[] decryptedBufferUnpadded = new byte[decryptedBuffer.Length - encryptedData.NumPaddingBytes]; 
     Array.Copy(decryptedBuffer, decryptedBufferUnpadded, decryptedBufferUnpadded.Length); 
     resultData = new CryptData(decryptedBufferUnpadded); 
     } 
     else 
     resultData = new CryptData(decryptedBuffer); 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine("SymmetricEncryptionHelper.Decrypt exception: " + ex); 
     throw; 
    } 
    finally 
    { 
     if (transform != null) 
     transform.Dispose(); 
     if (memStream != null) 
     memStream.Close(); 
     if (cryptoStream != null) 
     cryptoStream.Dispose(); 
    } 

    return resultData; 
    } 

    /// <summary> 
    /// Decrypts the given data. 
    /// </summary> 
    /// <param name="encryptedStream">The encrypted stream.</param> 
    /// <returns>Returns the decrypted data.</returns> 
    public CryptData Decrypt(System.IO.Stream encryptedStream) 
    { 
    if (encryptedStream == null) 
     throw new ArgumentNullException("encryptedStream"); 
    if (encryptedStream.Length < 1) 
     throw new ArgumentException("encryptedStream.Length < 1", "encryptedStream"); 

    ICryptoTransform transform = null; 
    MemoryStream memStream = null; 
    CryptoStream cryptoStream = null; 
    CryptData resultData = null; 
    byte[] decryptedBuffer; 
    int readBytes; 

    try 
    { 
     InitializeAlgorithm(); 
     transform = _algorithm.CreateDecryptor(); 
     memStream = new MemoryStream(_streamBufferLength); 
     cryptoStream = new CryptoStream(encryptedStream, transform, CryptoStreamMode.Read); 

     // create result buffer and read the data from the crypto stream (do decryption) 
     decryptedBuffer = new byte[_streamBufferLength]; 
     while (0 < (readBytes = cryptoStream.Read(decryptedBuffer, 0, decryptedBuffer.Length))) 
     { 
     memStream.Write(decryptedBuffer, 0, readBytes); // store decrypted bytes 
     } 

     // create the result data 
     resultData = new CryptData(memStream.ToArray()); 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine("SymmetricEncryptionHelper.Decrypt exception: " + ex); 
     throw; 
    } 
    finally 
    { 
     if (transform != null) 
     transform.Dispose(); 
     if (memStream != null) 
     memStream.Close(); 
     if (cryptoStream != null) 
     cryptoStream.Dispose(); 
    } 

    return resultData; 
    } 

    /// <summary> 
    /// Disposes the object. 
    /// </summary> 
    public void Dispose() 
    { 
    try 
    { 
     if (_algorithm != null) 
     _algorithm.Clear(); 
    } 
    catch (Exception ex) 
    { 
     Debug.WriteLine("SymmetricEncryptionHelper.Dispose exception: " + ex); 
    } 
    } 
} 

콘솔 테스트 클래스 :

class Program 
    { 
    static void Main(string[] args) 
    { 
     Console.WriteLine("AES Test Program\n\n"); 

     string passPhrase = "MyPassword"; 
     string secretText = "This is my secret text"; 

     var encrypted = Encrypt(passPhrase, new CryptData(secretText)); 

     Console.WriteLine("Encrypted: " + encrypted.Base64Text); 

     var decrypted = Decrypt(passPhrase, encrypted); 

     Console.WriteLine("Decrypted: " + decrypted.Text); 

     Console.WriteLine("\nPress <ENTER> to exit"); 
     Console.ReadLine(); 
    } 

    private static CryptData Encrypt(string passPhrase, CryptData plainData) 
    { 
     using (var enc = new SymmetricEncryptionHelper(passPhrase)) 
     { 
     return enc.Encrypt(plainData); 
     } 
    } 

    private static CryptData Decrypt(string passPhrase, CryptData encryptedData) 
    { 
     using (var dec = new SymmetricEncryptionHelper(passPhrase)) 
     { 
     return dec.Decrypt(encryptedData); 
     } 
    } 
    } 
관련 문제