有没有办法在不使用流的情况下加密bytearray?
实际上,您根本不需要使用任何流来操作字节.您唯一需要的是调用ICryptoTransform的TransformFinalBlock()方法,该方法可以是从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); } }
如果您担心磁盘I/O,可以使用MemoryStream.
但是,RSACryptoServiceProvider类将在字节数组上运行.此类使用RSA算法的实现执行非对称加密和解密.
这里的示例显示了如何使用字节数组执行此操作