开发者

I'm confuse about KeyGenerator and encoded key in JCE

Now I'm studying about Cryptography and I'm interested in JCE but I am confused about 开发者_开发百科the KeyGenerator class. I know this class can generate a key for a symmetric algorithm but I don't understand why I should use this class? since I can create a secret key by myself using SecretKeyFactory and use it to init the cipher object,right?

like this code below

// Create Key
DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

// Create Cipher
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, secretKey);

and then compare with this code

KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");

generator.init(192);

Key encryptionKey = generator.generateKey();

What is the difference between them? Do they do the same thing?

Also, In what situation should I choose to use the "getEncoded()" method??


KeyGenerator is a convenience class for generating keys. You can tell it what algorithm you will be using in your Cipher and it can generate a key that matches the algorithm without you having to provide anything.

You can of course do this manually, but it takes a few steps as you have have demonstrated in your question (and you don't even cover generating the key data in byte[] key).


There are some JCE providers where keys are treated more securely than byte arrays in that keys are used to encrypt and decrypt data, but are themselves never present in memory in the clear. For example, Smart Card and HSM-backed providers work like that.

When you create a byte array and then construct the key out of it, you're explicitly loading it into memory. When you use a KeyGenerator, the key might be created in a secure storage and not present in memory, eliminating one attack vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜