2009-03-03 34 views

回答

5

如果您擔心磁盤I/O,則可以使用MemoryStream。

但是,RSACryptoServiceProvider類將在字節數組上運行。該類使用RSA算法的實現執行非對稱加密和解密。

的例子here顯示如何使用字節數組

2

好了,你可以自己的加密算法 - 但它更容易只是使用內置的API寫流傳輸到MemoryStream然後您可以轉換到使用ToArray一個字節數組。

-1

使用塊暗號做到這一點,並實現它自己。

但是,這幾乎是毫無意義的,因爲在字節數組上使用MemoryStream應該工作得很好,並且會使用經過良好測試的實現。

當你在談論加密時自己實現一些東西,通常是一個壞主意。

0

使用微軟企業庫的Cryptography Application Block你可以做到這一點,但我同意其他人的觀點,即你沒有真正從不使用流的好處。

14

其實你不需要使用任何流的所有字節進行操作。 你唯一需要的就是調用TransformFinalBlock()ICryptoTransform的方法可以是從SymmetricAlgorithm類派生的任何算法的加密解密或

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); 

    } 
}