简单的加密/解密方法用于加密图像文件

6
我的要求是需要在C#中提供简单的加密/解密方法,以加密和解密图像(可能是gif / jpeg格式)。这很简单,因为我必须将其存储在数据库的BLOB字段中,并且其他一些开发人员可能需要从其他编程语言(如Java)中提取和显示此图像。我不需要太高的安全性,因为这只是“混淆式安全”(生活中的一种方式)。呜呼..有人能帮忙吗...

你是否使用MS SQL 2005或更高版本?如果您想要这样做,可以加密单个列... http://msdn.microsoft.com/en-us/library/ms179331(v=SQL.90).aspx - Saul Dolgin
2个回答

10

由于您“不需要太高的安全性”,您可能可以使用类似于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;
    }
}

这种加密方式会改变图像文件格式吗? - Mani
1
@Mani 不,它不会改变文件类型。加密会将文件内容混淆(无论其类型如何)。解密(使用用于加密的适当补充方法和相关密钥)只是将加密数据反转以恢复原始文件内容,文件类型不会改变。 - Charles Okwuagwu

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接