c# 图片加密解密的实例代码
using system;
using system.collections.generic;
using system.text;
using system.security.cryptography;
using system.io;
namespace net.template.common
{
/// <summary>
/// 对图片的加密和解密
/// </summary>
public class dencrypt4imagehelper
{
public dencrypt4imagehelper() { }
#region 加密方法 图片加密
/// <summary>
/// 图片加密
/// </summary>
/// <param name="filepath">源文件</param>
/// <param name="savepath">保存为文件名称</param>
/// <param name="keystr">密钥</param>
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();
}
#endregion
#region 解密方法 图片解密
/// <summary>
/// 图片解密
/// </summary>
/// <param name="filepath">源文件</param>
/// <param name="savepath">保存文件</param>
/// <param name="keystr">密钥</param>
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();
}
#endregion
}
}
上一篇: 分享C#操作内存读写方法的主要实现代码