Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Cipher in multihreaded environments

843811Jul 27 2007 — edited Jul 30 2007
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:
public class Whatever {

	// Are these to fields Thread safe?
	private static Cipher cipherEncrypt;
	private static Cipher cipherDecrypt;

	private static Key key = new SecretKeySpec("donttell".getBytes(), "DES");
	private static boolean initialised = false;

	private void 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);
			return null;
		}
		return new 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);
		}
		return null;
	}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 27 2007
Added on Jul 27 2007
2 comments
818 views