当我尝试解密字符串时,Visual Studio 会抛出异常:System.Security.Cryptography.CryptographicException 并说用于解密的数据长度无效。当编译器在 RC2_Decrypt 方法中到达 cs.Close() 时出现异常。
static byte[] RC2_Encrypt(byte[] bytesToBeEncrypted, byte[] passwordBytes)
{
byte[] encryptedBytes = null;
string salt = "D495560961CCCFE0";
byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
using (MemoryStream msStream = new MemoryStream())
{
using (RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider())
{
RC2.KeySize = 128;
RC2.BlockSize = 64;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
RC2.Key = key.GetBytes(RC2.KeySize / 8);
RC2.IV = key.GetBytes(RC2.BlockSize / 8);
RC2.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(msStream, RC2.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
encryptedBytes = msStream.ToArray();
}
}
return encryptedBytes;
}
static byte[] RC2_Decrypt(byte[] bytesToBeDecrypted, byte[] passwordBytes)
{
byte[] decryptedBytes = null;
string salt = "D495560961CCCFE0";
byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
using (MemoryStream msStream = new MemoryStream())
{
using (RC2CryptoServiceProvider RC2 = new RC2CryptoServiceProvider())
{
RC2.KeySize = 128;
RC2.BlockSize = 64;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
RC2.Key = key.GetBytes(RC2.KeySize / 8);
RC2.IV = key.GetBytes(RC2.BlockSize / 8);
RC2.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(msStream, RC2.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
decryptedBytes = msStream.ToArray();
}
}
return decryptedBytes;
}
这里的例子我只是测试这些方法。因此,首先我尝试加密一个简单的字符串。
static void Main(string[] args)
{
string password = "770A8A65DA156D24EE2A093277530142";
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
Console.WriteLine("Encrypting");
string str = "Hello world";
Console.WriteLine(EncString(str, password));
byte[] encArray = Encoding.UTF8.GetBytes(str);
Console.WriteLine(DecString(str, password));
Console.ReadKey();
}
我用于字符串加密的方法:
static string EncString(string message, string password)
{
byte[] byresToBeEncrypted = Encoding.UTF8.GetBytes(message);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] bytesToBeEncrypted = RC2_Encrypt(byresToBeEncrypted, passwordBytes);
string result = Convert.ToBase64String(byresToBeEncrypted);
return result;
}
static string DecString(string message, string password)
{
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(message);
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
byte[] bytesToBeDecrypted = RC2_Decrypt(bytesToBeEncrypted, passwordBytes);
string result = Encoding.UTF8.GetString(bytesToBeDecrypted);
return result;
}
那么这些方法可以加密和解密文本文件,这就是我所需要的。但我还有一个问题。为什么这不适用于简单的字符串变量?