我的要求是需要在C#中提供简单的加密/解密方法,以加密和解密图像(可能是gif / jpeg格式)。这很简单,因为我必须将其存储在数据库的BLOB字段中,并且其他一些开发人员可能需要从其他编程语言(如Java)中提取和显示此图像。我不需要太高的安全性,因为这只是“混淆式安全”(生活中的一种方式)。呜呼..有人能帮忙吗...
由于您“不需要太高的安全性”,您可能可以使用类似于AES(Rijndael)的内容。它使用对称密钥,.NET框架中有很多帮助使其易于实现。在MSDN关于Rijndael类的信息中有许多您可能会发现有用的信息。
以下是一个非常简化的示例,用于加密/解密方法,可用于处理字节数组(二进制内容)...
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class RijndaelHelper
{
// Example usage: EncryptBytes(someFileBytes, "SensitivePhrase", "SodiumChloride");
public static byte[] EncryptBytes(byte[] inputBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return CipherBytes;
}
// Example usage: DecryptBytes(encryptedBytes, "SensitivePhrase", "SodiumChloride");
public static byte[] DecryptBytes(byte[] encryptedBytes, string passPhrase, string saltValue)
{
RijndaelManaged RijndaelCipher = new RijndaelManaged();
RijndaelCipher.Mode = CipherMode.CBC;
byte[] salt = Encoding.ASCII.GetBytes(saltValue);
PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, salt, "SHA1", 2);
ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(password.GetBytes(32), password.GetBytes(16));
MemoryStream memoryStream = new MemoryStream(encryptedBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] plainBytes = new byte[encryptedBytes.Length];
int DecryptedCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return plainBytes;
}
}