Encrypt a file with a public key
Public key-based encryption is the most common way of exchanging information securely within a PGP infrastructure. SecureBlackbox supports such encryption through a dedicated encryption mode of TElPGPWriter component.
First, we need to load the public key that we will be encrypting our file for. This is normally a public key of the intended recipient of the encrypted message.
TElPGPWriter expects the encryption key to be placed in a dedicated keyring object. Therefore if you want to use a particular key from your local keyring, you will need to load the whole keyring, find the needed key in it, and then put it into a separate keyring object:
TElPGPKeyring myKeys = new TElPGPKeyring(); myKeys.Load("pubring.pkr", "secring.skr", true); int keyIndex = myKeys.FindPublicKeyByEmailAddress("email@example.com"); TElPGPKeyring encryptionKeys = new TElPGPKeyring(); encryptionKeys.AddPublicKey(myKeys.get_PublicKeys(keyIndex));
Now, let's proceed to the encryption itself.
TElPGPWriter writer = new TElPGPWriter();
pgpWriter.EncryptionType = SBPGP.TSBPGPEncryptionType.etPublicKey;
pgpWriter.EncryptingKeys = encryptionKeys;
pgpWriter.Filename = "picture.jpg"; pgpWriter.Timestamp = DateTime.UtcNow;Note: an empty string assigned to the Filename property will make the components create a for-your-eyes-only file, which won't be decrypted to a persistent media.
pgpWriter.SymmetricKeyAlgorithm = SBPGPConstants.Unit.SB_PGP_ALGORITHM_SK_AES256;Note: in default configuration, TElPGPWriter comes with its own pre-defined encryption settings (CAST5 with 128 bit key, on the date of creation of this article).
pgpWriter.Armor = true; pgpWriter.Compress = true;
Note: in certain scenarios, especially where heavy multi-subkey structures are used, there might be a need to specify the exact subkey to be used for encryption. While SecureBlackbox does its best to find the appropriate encryption key or subkey automatically, sometimes this is not possible due to lack of information stored within the keys. If unsure about the purpose of a particular primary key or subkey (i.e. whether it is signing-only, encryption-only or both encryption and signing capable), SecureBlackbox always uses it for encryption. As a result, the resulting file may be encrypted with multiple keys, which might be confusing for the receiving software. You can tell TElPGPWriter that it must not encrypt the file for a particular key or subkey by setting its Enabled property to false. For instance, the following setting makes TElPGPWriter not encrypt the file with the primary key and only use its subkeys:
encryptionKeys.get_PublicKeys(0).Enabled = false;