Preferred cypher for pgp encryption in Java

Table of contents

Preferred Cyphers of a Key

PGP keys hold symmetric cipher preferences and the software that performs the encryption must take them into account which algorithm to choose.

Preferred Cypher of the software

OpenPGP Library for Java can also be customized with a list of preferred symmetric cipher algorithms, and when a public key is provided for encryption the library will try to match its list and the key preferences. If none of them matches, then the first cipher from the library will be used!

As of version 3.x the default preferred symmetric cypher is AES_256.

Getting/Setting the preferred ciphers

A list of the supported ciphers is available in com.didisoft.pgp.CypherAlgorithm.Enum:

CypherAlgorithm.Enum.TRIPLE_DES;
CypherAlgorithm.Enum.CAST5;
CypherAlgorithm.Enum.BLOWFISH;
CypherAlgorithm.Enum.AES_128;
CypherAlgorithm.Enum.AES_192;
CypherAlgorithm.Enum.AES_256;
CypherAlgorithm.Enum.TWOFISH;
CypherAlgorithm.Enum.DES;
CypherAlgorithm.Enum.SAFER;
CypherAlgorithm.Enum.IDEA;
CypherAlgorithm.Enum.CAMELLIA_128
CypherAlgorithm.Enum.CAMELLIA_192
CypherAlgorithm.Enum.CAMELLIA_256

List of preferred ciphers

We can get the current list of ciphers preferred by the library with the methods PGPLib.getCyphers():

PGPLib pgp = new PGPLib();
CypherAlgorithm.Enum[] currentCyphers = pgp.getCyphers();

or we can get the preferred cypher(s) as String:

PGPLib pgp = new PGPLib();
System.out.println(pgp.getCypher());

Changing preferred ciphers

This can be changed through a setter method PGPLib.setCyphers(CypherAlgorithm.Enum[] cyphers)

The example below sets AES_256, AES_192, and AES_128 as preferred algorithms. If an encryption key has only AES_192 and TRIPLE_DES as its preferred algorithms, the library will match AES_192 and use it for the data encryption.

PGPLib pgp = new PGPLib();
pgp.setCyphers(new CypherAlgorithm.Enum[] {CypherAlgorithm.AES_256, CypherAlgorithm.AES_192, CypherAlgorithm.AES_128});

or we canset the cypher(s) as String:

PGPLib pgp = new PGPLib();
pgp.setCypher("AES_256, AES_192, AES_128 ");

Mandatory cipher

We can make the library preferences mandatory and in that case, it won’t take the key preferences into account at all!

If we initialize the library by invoking PGPLib.setOverrideKeyAlgorithmPreferences with true, this will make the library preferences mandatory:

PGPLib pgp = new PGPLib();
pgp.setOverrideKeyAlgorithmPreferences(true)

Now the first item of the preferred cypher, compression, and hash algorithms, from the library settings will be used at each cryptography operation, and the key preferences will be skipped.