C#.NET工行开放平台RSA私钥公钥生成小工具V2024

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值