Build up a cipher instance manually without getInstance

172 Views Asked by At

I don't seem to figure out a way to "manually" build up instance of cipher. Every tutorial and resource has same way trough Cipher.getInstance

Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");

What I'm trying to do is to build up Cipher instance manually by giving it block cipher of my decision, its mode but also padding scheme from my own class hopefully having right methods through interface.

So as a sample trying to do something like:

Cipher cipher = Cipher(new AESEngine());
...give cipher instance custom class which provides padding scheme
...

Upper one was imaginary to explain what I'm after.

Doing this for learning purposes.

1

There are 1 best solutions below

0
Maarten Bodewes On

You are for that looking at the wrong class. To do this you need to implement CipherSpi - a Service Provider Interface - and then implement a Provider with the right Service. Your SPI should use the software or hardware implementation of the block cipher, in turn.

Cipher has explicitly designed to require getInstance, otherwise you could get around the provider signing and the limited cryptography that is - or used to be - part of the JDK. However, on Android and OpenJDK you don't need to sign the provider anymore.

Other than that you are left with very ugly hacks with reflection etc. to get around the block that Cipher poses. You'll have to look those up yourself; as indicated with the latest runtimes there is really no need anymore.


If you think that is too complex and you can do with a software only implementation that is not compatible with Cipher you can have a look at the Bouncy Castle "lightweight API".

Bouncy Castle also implements a provider in the same way, but due to the size of the code it may be too complex as an example. You could of course decide to integrate your code into BC for your own purposes as well.