当前位置:首页 > 行业动态 > 正文

c# 图片加密解密的实例代码

当然,以下是一个简单的C#示例代码,用于图片的加密和解密。这个例子使用AES对称加密算法:“ csharp,using System;,using System.IO;,using System.Security.Cryptography;public class ImageEncryption,{, private static readonly string key = "your-encryption-key"; // 32 bytes for AES-256, private static readonly string iv = "your-initialization-vector"; // 16 bytes for AES public static void EncryptImage(string inputPath, string outputPath), {, using (Aes aes = Aes.Create()), {, aes.Key = Convert.FromBase64String(key);, aes.IV = Convert.FromBase64String(iv);, ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); using (FileStream fsInput = new FileStream(inputPath, FileMode.Open, FileAccess.Read)), using (FileStream fsOutput = new FileStream(outputPath, FileMode.Create, FileAccess.Write)), using (CryptoStream cs = new CryptoStream(fsOutput, encryptor, CryptoStreamMode.Write)), {, fsInput.CopyTo(cs);, }, }, } public static void DecryptImage(string inputPath, string outputPath), {, using (Aes aes = Aes.Create()), {, aes.Key = Convert.FromBase64String(key);, aes.IV = Convert.FromBase64String(iv);, ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); using (FileStream fsInput = new FileStream(inputPath, FileMode.Open, FileAccess.Read)), using (FileStream fsOutput = new FileStream(outputPath, FileMode.Create, FileAccess.Write)), using (CryptoStream cs = new CryptoStream(fsInput, decryptor, CryptoStreamMode.Read)), {, cs.CopyTo(fsOutput);, }, }, },},` 请确保将key iv`替换为实际的密钥和初始化向量,并注意这些值的长度要求(AES-256需要32字节的密钥和16字节的IV)。

在C#中,图片的加密和解密可以通过使用对称加密算法(如DES或AES)来实现,下面是一个详细的实例代码,展示了如何使用DES算法对图片进行加密和解密:

c# 图片加密解密的实例代码

加密方法

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ImageEncryptionDecryption
{
    public class DEncrypt4ImageHelper
    {
        public DEncrypt4ImageHelper() { }
        // 图片加密
        public static void EncryptFile(string filePath, string savePath, string keyStr)
        {
            // 创建DES加密服务提供程序实例
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            // 通过流打开文件
            FileStream fs = File.OpenRead(filePath);
            // 获取文件二进制字符
            byte[] inputByteArray = new byte[fs.Length];
            // 读流文件
            fs.Read(inputByteArray, 0, (int)fs.Length);
            // 关闭流
            fs.Close();
            // 获得加密字符串二进制字符
            byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
            // 计算指定字节组指定区域哈希值
            SHA1 ha = new SHA1Managed();
            byte[] hb = ha.ComputeHash(keyByteArray);
            // 加密密钥数组
            byte[] sKey = new byte[8];
            // 加密变量
            byte[] sIV = new byte[8];
            for (int i = 0; i < 8; i++)
                sKey[i] = hb[i];
            for (int i = 8; i < 16; i++)
                sIV[i 8] = hb[i];
            // 获取加密密钥
            des.Key = sKey;
            // 设置加密初始化向量
            des.IV = sIV;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            fs = File.OpenWrite(savePath);
            foreach (byte b in ms.ToArray())
            {
                fs.WriteByte(b);
            }
            fs.Close();
            cs.Close();
            ms.Close();
        }
    }
}

解密方法

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace ImageEncryptionDecryption
{
    public class DEncrypt4ImageHelper
    {
        public DEncrypt4ImageHelper() { }
        // 图片解密
        public static void DecryptFile(string filePath, string savePath, string keyStr)
        {
            // 创建DES加密服务提供程序实例
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            // 通过流读取文件
            FileStream fs = File.OpenRead(filePath);
            // 获取文件二进制字符
            byte[] inputByteArray = new byte[fs.Length];
            // 读取流文件
            fs.Read(inputByteArray, 0, (int)fs.Length);
            // 关闭流
            fs.Close();
            // 密钥数组
            byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
            // 定义哈希变量
            SHA1 ha = new SHA1Managed();
            // 计算指定字节组指定区域哈希值
            byte[] hb = ha.ComputeHash(keyByteArray);
            // 加密密钥数组
            byte[] sKey = new byte[8];
            // 加密变量
            byte[] sIV = new byte[8];
            for (int i = 0; i < 8; i++)
                sKey[i] = hb[i];
            for (int i = 8; i < 16; i++)
                sIV[i 8] = hb[i];
            // 获取加密密钥
            des.Key = sKey;
            // 加密变量
            des.IV = sIV;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            fs = File.OpenWrite(savePath);
            foreach (byte b in ms.ToArray())
            {
                fs.WriteByte(b);
            }
            fs.Close();
            cs.Close();
            ms.Close();
        }
    }
}

示例使用

以下是如何在主程序中使用上述加密和解密方法的示例:

c# 图片加密解密的实例代码

class Program
{
    static void Main(string[] args)
    {
        string filePath = "path/to/your/image.jpg"; // 替换为实际图片路径
        string savePathEncrypted = "path/to/your/encrypted_image.jpg"; // 替换为加密后图片保存路径
        string savePathDecrypted = "path/to/your/decrypted_image.jpg"; // 替换为解密后图片保存路径
        string keyStr = "your-secret-key"; // 替换为实际密钥字符串
        
        // 加密图片
        DEncrypt4ImageHelper.EncryptFile(filePath, savePathEncrypted, keyStr);
        Console.WriteLine("图片加密成功!");
        
        // 解密图片
        DEncrypt4ImageHelper.DecryptFile(savePathEncrypted, savePathDecrypted, keyStr);
        Console.WriteLine("图片解密成功!");
    }
}

代码中的path/to/your/image.jpgpath/to/your/encrypted_image.jpgpath/to/your/decrypted_image.jpgyour-secret-key需要根据实际情况进行替换,为了简化代码,这里使用了SHA1来生成密钥和IV(初始化向量),但在实际应用中,建议使用更安全的方法来管理密钥和IV。

c# 图片加密解密的实例代码