Factory Methods

The JCA makes extensive use of factory methods to supply instances of its classes. The basic model is to ask a concept class for an instance that implements a particular algorithm. For example, the following code produces a MessageDigest instance that uses the MD5 algorithm:

MessageDigest md5;
md5 = MessageDigest.getInstance("MD5");

Like all the factory methods in the JCA, this one will throw a NoSuchAlgorithmException if the requested algorithm is not available.

The instance that is returned to you from a factory method is some descendant of the class you asked for. But it doesn’t really matter; this is one of the perks of object-oriented programming. The preceding code might return a sun.security.provider.MD5, but you can do everything you need to do by treating it as a MessageDigest.

The following concept classes have getInstance() methods:

  • javax.crypto.Cipher

  • javax.crypto.KeyAgreement

  • java.security.KeyFactory

  • javax.crypto.KeyGenerator

  • java.security.KeyPairGenerator

  • javax.crypto.Mac

  • java.security.MessageDigest

  • javax.crypto.SecretKeyFactory

  • java.security.Signature

These classes also have an overloaded version of getInstance() that accepts an algorithm name and a provider name. I’ll discuss this in detail a little later.

Right now, I suggest you bask in the simplicity of this style of programming. Changing algorithms is just as simple as changing the argument to getInstance(). You don’t have to know a thing about the algorithms themselves ...

Get Java Cryptography now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.