Author: markt Date: Wed Feb 6 18:50:43 2013 New Revision: 1443122 URL: http://svn.apache.org/viewvc?rev=1443122&view=rev Log: Add a utility method for generating secure masks for client data.
Modified: tomcat/trunk/java/org/apache/tomcat/websocket/Util.java Modified: tomcat/trunk/java/org/apache/tomcat/websocket/Util.java URL: http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/tomcat/websocket/Util.java?rev=1443122&r1=1443121&r2=1443122&view=diff ============================================================================== --- tomcat/trunk/java/org/apache/tomcat/websocket/Util.java (original) +++ tomcat/trunk/java/org/apache/tomcat/websocket/Util.java Wed Feb 6 18:50:43 2013 @@ -16,6 +16,11 @@ */ package org.apache.tomcat.websocket; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + import javax.websocket.CloseReason.CloseCode; import javax.websocket.CloseReason.CloseCodes; @@ -25,6 +30,9 @@ import javax.websocket.CloseReason.Close */ class Util { + private static final Queue<SecureRandom> randoms = + new ConcurrentLinkedQueue<>(); + private Util() { // Hide default constructor } @@ -91,4 +99,34 @@ class Util { return CloseCodes.PROTOCOL_ERROR; } } + + + static byte[] generateMask() { + // SecureRandom is not thread-safe so need to make sure only one thread + // uses it at a time. In theory, the pool could grow to the same size + // as the number of request processing threads. In reality it will be + // a lot smaller. + + // Get a SecureRandom from the pool + SecureRandom sr = randoms.poll(); + + // If one isn't available, generate a new one + if (sr == null) { + try { + sr = SecureRandom.getInstance("SHA1PRNG"); + } catch (NoSuchAlgorithmException e) { + // Fall back to platform default + sr = new SecureRandom(); + } + } + + // Generate the mask + byte[] result = new byte[4]; + sr.nextBytes(result); + + // Put the SecureRandom back in the poll + randoms.add(sr); + + return result; + } } --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org