gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:25:02 25 4
gpt4 key购买 nike

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

Gulp..有人可以帮忙吗...

最佳答案

由于您“不需要太多安全性”,您可能可以通过类似 AES (Rijndael) 的方式来解决问题.它使用对称 key ,并且在 .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;
}
}

关于c# - 用于加密图像文件的简单加密/解密方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4438691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com