“公钥证书” .cer 文件是直接可以用X509Certificate2 对象来读取的,但 .cer 文件 不便于存储。
“公钥证书” .pem 文件内容如下:
-----BEGIN CERTIFICATE----- MIICnzCCAggCCQDbr9OvJHgzmDANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UEBhMC RUUxETAPBgNVBAgMCEhhcmp1bWFhMRAwDgYDVQQHDAdUYWxsaW5uMREwDwYDVQQK DAhFZXRhc29mdDERMA8GA1UECwwIYmFua2xpbmsxFjAUBgNVBAMMDXBhbmdhbGlu ay5uZXQxITAfBgkqhkiG9w0BCQEWEmVldGFzb2Z0QG9ubGluZS5lZTAeFw0xNDEy MjQxNjI1MjdaFw0zNDEyMTkxNjI1MjdaMIGTMQswCQYDVQQGEwJFRTERMA8GA1UE CAwISGFyanVtYWExEDAOBgNVBAcMB1RhbGxpbm4xETAPBgNVBAoMCEVldGFzb2Z0 MREwDwYDVQQLDAhiYW5rbGluazEWMBQGA1UEAwwNcGFuZ2FsaW5rLm5ldDEhMB8G CSqGSIb3DQEJARYSZWV0YXNvZnRAb25saW5lLmVlMIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDCi9usnv8rJLBeBgHhbM/80zPUOlkuH0uYrdzj/zxQSZS0QEoH yVvosEWqO34+17CzQ0sc34kzK5qhLws7AKetjLH7cpgmVH5YnQxKgZ2a5I5mpj02 v9rjwDSKX2ZDXCeRUdnZa26beMcX/i1C9jxk9tpE2NWud910yHPRpnAQFwIDAQAB MA0GCSqGSIb3DQEBBQUAA4GBAFmlXa8NkR2OP0bC0EapmCaoObUG2WOi6Fhl2dBB PInJq6tzv+YtMbaIAPANo1EzBeBcQTRvxgGIrqE/JJkjDhOvwxjdNcxp7Mt+7hkk PI55KkKAfOeE0ss0EUcCdnyCGAXdhJfUCxJydg0PaVpE70FXUcLZcZXfT968mDOC NpaS -----END CERTIFICATE-----如果导出公钥,或转为RSACryptoServiceProvider 对象呢?参照了:https://stackoverflow.com/questions/27642180/how-to-create-public-key-from-certificate代码如下:
string pemPublicCert = Path.Combine(Application.StartupPath, "CCQTGBtest.pem"); string base64X509Cert = "";//"公钥证书"字符串 /* -----BEGIN CERTIFICATE----- MIICnzCCAggCCQDbr9OvJHgzmDANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UEBhMC RUUxETAPBgNVBAgMCEhhcmp1bWFhMRAwDgYDVQQHDAdUYWxsaW5uMREwDwYDVQQK DAhFZXRhc29mdDERMA8GA1UECwwIYmFua2xpbmsxFjAUBgNVBAMMDXBhbmdhbGlu ay5uZXQxITAfBgkqhkiG9w0BCQEWEmVldGFzb2Z0QG9ubGluZS5lZTAeFw0xNDEy MjQxNjI1MjdaFw0zNDEyMTkxNjI1MjdaMIGTMQswCQYDVQQGEwJFRTERMA8GA1UE CAwISGFyanVtYWExEDAOBgNVBAcMB1RhbGxpbm4xETAPBgNVBAoMCEVldGFzb2Z0 MREwDwYDVQQLDAhiYW5rbGluazEWMBQGA1UEAwwNcGFuZ2FsaW5rLm5ldDEhMB8G CSqGSIb3DQEJARYSZWV0YXNvZnRAb25saW5lLmVlMIGfMA0GCSqGSIb3DQEBAQUA A4GNADCBiQKBgQDCi9usnv8rJLBeBgHhbM/80zPUOlkuH0uYrdzj/zxQSZS0QEoH yVvosEWqO34+17CzQ0sc34kzK5qhLws7AKetjLH7cpgmVH5YnQxKgZ2a5I5mpj02 v9rjwDSKX2ZDXCeRUdnZa26beMcX/i1C9jxk9tpE2NWud910yHPRpnAQFwIDAQAB MA0GCSqGSIb3DQEBBQUAA4GBAFmlXa8NkR2OP0bC0EapmCaoObUG2WOi6Fhl2dBB PInJq6tzv+YtMbaIAPANo1EzBeBcQTRvxgGIrqE/JJkjDhOvwxjdNcxp7Mt+7hkk PI55KkKAfOeE0ss0EUcCdnyCGAXdhJfUCxJydg0PaVpE70FXUcLZcZXfT968mDOC NpaS -----END CERTIFICATE----- */ using (FileStream fs = new FileStream(pemPublicCert, FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) { base64X509Cert = sr.ReadToEnd().Trim(); } } //提取纯字符串 base64X509Cert = base64X509Cert.Replace("-----BEGIN CERTIFICATE-----", "").Replace("-----END CERTIFICATE-----", "").Replace("\r", "").Replace("\n", ""); //https://stackoverflow.com/questions/27642180/how-to-create-public-key-from-certificate //转换为“公钥”对象 var derCert = Convert.FromBase64String(base64X509Cert); var x509 = new X509Certificate2(derCert); RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)x509.PublicKey.Key; MessageBox.Show(rsa.ToXmlString(false)); //Console.WriteLine(rsa.ToXmlString(false));
--