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

时间:2010-12-14 11:34:57

标签: c# encryption

我的要求是我需要在C#中使用简单的加密/解密方法来加密和 解密图像(也许是gif / jpeg)。简单的原因我必须将它存储在BLOB字段的数据库中,而其他一些编程语言(如java)的开发人员可能需要提取并显示该图像。我不需要安全性很高只是因为“模糊安全”(生活)。

Gulp ..有人帮忙......

2 个答案:

答案 0 :(得分:7)

由于您“不需要太多安全性”,您可能会设法使用AES (Rijndael)之类的东西。它使用对称密钥,.NET框架中有很多帮助,使其易于实现。 MSDN on the Rijndael class中有大量有关您可能会感兴趣的信息。

这是一个非常精简的加密/解密方法示例,可用于处理字节数组(二进制内容)......

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;
    }
}

答案 1 :(得分:1)

查看System.Security.Cryptography命名空间。

以下是关于encrypting data的文章。

您的问题非常笼统 - 链接的文章为您提供了使用内置函数进行加密的示例。