Exemplo n.º 1
0
        /// <summary>
        /// Export this <see cref="EncryptionKeyPair"/> into a PEM file.
        /// </summary>
        /// <param name="path">Only path name. DO NOT include filename.</param>
        /// <param name="filename">
        /// Filename to export, if not specified it sets to pub.key/priv.key adequately.
        /// DO NOT include extension.
        /// </param>
        /// <param name="includePrivate">On exporting to file include private key content, otherwise false</param>
        /// <exception cref="ArgumentNullException">Directory not specified.</exception>
        /// <exception cref="ArgumentException">Directory not found.</exception>
        /// <exception cref="InvalidOperationException">Error when exporting key.</exception>
        public void ExportAsPEMFile(string path, string filename = "key", bool includePrivate = false)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException(
                          paramName: nameof(path),
                          message: "Directory not specified.");
            }

            if (!Directory.Exists(path))
            {
                throw new ArgumentException(
                          paramName: nameof(path),
                          message: "Directory not found.");
            }

            // trying to export private key from a public key
            if (PublicOnly && includePrivate)
            {
                throw new InvalidOperationException(
                          message: "Impossible to export private content from a public key.");
            }

            using (var rsa = new RSACryptoServiceProvider(this.KeySize))
            {
                try
                {
                    rsa.ImportParameters(this.RSAParameters);
                    if (includePrivate)
                    {
                        filename = "priv." + filename + ".pem";
                        string fileContent = rsa.ExportRSAPrivateKeyAsPEM();
                        FileManipulation.SaveFile(fileContent.ToByteArray(), path, filename, attributes: FileAttributes.ReadOnly);
                    }
                    else
                    {
                        filename = "pub." + filename + ".pem";
                        string fileContent = rsa.ExportRSAPublicKeyAsPEM();
                        FileManipulation.SaveFile(fileContent.ToByteArray(), path, filename, attributes: FileAttributes.ReadOnly);
                    }
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }