Exemplo n.º 1
0
        /// <summary>
        /// Export an <see cref="EncryptionKeyPair"/> as an encrypted key using a password./>
        /// </summary>
        /// <param name="password">password to encrypt key.</param>
        /// <param name="path">output path</param>
        /// <param name="filename">output file name</param>
        /// <exception cref="ArgumentNullException">Password or path are missing.</exception>
        /// <exception cref="ArgumentException">File not found.</exception>
        /// <exception cref="InvalidOperationException">Impossible to export as encrypted key when public only.</exception>
        /// <exception cref="CryptographicException">Password is incorrect.</exception>
        public void ExportAsPKCS8(string password, string path, string filename = "key")
        {
            if (string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException(
                          paramName: nameof(password),
                          message: "In order to export as an encrypted key a password is needed.");
            }
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(
                          paramName: nameof(path),
                          message: "Directory not specified.");
            }

            if (this.PublicOnly)
            {
                throw new InvalidOperationException(
                          message: "Must be a private key to export as an encrypted key.");
            }

            filename = $"enc.{filename}.pem";

            using (var rsa = new RSACryptoServiceProvider(this.KeySize))
            {
                try
                {
                    rsa.ImportParameters(this.RSAParameters);
                    var    hashalg     = new HashAlgorithmName("SHA1");
                    var    pbe         = new PbeParameters(PbeEncryptionAlgorithm.Aes256Cbc, hashalg, 64);
                    string fileContent = rsa.ExportEncryptedPkcs8PrivateKeyAsPEM(password, pbe);

                    FileManipulation.SaveFile(fileContent.ToByteArray(), path, filename, attributes: FileAttributes.ReadOnly);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }