先前的 Util 是直接从文件中转换的
https://www.cnblogs.com/runliuv/p/15079404.html
public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
加一个方法,从文本字符串转换。
SM2 公钥证书文本:
-----BEGIN CERTIFICATE-----
MIICvTCCAmGgAwIBAgIFExIYAVkwDAYIKoEcz1UBg3UFADAlMQswCQYDVQQGEwJD
TjEWMBQGA1UECgwNQ0ZDQSBTTTIgT0NBMTAeFw0yMDEyMDkwMjU3NTVaFw0yNTEy
MDkwMjU3NTVaMIGaMQswCQYDVQQGEwJDTjESMBAGA1UECgwJQ0ZDQSBPQ0ExMQ0w
CwYDVQQLDARQU0JDMRkwFwYDVQQLDBBPcmdhbml6YXRpb25hbC0yMU0wSwYDVQQD
DEQwNTFA5Lit5Zu96YKu5pS/5YKo6JOE6ZO26KGM6IKh5Lu95pyJ6ZmQ5YWs5Y+4
QE45MTExMDAwMDcxMDkzNDY1WENAMjBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IA
BNO38IXNDIOEVG0agcMVldn44y2Dy+O/5y5CNiX17zNHTduqbo8e2W/dUFJI4Nlh
+t+ob+0FFh2vLip/N2sSzrujggEEMIIBADAfBgNVHSMEGDAWgBRck1ggWiRzVhAb
ZFAQ7OmnygdBETAMBgNVHRMBAf8EAjAAMEgGA1UdIARBMD8wPQYIYIEchu8qAQEw
MTAvBggrBgEFBQcCARYjaHR0cDovL3d3dy5jZmNhLmNvbS5jbi91cy91cy0xNC5o
dG0wNwYDVR0fBDAwLjAsoCqgKIYmaHR0cDovL2NybC5jZmNhLmNvbS5jbi9TTTIv
Y3JsNTA4Ny5jcmwwDgYDVR0PAQH/BAQDAgbAMB0GA1UdDgQWBBQpy5PgWpo2fVK2
0jQS4vZFhm4FbzAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDAYIKoEc
z1UBg3UFAANIADBFAiAzaOYBRP9RY93947T6h7VKBnwdj5FV2f/ULYAHAG+DGQIh
ANpF9YrgoO7MHQi3bDdz/G+cZGZLqznltOnbBHeJUga9
-----END CERTIFICATE-----
处理方法(nuget上下载最新BouncyCastle.Crypto.dll):
public static AsymmetricKeyParameter GetPublickeyFromX509String(string publicKeyCert) { //还原完整文本格式 publicKeyCert = StrToPubCert(publicKeyCert); byte[] bytesCerContent = System.Text.Encoding.UTF8.GetBytes(publicKeyCert); //需要完整文本格式才能解析 X509Certificate certificate = new X509CertificateParser().ReadCertificate(bytesCerContent); return certificate.GetPublicKey(); } /// <summary> /// 转为完整格式 /// </summary> /// <param name="pubKeyStr"></param> /// <returns></returns> public static string StrToPubCert(string publicKeyCert) { //去除意外字符 publicKeyCert = publicKeyCert.Replace("-----BEGIN CERTIFICATE-----", "").Replace("-----END CERTIFICATE-----", "").Replace(" ", "").Replace(" ", "").Trim(); //完整 string rn = " "; StringBuilder sbKey = new StringBuilder(publicKeyCert); int nKeyLen = sbKey.Length; //sbKey为base64编码的公钥字符串 for (int i = 64; i < nKeyLen; i += 64) { sbKey.Insert(i, rn); i++; } sbKey.Insert(0, "-----BEGIN CERTIFICATE-----" + rn); sbKey.Append(rn + "-----END CERTIFICATE-----" + rn); string all_key_str = sbKey.ToString(); return all_key_str; }
public X509Certificate ReadCertificate(byte[] input),这个方法需要读取完整公钥格式的字符串,即带“-----BEGIN CERTIFICATE-----”和“"-----END CERTIFICATE-----”,否则转换不了。
文本转byte[] 时,使用System.Text.Encoding.UTF8.GetBytes(),而非Convert.FromBase64String()。