图片加密解密时出现"要解密的数据的长度无效"

sxmonsy CSDN会员 sxmonsy 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在读取解密图片的时候出现“要解密的数据的长度无效” 大家帮我看下是什么原因。
代码如下:

/// <summary>
/// 加密保存
/// </summary>
private void button1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image != null)
{
//进行加密
byte[] imgData =CommonClass.ImageOperae.EncryptFle(pictureBox1.Image, "201104");

string cmdText = "";
using (OleDbConnection conn = new OleDbConnection(CommonClass.OleDbHelper.connAutomation))
{
//数据库保存略
}
}
}
/// <summary>
/// 读取文件
/// </summary>
private void button2_Click(object sender, EventArgs e)
{

OleDbConnection conn = new OleDbConnection(CommonClass.OleDbHelper.connAutomation);
conn.Open();
OleDbDataAdapter obda = new OleDbDataAdapter("select [image] from table1 where id=6", conn);
DataTable dt = new DataTable();
obda.Fill(dt);
conn.Close();
byte[] buffer = dt.Rows[0][0] as byte[];

//解密打开
MemoryStream ms = new MemoryStream(CommonClass.ImageOperae.DecryptFile(buffer,"sxm"));
pictureBox1.Image = img;
}

/// <summary>
/// 图片加密
/// </summary>
public static Byte[] EncryptFile(Image img, string keyStr)
{
//通过des加密
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
MemoryStream ms = new MemoryStream();
//获取文件二进制字符
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] inputByteArray = ms.GetBuffer();

//获得加密字符串二进制字符
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;

CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
ms.Close();
return ms.ToArray();
}

/// <summary>
/// 图片解密
/// </summary>
public static byte[] DecryptFile(byte[] inputByteArray, string keyStr)
{
//通过des解密
DESCryptoServiceProvider des = new DESCryptoServiceProvider();

//密钥数组
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();
cs.Close();
ms.Close();
return ms.ToArray();
}
...全文

相关推荐

评论 22
收藏 已收藏
分享
返回顶部
sxmonsy CSDN会员
C# 111,130 成员 642,539 内容