Inside Cipher

So far, you’ve looked at different ways you can use the Cipher class. Now, I’ll show you how to write your own cipher implementation. First, I’ll talk about CipherSpi, the superclass of any cipher implementation. We’ll develop a generic BlockCipher class to handle the mundane details of block formatting. Finally, I’ll present two cipher “wrapper” classes that implement CBC and CFB mode with any existing block cipher.


The methods in javax.crypto.CipherSpi mirror methods in Cipher’s API. As a matter of fact, the SPI is a little simpler than the API because overloaded API methods like update() and doFinal() call fewer overloaded versions of their SPI counterparts.


Suppose you want to implement DES in CBC mode with PKCS#5 padding. There are several ways to do this. You might, for example, write a class that supports this exact combination of mode and padding with DES. Alternately, you could write a class that implements DES in CBC mode and could support several different padding schemes. Finally, you might just write a generic DES class that supports multiple modes and padding schemes.

If you write generic classes and set them up properly in a provider (see Chapter 9), your implementation will be notified what mode and padding scheme it should use. This notification occurs through calls to the following methods:

protected abstract void engineSetMode(String mode) throws NoSuchAlgorithmException

This method informs the cipher implementation that it should operate ...

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.