Ejemplo n.º 1
0
        /// <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));
            }
        }