第一步获取签名证书私钥
/// <summary> /// 获取签名证书私钥 /// </summary> /// <param name="priKeyFile">证书文件路径</param> /// <param name="keyPwd">密码</param> /// <returns></returns> private static RSA GetPrivateKey(string priKeyFile, string keyPwd) { var pc = new X509Certificate2(priKeyFile, keyPwd, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); return (RSA)pc.PrivateKey; }
第二步根据私钥对数据进行签名
/// <summary> /// 根据证书签名数据 /// </summary> /// <param name="data">要签名的数据</param> /// <param name="certPah">证书路径</param> /// <param name="certPwd">密码</param> /// <returns></returns> public string Sign(string data, string certPah, string certPwd) { var rsa = GetPrivateKey(certPah, certPwd); var rsaClear = new RSACryptoServiceProvider(); var paras = rsa.ExportParameters(true); rsaClear.ImportParameters(paras); var signData = rsa.SignData(Encoding.UTF8.GetBytes(data), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signData); }