📄 form1.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security;
using System.Security.Cryptography;
namespace DigestAndSignature
{
public partial class btnSaveFile : Form
{
private string openFileName;
private string saveFileName;
private byte[] hashBytes;
public byte[] HashCreate(string filePath)
{
//利用SHA报文算法生成报文鉴别码
HashAlgorithm hash = HashAlgorithm.Create();
//读入文件
FileStream fs = new FileStream(filePath, FileMode.Open);
//计算hash值
byte[] hashBytes = hash.ComputeHash(fs);
fs.Close();
return hashBytes;
}
public bool EncryptFile(byte[] hashBytes, string outPath)
{
try
{
//利用RSA算法对报文鉴别码进行数字签名
RSACryptoServiceProvider rsac = new RSACryptoServiceProvider();
//打开文件输出流
FileStream res = new FileStream(outPath, FileMode.Create, FileAccess.Write);
hashBytes = rsac.Encrypt(hashBytes, false);
res.Write(hashBytes, 0, hashBytes.Length);
res.Close();
//保存密钥到文件
StreamWriter sw = new StreamWriter("RSA.key");
sw.Write(rsac.ToXmlString(true));
sw.Close();
return true;
}
catch (System.Exception e)
{
return false;
}
}
public btnSaveFile()
{
InitializeComponent();
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
openFileDlg.ShowDialog();
}
private void button2_Click(object sender, EventArgs e)
{
saveFileDlg.ShowDialog();
}
private void openFileDlg_FileOk(object sender, CancelEventArgs e)
{
txtOpenFile.Text = openFileDlg.FileName;
openFileName = txtOpenFile.Text;
}
private void saveFileDlg_FileOk(object sender, CancelEventArgs e)
{
txtSaveFile.Text = saveFileDlg.FileName;
saveFileName = txtSaveFile.Text;
}
private void btnSHA_Click(object sender, EventArgs e)
{
hashBytes=HashCreate(openFileName);
if(hashBytes.Length>0)
{
MessageBox.Show("报文鉴别码是:"+BitConverter.ToString(hashBytes));
}
else
{
MessageBox.Show("error!");
}
}
private void btnRSA_Click(object sender, EventArgs e)
{
if(txtSaveFile.Text=="")
{
MessageBox.Show("请输入保存的文件名!");
return;
}
if (EncryptFile(hashBytes,txtSaveFile.Text))
{
MessageBox.Show("success!");
}
else
{
MessageBox.Show("error!");
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -