我的要求是我需要在C#中使用简单的加密/解密方法来加密和解密图像(可能是gif/jpeg).简单的原因我必须将它存储在BLOB字段中的数据库中,而其他一些开发人员则使用其他编程语言(如java)可能需要提取和显示这个图像.我不需要太多的安全性,因为它只是"通过模糊安全"(生活)的问题.
Gulp ..可以有人帮忙......
既然你"不需要太多的安全性",你可能会设法通过像AES(Rijndael)这样的东西.它使用对称密钥,.NET框架中有很多帮助,使其易于实现.在Rijndael类中有很多关于MSDN的信息,您可能会发现它们很有帮助.
这是一个非常简单的加密/解密方法示例,可用于处理字节数组(二进制内容)......
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21114 次 |
| 最近记录: |