Cipher in multihreaded environments

Hi,

I have short question because I didn't find an anwser yet.

Is the Cipher I use to encrypt/decrypt multithreading-safe?

I ask this because I want to use it in a web-environment.

I have something like this:

publicclass Whatever{

// Are these to fields Thread safe?

privatestatic Cipher cipherEncrypt;

privatestatic Cipher cipherDecrypt;

privatestatic Key key =new SecretKeySpec("donttell".getBytes(),"DES");

privatestaticboolean initialised =false;

privatevoid initialise(){

if (!initialised){

synchronized (ImmonetCookie.class){

if (!initialised){

try{

cipherEncrypt = Cipher.getInstance("DES");// This one is very expensive, so we try to avoid it for every user

cipherEncrypt.init(Cipher.ENCRYPT_MODE, key);

cipherDecrypt = Cipher.getInstance("DES");

cipherDecrypt.init(Cipher.DECRYPT_MODE, key);

}

catch (Exception ex){

logger.error("..", ex);

}

initialised =true;

}

}

}

}

protected String encryptValue(String value){

ByteArrayOutputStream output =new ByteArrayOutputStream();

// Here we use the cipher ..

CipherOutputStream cos =new CipherOutputStream(output, cipherEncrypt);

try{

cos.write(value.getBytes());

cos.close();

}

catch (IOException e){

logger.error("..", e);

returnnull;

}

returnnew String(Base64.encodeBase64(output.toByteArray()));

}

protected String decryptValue(String value){

ByteArrayInputStream input =new ByteArrayInputStream(Base64.decodeBase64(value.getBytes()));

// .. and here we use the cipher

CipherInputStream cis =new CipherInputStream(input, cipherDecrypt);

BufferedReader reader =new BufferedReader(new InputStreamReader(cis));

try{

StringBuffer buffer =new StringBuffer();

String next = reader.readLine();

while (next !=null){

buffer.append(next);

next = reader.readLine();

}

reader.close();

return buffer.toString();

}

catch (IOException e){

logger.error("..", e);

}

returnnull;

}

}

[4704 byte] By [danielgalana] at [2007-11-27 11:54:33]
# 1

Cipher keeps internal state between init, update, and doFinal time. I suspect that what you're doing here will fail horribly.

Sharing the Key is cool - but don't store the ciphers. Ew.

And why do you think that Cipher.getInstance("DES") is so awful? The very first time you do it, ever, I suspect it will be, because I think that's when SecureRandom gets initialized. After that, though, Cipher.getInstance() isn't a big deal.

Grant

(Your key, btw, is pretty dismal. There are ways of generating reasonable keys from human-readable passwords - a straight getBytes() isn't one of them.)

(Also, if you throw an exception trying to initialize your Ciphers, you -still- set "initialised" to true. This will break the rest of your app, because it will keep trying to use null Ciphers.)

(And why are you using DES? Ew. AES is actually secure - nowadays, DES is considered so broken that you might almost just as well use plaintext.)

ggaineya at 2007-7-29 18:56:43 > top of Java-index,Security,Cryptography...