Reputation: 1606
I'm thinking about creating several Ciphers and putting them in a collection. Mainly for optimization when creating keys and initializing the Cipher object. They will be used a lot.
Map<Integer, Cipher> encrytors = new HashMap<Integer, Cipher>();
Key key = new SecretKeySpec(secret, KEY_ALGORITHM);
Cipher encrypter = Cipher.getInstance(CIPHER_ALOGORITHM);
encrypter.init(Cipher.ENCRYPT_MODE, key);
encrytors.put(1, encrypter);
Key key2 = new SecretKeySpec(secret2, KEY_ALGORITHM);
Cipher encrypter2 = Cipher.getInstance(CIPHER_ALOGORITHM);
encrypter2.init(Cipher.ENCRYPT_MODE, key2);
encrytors.put(2, encrypter);
Good/bad? How does people handle several different keys and ciphers?
Upvotes: 1
Views: 319
Reputation: 93998
Personally I don't like the idea of putting Cipher
instances in a Map
. Most of the time I do use maps and collections in general for data structures. Cipher instances are not data structures, they are stateful classes that perform a specific action.
Furthermore, I don't like to use objects by different software components. Putting a cipher in a map suggests use by various different classes with different goals. This means you are creating tight coupling between this class and several components. That is not a good thing to do.
That said, there is little wrong with reusing a class like Cipher
within a class. This is especially useful if the relatively expensive key schedule of e.g. AES should not be repeated. It depends on the implementation of the Cipher how this is handled though. In these cases an instance of Cipher
is just a private
, unexposed field of the specific class (say, a FileEncrypter
or such) that is accessed by subsequent calls to a public
method.
Upvotes: 1
Reputation: 5744
Do not optimize prematurely.
While creating a Cipher instance and initializing it is a relatively expensive operation, test it first. Only after performance testing should you optimize performance.
Also note that Cipher is not thread safe (nor is HashMap), in case you wanted to use this cache in multiple threads.
Upvotes: 5