Encrypting with OpenPGP Library for .NET
This chapter illustrates OpenPGP encryption with C# and VB.NET examples.
In order to encrypt a file we usually need the public key of the recipient(s). There is also an option to encrypt a file with a password.
Originally OpenPGP applications encrypted a single data file in one OpenPGP archive. However newer implementations (PGP(r) 9+, GnuPG 2+) and our library also support encrypting multiple files and folders into a single encrypted file.
Additional parameters
The encrypt methods provided by the library have two additional parameters that reflect the encryption output: asciiArmor and withIntegrityCheck.
- asciiArmor specifies the format of the result file, when true the file is in ASCII armored Operating System neutral form usually with .asc extension (e.g. suitable for Email attachments), when false the output file is in a binary format (usually with file name extension .pgp).
- withIntegrityCheck specifies if additional integrity check information is appended to the encrypted file. For compatibility with PGP 6.5 shall be false.
List of examples
Encrypting a File
1. with public key located in a file
2. with public key located in a KeyStore file
Encrypting a String message
3. with public key located in a file
4. with public key located in a KeyStore
Encrypting for multiple recipients
5. with recipients’ keys located in files
Encrypt a Stream
6. encrypt a stream with recipient public key provided also as stream
7. encrypt a stream with recipient public key in a KeyStore object
Encrypting multiple Files
8. encrypt multiple Files in one OpenPGP archive
Encrypting with a Password
9. encrypting a file only with a password
1. Encrypt file with recipient public key located in a file
This example demonstrates OpenPGP file encryption, providing public key stored directly in a file.
C# example
using System.IO; using DidiSoft; class EncryptDemo { public void Demo() { // create an instance of the library PGPLib pgp = new PGPLib(); // specify should the output be ASCII or binary bool asciiArmor = false; // should additional integrity information be added // set to false for compatibility with older versions of PGP such as 6.5.8. bool withIntegrityCheck = false; pgp.EncryptFile(@"C:\Test\INPUT.txt", @"C:\Test\public_key.asc", @"C:\Test\OUTPUT.pgp", asciiArmor, withIntegrityCheck); } }
VB.NET example
Imports System.IO Imports DidiSoft Class EncryptDemo Public Sub Demo() ' create an instance of the library Dim pgp As New PGPLib() ' specify should the output be ASCII or binary Dim asciiArmor As Boolean = False ' should additional integrity information be added ' set to False for compatibility with older versions of PGP such as 6.5.8. Dim withIntegrityCheck As Boolean = False pgp.EncryptFile("C:\Test\INPUT.txt", _ "C:\Test\public_key.asc", _ "C:\Test\OUTPUT.pgp", _ asciiArmor, _ withIntegrityCheck) End Sub End Class
2. Encrypt file with recipient public key located in a KeyStore file
Storing our partners’ public keys in a KeyStore gives us one extra layer of security. For example how to import keys in a KeyStore see Import key ring in a KeyStore.
This sample shows how to encrypt a file with public key stored in a Key store
C# example
using System; using DidiSoft; public class KeyStoreEncryptFile { public static void Demo() { // initialize the key store KeyStore keyStore = new KeyStore(@"DataFiles\key.store", "keystore passphrase"); // create an instance of the library PGPLib pgp = new PGPLib(); String publicKeyUserId = "support@didisoft.com"; // specify should the output be ASCII or binary bool asciiArmor = false; // should additional integrity information be added // set to false for compatibility with older versions of PGP such as 6.5.8. bool integrityCheck = false; pgp.EncryptFile(@"DataFiles\INPUT.txt", keyStore, publicKeyUserId, @"DataFiles\OUTPUT.pgp", asciiArmor, integrityCheck); } }
VB.NET example
Imports System Imports DidiSoft Public Class KeyStoreEncryptFile Public Shared Sub Demo() ' initialize the key store Dim keyStore As New KeyStore("DataFiles\key.store", _ "keystore passphrase") ' create an instance of the library Dim pgp As New PGPLib() Dim publicKeyUserId As String = "support@didisoft.com" ' specify should the output be ASCII or binary Dim asciiArmor As Boolean = False ' should additional integrity information be added ' set to False for compatibility with older versions of PGP such as 6.5.8. Dim integrityCheck As Boolean = False pgp.EncryptFile("DataFiles\INPUT.txt", _ keyStore, _ publicKeyUserId, _ "DataFiles\OUTPUT.pgp", _ asciiArmor, _ integrityCheck) End Sub End Class
3. Encrypting a string message with public key located in a file
Sometimes we may prefer to encrypt a string message directly instead of writing it to a file. The output in this case is directly in ASCII armored format so there is no need of this parameter:
C# example
using System; using System.IO; using DidiSoft; class EncryptString { public void Demo() { // create an instance of the library PGPLib pgp = new PGPLib(); String encryptedString = pgp.EncryptString("The quick brown fox jumps.", new FileInfo(@"DataFiles\public.key")); } }
VB.NET example
Imports System Imports System.IO Imports DidiSoft Class EncryptString Public Shared Function Demo() As String ' create an instance of the library Dim pgp As New PGPLib() Dim encryptedString As String = _ pgp.EncryptString("The quick brown fox jumps.", _ New FileInfo("DataFiles\public.key")) Return encryptedString End Function End Class
4. Encrypting a string message with public key located in a KeyStore
In this example the public key of the recipient is stored in a KeyStore object and we encrypt a string message directly.
C# example
using System; using DidiSoft; class KeyStoreEncryptString { public void Demo() { string recipientKeyUserId = "support@didisoft.com"; // initialize the key store KeyStore ks = new KeyStore(@"DataFiles\key.store", "changeit"); // if this key store contains a key with this recipient userId // then encrypt, otherwise notify that there is no such key if (ks.ContainsKey(recipientKeyUserId)) { // create an instance of the library PGPLib pgp = new PGPLib(); string plainText = "C# pgp encrypt made easy."; string encryptedString = pgp.EncryptString(plainText, ks, recipientKeyUserId); } else { Console.WriteLine("No key with user Id:" + recipientKeyUserId + " was found in this key store."); } } }
VB.NET example
Imports System Imports DidiSoft Class KeyStoreEncryptString Public Sub Demo() Dim recipientKeyUserId As String = "support@didisoft.com" ' initialize the key store Dim ks As New KeyStore("DataFiles\key.store", _ "changeit") ' if this key store contains a key with this recipient userId ' then encrypt, otherwise notify that there is no such key If ks.ContainsKey(recipientKeyUserId) Then ' create an instance of the library Dim pgp As New PGPLib() Dim plainText As String = "VB.NET pgp encrypt made easy." Dim encryptedString As String = _ pgp.EncryptString(plainText, ks, _ recipientKeyUserId) Else Console.WriteLine("No key with user Id: " + _ recipientKeyUserId + _ " was found in this key store.") End If End Sub End Class
5. Encrypting a file for multiple recipients
OpenPGP allows to encrypt a file for multiple recipients if we have their public keys. The example below illustrates how to achieve that.
C# example
using System.IO; using DidiSoft.Pgp; class EncryptForMultiRecipientsDemo { public void Demo() { PGPLib pgp = new PGPLib(); // ASCII armor or binary bool asciiArmor = true; // append integrity protection check bool withIntegrityCheck = false; string[] recipientsPublicKeys = {@"c:\recipient_1_key.asc", @"c:\recipient_2_key.asc", @"c:\recipient_3_key.asc"}; pgp.EncryptFile(@"c:\INPUT.txt", recipientsPublicKeys, @"c:\OUTPUT.pgp", asciiArmor, withIntegrityCheck); } }
VB.NET example
Imports System.IO Imports DidiSoft.Pgp Class EncryptForMultiRecipientsDemo Public Sub Demo() Dim pgp As New PGPLib() ' ASCII armor or binary Dim asciiArmor As Boolean = True ' append integrity protection check Dim withIntegrityCheck As Boolean = False Dim recipientsPublicKeys As String() = _ New String() {"c:\recipient_1_key.asc", _ "c:\recipient_2_key.asc", _ "c:\recipient_3_key.asc"} pgp.EncryptFile("c:\INPUT.txt", _ recipientsPublicKeys, _ "c:\OUTPUT.pgp", _ asciiArmor, _ withIntegrityCheck) End Sub End Class
6. Encrypting a stream
The library allows to encrypt a stream. This can be useful for example if we do not want to write anything to the filesystem. The example below uses streams derived from files, but of course they can be any subclass of System.IO.Stream.
C# example
using System.IO; using DidiSoft.Pgp; class EncryptStreamDemo { public void Demo() { PGPLib pgp = new PGPLib(); Stream inputStream = File.OpenRead(@"DataFiles\INPUT.txt"); Stream publicKey = File.OpenRead(@"DataFiles\public.asc"); Stream encryptedStream = File.OpenWrite(@"DataFiles\OUTPUT.pgp"); // specify should the output be ASCII or binary bool asciiArmor = true; pgp.EncryptStream(inputStream, publicKey, encryptedStream, asciiArmor); } }
VB.NET example
Imports System.IO Imports DidiSoft.Pgp Class EncryptStreamDemo Public Sub Demo() Dim pgp As New PGPLib() Dim inputStream As Stream = File.OpenRead("DataFiles\INPUT.txt") Dim publicKey As Stream = File.OpenRead("DataFiles\public.asc") Dim encryptedStream As Stream = File.OpenWrite("DataFiles\OUTPUT.pgp") ' specify should the output be ASCII or binary Dim asciiArmor As Boolean = True pgp.EncryptStream(inputStream, publicKey, encryptedStream, asciiArmor) End Sub End Class
7. Encrypt a stream with recipient public key in a KeyStore object
This example is equivalent to the above one, except that the recipient public key used for encryption is stored in a KeyStore object.
C# example
using System.IO; using DidiSoft.Pgp; class EncryptStreamDemo { public void Demo() { // init the KeyStore KeyStore keyStore = new KeyStore(@"c:\my.keystore", "password123"); String recipientUserId = "support@didisoft.com"; PGPLib pgp = new PGPLib(); Stream inputStream = File.OpenRead(@"DataFiles\INPUT.txt"); Stream encryptedStream = File.OpenWrite(@"DataFiles\OUTPUT.pgp"); // specify should the output be ASCII or binary bool asciiArmor = true; pgp.EncryptStream(inputStream, keyStore, recipientUserId, encryptedStream, asciiArmor); } }
VB.NET example
Imports System.IO Imports DidiSoft.Pgp Class EncryptStreamDemo Public Sub Demo()
' init the KeyStore Dim keyStore As New KeyStore("c:\my.keystore", "password123") Dim recipientUserId As String = "support@didisoft.com" Dim pgp As New PGPLib() Dim inputStream As Stream = File.OpenRead("DataFiles\INPUT.txt") Dim encryptedStream As Stream = File.OpenWrite("DataFiles\OUTPUT.pgp") ' specify should the output be ASCII or binary Dim asciiArmor As Boolean = True pgp.EncryptStream(inputStream, keyStore, recipientUserId, encryptedStream, asciiArmor) End Sub End Class
8. Encrypting multiple files in one OpenPGP archive
Encrypting multiple file was first introduced by PGP(r) version 9 and later by other OpenPGP implementations.
Please have in mind that the recipient of the encrypted content should use PGP (r) 9+ or compatible software. This example will show how to encrypt multiple files in one OpenPGP archive with the library.
C# example
using System.IO; using DidiSoft; class EncryptFilesDemo { public void Demo() { // initialize the library PGPLib pgp = new PGPLib(); // specify should the output be ASCII or binary bool asciiArmor = false; // should additional integrity information be added bool withIntegrityCheck = false; // files to be encrypted FileInfo[] inputFiles = new FileInfo[] {new FileInfo(@"c:\INPUT1.txt"), new FileInfo(@"c:\INPUT2.txt")}; // one or more public keys to encrypt with FileInfo[] recipientPublicKeys = new FileInfo[] {new FileInfo(@"c:\public_key.asc")}; // encryption output FileInfo encryptedOutputFile = new FileInfo(@"c:\OUTPUT.pgp"); pgp.EncryptFiles(inputFiles, recipientPublicKeys, encryptedOutputFile, asciiArmor, withIntegrityCheck); } }
VB.NET example
Imports System.IO Imports DidiSoft Class EncryptFiles Public Shared Sub Demo() ' create an instance of the library Dim pgp As New PGPLib() ' specify should the output be ASCII or binary Dim asciiArmor As Boolean = True ' should additional integrity information be added Dim withIntegrityCheck As Boolean = True ' files to be encrypted Dim inputFiles As FileInfo() = _ New FileInfo() {New FileInfo("DataFiles\INPUT.txt"), _ New FileInfo("DataFiles\OUTPUT.txt")} ' one or more public keys to encrypt with Dim recipientPublicKeys As FileInfo() = _ New FileInfo() {New FileInfo("DataFiles\public.key")} ' encryption output Dim encryptedOutputFile As New FileInfo("DataFiles\OUTPUT.pgp") pgp.EncryptFiles(inputFiles, _ recipientPublicKeys, _ encryptedOutputFile, _ asciiArmor, _ withIntegrityCheck) End Sub End Class
(This feature is available as of version 1.6.2)
9. Encrypting a file only with a password
Encrypting a file with a password is less secure than the standard OpenPGP encryption performed with a public key. It is also known as conventional encryption or password based encryption (PBE). The recipient of the file will use the same password used for encryption to decrypt the file.
C# example
using System.IO; using DidiSoft.Pgp; class EncryptPasswordBasedDemo { public void Demo() { PGPLib pgp = new PGPLib(); // specify should the output be ASCII or binary bool asciiArmor = true; pgp.EncryptFilePBE(new FileInfo(@"DataFiles\INPUT.txt"), "password", new FileInfo(@"DataFiles\OUTPUT.pgp"), asciiArmor); } }
VB.NET example
Imports System.IO Imports DidiSoft.Pgp Class EncryptPasswordBasedDemo Public Sub Demo() Dim pgp As New PGPLib() ' specify should the output be ASCII or binary Dim asciiArmor As Boolean = True pgp.EncryptFilePBE(New FileInfo("DataFiles\INPUT.txt"), _ "password", _ New FileInfo("DataFiles\OUTPUT.pgp"), _ asciiArmor) End Sub End Class
Summary
In this chapter we have introduced OpenPGP encryption with OpenPGP Library for .NET. For other OpenPGP related operations like decrypting and one pass encrypting and signing, please check the table of contents.
Summary of the illustrated methods
| Method | Description |
| PgpLib.EncryptFile | Encrypts a file |
| PgpLib.EncryptString | Encrypts a string message |
| PgpLib.EncryptStream | Encrypts a stream into another stream |
| PgpLib.EncryptFiles | Encrypts multiple files and/or folders into a single OpenPGP archive |