Exemplo n.º 1
0
        /// <summary>
        /// Export RSA private key
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="type"></param>
        /// <param name="usePemFormat">Only valid if the private key type is PKCS#1 and PKCS#8.</param>
        /// <returns></returns>
        public static string ExportPrivateKey(this RSA rsa, RSAKeyType type, bool usePemFormat = false)
        {
            var key = string.Empty;

            switch (type)
            {
            case RSAKeyType.Pkcs1:
                key = Convert.ToBase64String(rsa.ExportRSAPrivateKey());
                break;

            case RSAKeyType.Pkcs8:
                key = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
                break;

            case RSAKeyType.Xml:
                key = rsa.ExportXmlPrivateKey();
                break;
            }

            if (usePemFormat && type != RSAKeyType.Xml)
            {
                key = PemFormatUtil.GetPrivateKeyFormat(type, key);
            }

            return(key);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Export RSA private key
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="type"></param>
        /// <param name="usePemFormat">Only valid if the private key type is PKCS#1 and PKCS#8.</param>
        /// <returns></returns>
        public static string ExportPrivateKey(this RSA rsa, RSAKeyType type, bool usePemFormat = false)
        {
            var key = type switch
            {
                RSAKeyType.Pkcs1 => Convert.ToBase64String(rsa.ExportRSAPrivateKey()),
                RSAKeyType.Pkcs8 => Convert.ToBase64String(rsa.ExportPkcs8PrivateKey()),
                RSAKeyType.Xml => rsa.ExportXmlPrivateKey(),
                _ => string.Empty
            };

            if (usePemFormat && type != RSAKeyType.Xml)
            {
                key = PemFormatUtil.GetPrivateKeyFormat(type, key);
            }

            return(key);
        }