public static PgpProfile Generate(string email, string password = null) { if (password == null) { password = Internet.GetPassword(); } var p = new PgpProfile(); using (var pgp = new PGP()) { const string publicFile = "public.asc"; const string privateFile = "private.asc"; // Generate keys pgp.GenerateKey(publicFile, privateFile, email, password); p.Email = email; p.Password = password; p.PublicKey = File.ReadAllText(publicFile); p.PrivateKey = File.ReadAllText(privateFile); File.Delete(publicFile); File.Delete(privateFile); } return(p); }
static void Main(string[] args) { using (PGP pgp = new PGP()) { // Generate keys pgp.GenerateKey(@"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "*****@*****.**", "password"); // Encrypt file pgp.EncryptFile(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\public.asc", true, true); // Encrypt and sign file pgp.EncryptFileAndSign(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "password", true, true); // Decrypt file pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\content__decrypted.txt", @"C:\TEMP\keys\private.asc", "password"); // Decrypt signed file pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\content__decrypted_signed.txt", @"C:\TEMP\keys\private.asc", "password"); // Encrypt stream using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content.txt", FileMode.Open)) using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__encrypted2.pgp")) using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open)) pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true); // Decrypt stream using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open)) using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__decrypted2.txt")) using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open)) pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password"); } }
static void Main() { using (PGP pgp = new PGP()) { Console.WriteLine($"Welcome to PGPEncryptConsoleApp!"); string tempPath = Path.Combine(Path.GetTempPath(), "pgpcore"); string publicKeyFilePath = Path.Combine(tempPath, "public.asc"); string publicKeyBase64FilePath = Path.Combine(tempPath, "public_base64.asc"); string privateKeyFilePath = Path.Combine(tempPath, "private.asc"); string privateKeyBase64FilePath = Path.Combine(tempPath, "private_base64.asc"); string contentFilePath = Path.Combine(tempPath, "content.txt"); string encryptedFilePath = Path.Combine(tempPath, "content_encrypted.pgp"); string decryptedFilePath = Path.Combine(tempPath, "content_decrypted.txt"); string username = null; int strength = 4096; int certainty = 8; //Create temp direcory and test file Directory.CreateDirectory(tempPath); Console.WriteLine($"Created temp directory: {tempPath}"); File.WriteAllText(contentFilePath, "Hello World PGPCore!"); Console.WriteLine($"Created test file: {contentFilePath}"); // Create a password Console.WriteLine($"Enter a password or press enter to not use a password"); string password = ReadLine.ReadPassword(); // Generate keys Spinner.Start("Generating keys...", () => { pgp.GenerateKey(publicKeyFilePath, privateKeyFilePath, username, password, strength, certainty); }); string publicKey = File.ReadAllText(publicKeyFilePath); File.WriteAllText(publicKeyBase64FilePath, Convert.ToBase64String(Encoding.UTF8.GetBytes(publicKey))); Console.WriteLine($"Created public key: {publicKeyFilePath}"); Console.WriteLine($"Converted public key to base64: {publicKeyBase64FilePath}"); Console.WriteLine($"Created private key: {privateKeyFilePath}"); string privateKey = File.ReadAllText(privateKeyFilePath); File.WriteAllText(privateKeyBase64FilePath, Convert.ToBase64String(Encoding.UTF8.GetBytes(privateKey))); Console.WriteLine($"Created private key: {privateKeyFilePath}"); Console.WriteLine($"Converted private key to base64: {privateKeyBase64FilePath}"); // Encrypt file pgp.EncryptFile(contentFilePath, encryptedFilePath, publicKeyFilePath, true, true); Console.WriteLine($"Encrypted test file: {encryptedFilePath}"); // Decrypt file pgp.DecryptFile(encryptedFilePath, decryptedFilePath, privateKeyFilePath, password); Console.WriteLine($"Decrypted test file: {decryptedFilePath}"); Console.WriteLine("Press any key to exit"); Console.ReadLine(); } }
private void Arrange(KeyType keyType) { Directory.CreateDirectory(keyDirectory); Directory.CreateDirectory(contentDirectory); PGP pgp = new PGP(); // Create keys if (keyType == KeyType.Generated) { pgp.GenerateKey(publicKeyFilePath1, privateKeyFilePath1, userName1, password1); pgp.GenerateKey(publicKeyFilePath2, privateKeyFilePath2, userName2, password2); } else if (keyType == KeyType.Known) { using (StreamWriter streamWriter = File.CreateText(publicKeyFilePath1)) { streamWriter.WriteLine(publicKey1); } using (StreamWriter streamWriter = File.CreateText(publicKeyFilePath2)) { streamWriter.WriteLine(publicKey2); } using (StreamWriter streamWriter = File.CreateText(privateKeyFilePath1)) { streamWriter.WriteLine(privatekey1); } using (StreamWriter streamWriter = File.CreateText(privateKeyFilePath2)) { streamWriter.WriteLine(privatekey2); } } // Create content file using (StreamWriter streamWriter = File.CreateText(contentFilePath)) { streamWriter.WriteLine(content); } }
private static void CreatePgpKey() { if (File.Exists(_publicKeyPath) || File.Exists(_privateKeyPath)) { Console.WriteLine($"Key files exist: [{_publicKeyPath}] and [{_privateKeyPath}]. Please move/remove them before key creation."); return; } Pgp.GenerateKey(_publicKeyPath, _privateKeyPath, "default", ""); Console.WriteLine("PGP key successfully created."); }
/// <summary> Generate a public/private <see cref="KeyPair"/>. </summary> /// <param name="username"> Username bound to keypair </param> /// <param name="password"> Password bound to keypair </param> /// <param name="strength"> Encryption strength, defaults to 1024. </param> /// <param name="certainty"> Encryption certainty, defaults to 8</param> /// <returns> <see cref="KeyPair"/> with newly generated public/private keys. </returns> public static KeyPair GenerateKey(string username = "******", string password = "******", int strength = 1024, int certainty = 8) { Guid id = Guid.NewGuid(); MemoryStream publicStream = new MemoryStream(); MemoryStream privateStream = new MemoryStream(); instance.GenerateKey(publicStream, privateStream, username, password, strength, certainty); string publicKey = Encoding.UTF8.GetString(publicStream.ToArray()).Replace("\r\n", "\n"); string privateKey = Encoding.UTF8.GetString(privateStream.ToArray()).Replace("\r\n", "\n"); return(new KeyPair(publicKey, privateKey)); }
public void GenerateKey_CreatePublicPrivateKeyFiles() { // Arrange Directory.CreateDirectory(keyDirectory); PGP pgp = new PGP(); // Act pgp.GenerateKey(publicKeyFilePath1, privateKeyFilePath1, password1); // Assert Assert.True(File.Exists(publicKeyFilePath1)); Assert.True(File.Exists(privateKeyFilePath1)); }
public PgpDto GenerateKeys(string userName, string password, int length = 2048) { var pgpDto = new PgpDto(); using (var pgp = new PGP()) { var publicKeyStream = new MemoryStream(); var privateKeyStream = new MemoryStream(); pgp.GenerateKey(publicKeyStream, privateKeyStream, userName, password, length); pgpDto.PrivateKey = GetStringFromStream(privateKeyStream); pgpDto.PublicKey = GetStringFromStream(publicKeyStream); } return(pgpDto); }
public void GenerateKey_CreatePublicPrivateKeyFiles() { // Arrange TestFactory testFactory = new TestFactory(); testFactory.Arrange(); PGP pgp = new PGP(); // Act pgp.GenerateKey(testFactory.PublicKeyFilePath, testFactory.PrivateKeyFilePath, testFactory.Password); // Assert Assert.True(File.Exists(testFactory.PublicKeyFilePath)); Assert.True(File.Exists(testFactory.PrivateKeyFilePath)); // Cleanup testFactory.Teardown(); }
private bool GenerateKeyChain(string path, string email, string password) { using (PGP pgp = new PGP()) { try { pgp.GenerateKey(path + @"\public.asc", path + @"\private.asc", email, password, 4096); CheckList[1] = 1; Properties.Settings.Default.public_key = path + @"\public.asc"; Properties.Settings.Default.Save(); return(true); } catch (Exception e) { CheckList[1] = 0; return(false); } } }
public void Arrange(KeyType keyType) { Arrange(); PGP pgp = new PGP(); // Create keys if (keyType == KeyType.Generated) { pgp.GenerateKey(PublicKeyFilePath, PrivateKeyFilePath, UserName, Password); } else if (keyType == KeyType.Known) { using (StreamWriter streamWriter = File.CreateText(PublicKeyFilePath)) { streamWriter.WriteLine(Constants.PUBLICKEY1); } using (StreamWriter streamWriter = File.CreateText(PrivateKeyFilePath)) { streamWriter.WriteLine(Constants.PRIVATEKEY1); } _userName = Constants.USERNAME1; _password = Constants.PASSWORD1; } else if (keyType == KeyType.KnownGpg) { using (StreamWriter streamWriter = File.CreateText(PublicKeyFilePath)) { streamWriter.WriteLine(Constants.PUBLICGPGKEY1); } using (StreamWriter streamWriter = File.CreateText(PrivateKeyFilePath)) { streamWriter.WriteLine(Constants.PRIVATEGPGKEY1); } _userName = Constants.USERNAME1; _password = Constants.PASSWORD1; } }
private void btnCreateKey_Click(object sender, EventArgs e) { string currentDirectory = Directory.GetCurrentDirectory(); string publicKeyName = txtPublicKeyName.Text; string privateKeyName = txtPrivateKeyName.Text; string email = txtEmailAddress.Text; string password = txtPassword.Text; string confirmPassword = txtConfirmPassword.Text; publicKeyName = $"{Regex.Replace(publicKeyName, "[^0-9a-zA-Z]+", "_")}_Public.asc"; privateKeyName = $"{Regex.Replace(privateKeyName, "[^0-9a-zA-Z]+", "_")}_Private.asc"; if (publicKeyName.Trim().Length < 1 || privateKeyName.Trim().Length < 1 || email.Trim().Length < 1 || password.Trim().Length < 1 || confirmPassword.Trim().Length < 1) { MessageBox.Show("Please fill all fields!", "Blank Fields", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } bool isEmail = Regex.IsMatch(email, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase); //Regex expr = new Regex(@"^[a-zA-Z][\w\.-][a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"); if (!isEmail) { txtEmailAddress.Focus(); txtEmailAddress.SelectAll(); MessageBox.Show("Please enter a valid Email"); return; } if (password != confirmPassword) { txtPassword.Focus(); txtPassword.SelectAll(); MessageBox.Show("The password entered and the one confirmed do not match!", "Password Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else { if (!PasswordPolicy.IsValid(password)) { txtPassword.Focus(); txtPassword.SelectAll(); MessageBox.Show("Password must have minimum of 6 characters, be alphanumeric, and include a special character!", "Password Violation", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } } //string rootDirectory = $"{encryptionKeyLocation}{subFolder}"; try { if (string.IsNullOrEmpty(rootDirectory)) { MessageBox.Show("No Key Export location selected!"); return; } rootDirectory = $"{rootDirectory}\\{subFolder}"; if (!Directory.Exists(rootDirectory)) { Directory.CreateDirectory(rootDirectory); } using (PGP pgp = new PGP()) { pgp.GenerateKey($"{rootDirectory}\\{publicKeyName}", $"{rootDirectory}{privateKeyName}", email, password); lnkLblDisplayOutputPath.Text = $"Key pair created to {rootDirectory}"; //fullPath = rootDirectory; btnCreateKey.Enabled = false; MessageBox.Show("Key created", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { Console.WriteLine($"Error: An error occured creating pgp key pair {rootDirectory}{publicKeyName}---->>{rootDirectory}{privateKeyName}, Message: {ex.Message}"); MessageBox.Show("Key not created. check console for errors", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
static void Main(string[] args) { using (PGP pgp = new PGP()) { // Generate keys pgp.GenerateKey(@"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "*****@*****.**", "password"); pgp.GenerateKey(@"C:\TEMP\keys\public2.asc", @"C:\TEMP\keys\private2.asc", "*****@*****.**", "password2"); // Encrypt file pgp.EncryptFile(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\public.asc", true, true); // Encrypt file with multiple keys string[] publicKeys = { @"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\public2.asc" }; pgp.EncryptFile(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_multiple.pgp", publicKeys, true, true); // Encrypt and sign file pgp.EncryptFileAndSign(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "password", true, true); // Encrypt and sign multiple file pgp.EncryptFileAndSign(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_signed_multiple.pgp", publicKeys, @"C:\TEMP\keys\private.asc", "password", true, true); // Decrypt file pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\content__decrypted.txt", @"C:\TEMP\keys\private.asc", "password"); // Decrypt multiple file pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_multiple.pgp", @"C:\TEMP\keys\content__decrypted_multiple.txt", @"C:\TEMP\keys\private.asc", "password"); pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_multiple.pgp", @"C:\TEMP\keys\content__decrypted_multiple2.txt", @"C:\TEMP\keys\private2.asc", "password2"); // Decrypt signed file pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\content__decrypted_signed.txt", @"C:\TEMP\keys\private.asc", "password"); // Decrypt signed multiple file pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed_multiple.pgp", @"C:\TEMP\keys\content__decrypted_signed_multiple.txt", @"C:\TEMP\keys\private.asc", "password"); pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed_multiple.pgp", @"C:\TEMP\keys\content__decrypted_signed_multiple2.txt", @"C:\TEMP\keys\private2.asc", "password2"); // Encrypt stream using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content.txt", FileMode.Open)) using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__encrypted2.pgp")) using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open)) pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true); // Decrypt stream using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open)) using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__decrypted2.txt")) using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open)) pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password"); // Encrypt and decrypt streams using (Stream inputFileStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("Streaming test message"))) { using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open)) { using (Stream encryptedMemoryStream = new MemoryStream()) { pgp.EncryptStream(inputFileStream, encryptedMemoryStream, publicKeyStream); encryptedMemoryStream.Seek(0, SeekOrigin.Begin); StreamReader encryptedReader = new StreamReader(encryptedMemoryStream); // Reset stream to beginning encryptedMemoryStream.Seek(0, SeekOrigin.Begin); string encryptedText = encryptedReader.ReadToEnd(); Console.WriteLine(encryptedText); // Reset stream to beginning again // Only necessary as stream read to end above for demo output encryptedMemoryStream.Seek(0, SeekOrigin.Begin); using (Stream decryptedMemoryStream = new MemoryStream()) { using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open)) { pgp.DecryptStream(encryptedMemoryStream, decryptedMemoryStream, privateKeyStream, "password"); decryptedMemoryStream.Seek(0, SeekOrigin.Begin); StreamReader decryptedReader = new StreamReader(decryptedMemoryStream); string decryptedText = decryptedReader.ReadToEnd(); Console.WriteLine(decryptedText); } } } } } // Encrypt key and sign stream using (Stream inputFileStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("Streaming signed test message"))) { using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open)) { using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open)) { using (Stream encryptedMemoryStream = new MemoryStream()) { pgp.EncryptStreamAndSign(inputFileStream, encryptedMemoryStream, publicKeyStream, privateKeyStream, "password"); // Reset stream to beginning encryptedMemoryStream.Seek(0, SeekOrigin.Begin); StreamReader encryptedReader = new StreamReader(encryptedMemoryStream); string encryptedText = encryptedReader.ReadToEnd(); Console.WriteLine(encryptedText); } } } } } }
private static void ProcessFiles(Options opts) { timer.Stop(); PGP pgp = new PGP(); // Key generation if (opts.KeyGen) { if (opts.Daemon) { Log("Can't generate keys when running as daemon.", LEVEL.Error); Environment.Exit(1); } if (!File.Exists(opts.KeyPath + PUBLIC_KEY) || !File.Exists(opts.KeyPath + PRIVATE_KEY)) { try { pgp.GenerateKey(opts.KeyPath + PUBLIC_KEY, opts.KeyPath + PRIVATE_KEY, password: opts.Password); } catch (Exception ex) { Log(ex.ToString(), LEVEL.Error); Environment.Exit(1); } Log("Keypair written to " + opts.KeyPath + "/", LEVEL.Info); Environment.Exit(0); } else { Log("Key files already present, will not overwrite for security reasons. Exiting", LEVEL.Error); Environment.Exit(1); } } // Reviewing Deletions if (opts.ReviewDeletions) { foreach (string x in HashHelper.GetDeletedFiles()) { Log(x); } Environment.Exit(0); } if (opts.ApplyDeletions) { DeleteFiles(opts, pgp); // Pgp passed because we need to decrypt the file before deleting. Environment.Exit(0); } // File Handling Log("Searching files and directories..."); string[] files = Directory.GetFiles(opts.Inputdir, "*", SearchOption.AllDirectories); string[] dirs = Directory.GetDirectories(opts.Inputdir, "*", SearchOption.AllDirectories); Log("Creating directories..."); foreach (string dir in dirs) { try { if (!Directory.Exists(dir.Replace(opts.Inputdir, opts.Ouputdir))) { try { Directory.CreateDirectory(dir.Replace(opts.Inputdir, opts.Ouputdir)); Log("Created " + dir.Replace(opts.Inputdir, opts.Ouputdir), LEVEL.Info); } catch (Exception ex) { Log(ex.ToString(), LEVEL.Error); Environment.Exit(1); } } } catch (Exception ex) { Log(ex.ToString(), LEVEL.Error); Environment.Exit(1); } } Log("Using keyfile: " + opts.KeyPath + PRIVATE_KEY, LEVEL.Info); Log("Processing " + files.Count().ToString() + " files.", LEVEL.Info); int total = files.Count(); int count = 1; foreach (string file in files) { Log(count.ToString() + "/" + total.ToString()); if (opts.Decrypt) { Log("Decrypting " + file); try { pgp.DecryptFile(file, opts.Ouputdir + "/" + Path.GetFileName(file).Replace(".pgp", ""), opts.KeyPath + PRIVATE_KEY, opts.Password); } catch (Exception ex) { Log(ex.ToString(), LEVEL.Error); } Log("Wrote " + opts.Ouputdir + "/" + Path.GetFileName(file), LEVEL.Ok); } else { string fileHash = HashHelper.GetHashFromFile(file); if (HashHelper.GetHashFromDb(file) != fileHash) { bool update = false; if (HashHelper.FindDupeHash(fileHash)) { Log("Found an existing hash for file: " + file + ", skipping.", LEVEL.Warning); } else { if (HashHelper.FindDupeFileName(file)) { update = true; Log("Found another file with the same name, updating hash and re-encrypting.", LEVEL.Info); } try { Log("Encrypting " + file, LEVEL.Info); pgp.EncryptFile(file, file.Replace(opts.Inputdir, opts.Ouputdir) + ".pgp", opts.KeyPath + PUBLIC_KEY); Log("Storing hash " + fileHash + " for " + file, LEVEL.Info); HashHelper.StoreHash(file, fileHash, update); Log("Wrote " + file.Replace(opts.Inputdir, opts.Ouputdir) + ".pgp", LEVEL.Ok); } catch (Exception ex) { Log(ex.ToString(), LEVEL.Error); } } } else { Log("Skipping " + file + " -> Unchanged."); } } count++; } // Exit after loop if only used for decryption if (opts.Decrypt) { Environment.Exit(0); } // Check deletions Log("Marking files for deletions...", LEVEL.Info); string[] dbFiles = HashHelper.GetDbFilesList(); foreach (string file in dbFiles) { if (files.ToList().IndexOf(file) < 0) { HashHelper.MarkForDeletion(file); Log("File " + file + " is not in the source directory and was marked for deletion."); } } // Delete if (opts.PropagateDeletions) { DeleteFiles(opts, pgp); } Log("Complete.", LEVEL.Info); timer.Start(); }
public void GenerateKey(string publicKeyPath, string privateKeyPath, string email, string password, int strength = 1024, int certainty = 8) { TryExecute(() => crypter.GenerateKey(publicKeyPath, privateKeyPath, email, password, strength, certainty)); }