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.Cipherjavax.crypto.KeyAgreementjava.security.KeyFactoryjavax.crypto.KeyGeneratorjava.security.KeyPairGeneratorjavax.crypto.Macjava.security.MessageDigestjavax.crypto.SecretKeyFactoryjava.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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access