/// <summary> /// 从证书中提取公钥并转换为PEM格式 /// </summary> /// <param name="input">证书</param> /// <returns>PEM格式公钥</returns> public static string ExtractPemPublicKeyFromCert(X509Certificate input) { using (var cert = new System.Security.Cryptography.X509Certificates.X509Certificate2(input.GetEncoded())) { byte[] algOid; switch (cert.GetKeyAlgorithm()) { case "1.2.840.113549.1.1.1": algOid = new byte[] { 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 }; break; default: throw new ArgumentOutOfRangeException("Need an OID lookup for " + cert.GetKeyAlgorithm()); } var algParams = cert.GetKeyAlgorithmParameters(); var publicKey = WrapAsBitString(cert.GetPublicKey()); var algId = BuildSimpleDerSequence(algOid, algParams); var spki = BuildSimpleDerSequence(algId, publicKey); return(Convert.ToBase64String(spki)); } }
/// <summary> /// Gets the public key algorithm for the certificate. /// </summary> /// <remarks> /// Gets the public key algorithm for the ceretificate. /// </remarks> /// <returns>The public key algorithm.</returns> /// <param name="certificate">The certificate.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="certificate"/> is <c>null</c>. /// </exception> public static PublicKeyAlgorithm GetPublicKeyAlgorithm(this X509Certificate2 certificate) { if (certificate == null) { throw new ArgumentNullException(nameof(certificate)); } var identifier = certificate.GetKeyAlgorithm(); var oid = new Oid(identifier); switch (oid.FriendlyName) { case "DSA": return(PublicKeyAlgorithm.Dsa); case "RSA": return(PublicKeyAlgorithm.RsaGeneral); case "ECC": return(PublicKeyAlgorithm.EllipticCurve); case "DH": return(PublicKeyAlgorithm.DiffieHellman); default: return(PublicKeyAlgorithm.None); } }