2009-03-03 4 views

답변

5

디스크 I/O가 염려되는 경우 MemoryStream을 사용할 수 있습니다.

그러나 RSACryptoServiceProvider 클래스는 바이트 배열에서 작동합니다. 이 클래스는, RSA 알고리즘의 구현을 사용해, 비대칭의 암호화 및 복호화를 실시합니다.

의 예 here는 바이트 배열

2

글쎄, 당신은 자신의 암호화 알고리즘을 쓸 수 -하지만 그냥 사용하는 것이 훨씬 쉽게 내장 당신이 다음 ToArray를 사용하여 바이트 배열로 변환 MemoryStream에 API 쓰기 스트리밍.

-1

사용 블록 사이퍼이 작업을 수행하고 스스로를 구현할 수있는 방법을 보여줍니다.

그러나 바이트 배열에서 MemoryStream을 사용하면 잘 작동하며 잘 테스트 된 구현을 사용하므로 거의 무의미합니다.

암호에 대해 이야기 할 때 직접 구현하면 은 일반적으로입니다.

0

Microsoft 기업 라이브러리 Cryptography Application Block을 사용하면이 작업을 수행 할 수 있지만 다른 작업에서는 실제로 스트림을 사용하지 않아도 이익을 얻지 못하는 것에 동의합니다.

14

는 사실 당신은 바이트 작동 전혀 스트림을 사용할 필요가 없습니다. 당신이 필요로하는 유일한 것은) TransformFinalBlock를 (전화 SymmetricAlgorithm 클래스에서 파생 된 알고리즘의 암호 화기 또는 암호 해독기가 될 수 ICryptoTransform의 방법이다

public class CryptoProvider 
{ 
    private SymmetricAlgorithm _algorithm = new RijndaelManaged(); 

    public byte[] EncryptData(byte[] data, string password) 
    { 
     GetKey(password); 

     ICryptoTransform encryptor = _algorithm.CreateEncryptor(); 

     byte[] cryptoData = encryptor.TransformFinalBlock(data, 0, data.Length); 

     return cryptoData; 
    } 

    public byte[] DecryptData(byte[] cryptoData, string password) 
    { 
     GetKey(password); 

     ICryptoTransform decryptor = _algorithm.CreateDecryptor(); 

     byte[] data = decryptor.TransformFinalBlock(cryptoData, 0, cryptoData.Length); 

     return data; 
    } 

    private void GetKey(string password) 
    { 
     byte[] salt = new byte[8]; 

     byte[] passwordBytes = Encoding.ASCII.GetBytes(password); 

     int length = Math.Min(passwordBytes.Length, salt.Length); 

     for (int i = 0; i < length; i++) 
      salt[i] = passwordBytes[i]; 

     Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt); 

     _algorithm.Key = key.GetBytes(_algorithm.KeySize/8); 
     _algorithm.IV = key.GetBytes(_algorithm.BlockSize/8); 

    } 
}