SoFunction
Updated on 2025-03-07

C# Image encryption and decryption example code


using System;
using ;
using ;
using ;
using ;

namespace
{
/// <summary>
/// Encryption and decryption of pictures
/// </summary>
public class DEncrypt4ImageHelper
{
public DEncrypt4ImageHelper() { }

#region encryption method Image encryption
/// <summary>
/// Picture encryption
/// </summary>
/// <param name="filePath">Source file</param>
/// <param name="savePath">Save as file name</param>
/// <param name="keyStr">key</param>
public static void EncryptFile(string filePath, string savePath, string keyStr)
{
// Encryption via des
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
//Open the file through stream
FileStream fs = (filePath);
//Get binary characters in the file
byte[] inputByteArray = new byte[];
//Read stream file
(inputByteArray, 0, (int));
//Close the flow
();
//Get encrypted string binary characters
byte[] keyByteArray = (keyStr);

// Calculate the hash value of the specified byte group specified area
SHA1 ha = new SHA1Managed();
byte[] hb = (keyByteArray);
//Encryption key array
byte[] sKey = new byte[8];
//Encryption variable
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];
//Get the encryption key

= sKey;
//Set the encryption initialization vector
= sIV;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, (), );
(inputByteArray, 0, );
();
fs = (savePath);

foreach (byte b in ())
{
(b);

}

();
();
();

}
#endregion

#region decryption method Image decryption
/// <summary>
/// Picture decryption
/// </summary>
/// <param name="filePath">Source file</param>
/// <param name="savePath">Save file</param>
/// <param name="keyStr">key</param>
public static void DecryptFile(string filePath, string savePath, string keyStr)
{
//Decryption through des
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

//Read the file through stream
FileStream fs = (filePath);
//Get binary characters in the file
byte[] inputByteArray = new byte[];
//Read stream file
(inputByteArray, 0, (int));
//Close the flow
();
//Array of keys
byte[] keyByteArray = (keyStr);
//Define hash variable
SHA1 ha = new SHA1Managed();
// Calculate the hash value of the specified byte group specified area
byte[] hb = (keyByteArray);
//Encryption key array
byte[] sKey = new byte[8];
//Encryption variable
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];
//Get the encryption key
= sKey;
//Encryption variable
= sIV;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, (), );
(inputByteArray, 0, );
();
fs = (savePath);
foreach (byte b in ())
{
(b);
}
();
();
();

}
#endregion

}
}