コード例 #1
0
        /// <summary>
        /// Exports the current key in the PKCS#8 EncryptedPrivateKeyInfo format with a char-based password.
        /// </summary>
        /// <param name="csp"></param>
        /// <param name="password">The password to use when encrypting the key material.</param>
        /// <param name="pbeParameters">The password-based encryption (PBE) parameters to use when encrypting the key material.</param>
        /// <returns cref="String">A PEMBase64 string containing the PKCS#8 EncryptedPrivateKeyInfo representation of this key.</returns>
        /// <remarks>
        /// When pbeParameters indicates an algorithm that uses PBKDF2 (Password-
        /// Based Key Derivation Function 2), the password is converted to bytes via the
        /// UTF-8 encoding.
        /// </remarks>
        /// <exception cref="CryptographicException">The key could not be exported.</exception>
        public static string ExportEncryptedPkcs8PrivateKeyAsPEM(this RSACryptoServiceProvider csp, ReadOnlySpan <char> password, PbeParameters pbeParameters)
        {
            var result = csp.ExportEncryptedPkcs8PrivateKey(password, pbeParameters);
            var base64 = Convert.ToBase64String(result).ToCharArray();

            using (var sw = new StringWriter())
            {
                sw.Write("-----BEGIN ENCRYPTED PRIVATE KEY-----\n");
                for (var i = 0; i < base64.Length; i += 64)
                {
                    sw.Write(base64, i, Math.Min(64, base64.Length - i));
                    sw.Write('\n');
                }
                sw.Write("-----END ENCRYPTED PRIVATE KEY-----");
                return(sw.ToString());
            }
        }