Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I zero-ise a secret key in java?

Is the following java code sufficient for clearing the secret key in memory (setting all of its byte value to 0)?

zerorize(SecretKey key)
{
    byte[] rawKey = key.getEncoded();
    Arrays.fill(rawKey, (byte) 0);
}

In other words, does the getEncoded method return a copy or reference to the actual key? If a copy is returned, then how can I clear the secret key as a security measure?

like image 800
Lopper Avatar asked Aug 25 '11 14:08

Lopper


People also ask

What is secret key in Java?

A secret key is the piece of information or parameter that is used to encrypt and decrypt messages. In Java, we have SecretKey an interface that defines it as a secret (symmetric) key. The purpose of this interface is to group (and provide type safety for) all secret key interfaces.

How do you decode a secret key?

You can convert the SecretKey to a byte array ( byte[] ), then Base64 encode that to a String . To convert back to a SecretKey , Base64 decode the String and use it in a SecretKeySpec to rebuild your original SecretKey .

What is SecretKeySpec in Java?

javax.crypto.spec.SecretKeySpec. This class specifies a secret key in a provider-independent fashion. It can be used to construct a SecretKey from a byte array, without having to go through a (provider-based) SecretKeyFactory .


1 Answers

Before trying to clear the key, you should check first if the implementation of the SecretKey interface also implements the javax.security.auth.Destroyable interface. If so, prefer that of course.

like image 78
Joris Wit Avatar answered Sep 21 '22 07:09

Joris Wit