C#.NET工行开放平台RSA私钥公钥生成小工具V2024
开发环境:
.NET FRAMEWORK 4.0
rsatool.exe,来自于工行开发文档。
主要代码:
string thisAppPath = Application.StartupPath;
string exePath = Path.Combine(thisAppPath, "tools");
string exeFullName = Path.Combine(exePath, "rsatool.exe");
if (!File.Exists(exeFullName))
{
MessageBox.Show("文件不存在:" + exeFullName);
return;
}
STARTGEN:
//参数顺序:消息,朗读者index
StringBuilder args = new StringBuilder();
args.Append(" keygen"); //keygen 前边有空格
ProcessStartInfo psi = new ProcessStartInfo(exeFullName, args.ToString());
psi.CreateNoWindow = true;//不显示控制台窗口
psi.UseShellExecute = false;//不显示控制台窗口
psi.WorkingDirectory = exePath;
Process _viceProcess = new Process();
_viceProcess.StartInfo = psi;
_viceProcess.Start();
System.Threading.Thread.Sleep(3000);//防止 EXE没执行完
string priKeyFullName = Path.Combine(exePath, "private.pem");
string pubKeyFullName = Path.Combine(exePath, "public.pem");
if (!File.Exists(priKeyFullName) || !File.Exists(pubKeyFullName))
{
MessageBox.Show("私钥或公钥文件未生成成功:" + priKeyFullName);
return;
}
//复制一份
string filePrefix = DateTime.Now.ToString("yyyyMMddHHmmssfff-");
string priKeyFullName2 = Path.Combine(exePath, filePrefix + "private.pem");
string pubKeyFullName2 = Path.Combine(exePath, filePrefix + "public.pem");
File.Copy(priKeyFullName, priKeyFullName2);
File.Copy(pubKeyFullName, pubKeyFullName2);
//校验PKCS8是否能过
string priKeyText = File.ReadAllText(priKeyFullName2);
if (!CheckPkcs8(priKeyText))
{
GLog.WLog("PKCS8 私钥不能解析,准备重新生成。\r\n"+ priKeyText);
goto STARTGEN;
}
txtPriFullName.Text = priKeyFullName2;
txtPubFullName.Text = pubKeyFullName2;
string pubKeyText = File.ReadAllText(pubKeyFullName2);
txtPriKey.Text = priKeyText;
txtPubKey.Text = pubKeyText;
MessageBox.Show("生成成功!请保存好生成的文件。");
CheckPkcs8 方法:
private bool CheckPkcs8(string pkcs8Str)
{
try
{
var myRsa = RsaUtil.LoadPrivateKeyPKCS8(pkcs8Str);
if (myRsa != null)
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
return true;
}
工具类:
RsaUtil,需要在nuget引用 BouncyCastle.Crypto 库:
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace CommonUtils
{
public static class RsaUtil
{
#region 加载私钥
/// <summary>
/// 转换私钥字符串为RSACryptoServiceProvider
/// </summary>
/// <param name="privateKeyStr">私钥字符串</param&g