/** * Sets the number of random characters that will be appended to the * {@link #createDigest(String) digest}. When it is set to 0, nothing * will be appended to the digest. Otherwise, a random string will be * generated (containing only letters and digits) and appended to the * digest. * <p> * Random digest chars is a <b>unique</b> key per one VM! * This key is initialized only once. * This is useful to automatically expire any cache that browsers may have in * JS and CSS files, so that changes in those files will be downloaded by the * browser. */ public void setRandomDigestChars(final int randomDigestChars) { this.randomDigestChars = randomDigestChars; if (randomDigestChars == 0) { uniqueDigestKey = null; } else { uniqueDigestKey = new RandomString().randomAlphaNumeric(randomDigestChars); } }
/** * Generates new CSRF token and puts it in the session. Returns generated token value. */ @SuppressWarnings({"unchecked"}) public static String prepareCsrfToken(final HttpSession session, final int timeToLive) { Set<Token> tokenSet = (Set<Token>) session.getAttribute(CSRF_TOKEN_SET); if (tokenSet == null) { tokenSet = new HashSet<>(); session.setAttribute(CSRF_TOKEN_SET, tokenSet); } String value; boolean unique; do { value = RandomString.get().randomAlphaNumeric(32); assureSize(tokenSet); unique = tokenSet.add(new Token(value, timeToLive)); } while (!unique); return value; }
@Test void testRandomAppends() { StringBuilder sb = new StringBuilder(10); FastCharBuffer fcb = new FastCharBuffer(10); Random rnd = new Random(); int loop = 100; while (loop-- > 0) { String s = RandomString.get().randomAlphaNumeric(rnd.nextInt(20)); sb.append(s); fcb.append(s); } assertEquals(sb.toString(), fcb.toString()); }
@Test void testBCryptRandom() { for (int rounds = 0; rounds < 1000; rounds++) { String text = RandomString.get().randomAlphaNumeric(10); String hash = BCrypt.hashpw(text, BCrypt.gensalt(4)); assertTrue(BCrypt.checkpw(text, hash)); } }
String boundary = StringUtil.repeat('-', 10) + RandomString.get().randomAlphaNumeric(10);
/** * Sets the number of random characters that will be appended to the * {@link #createDigest(String) digest}. When it is set to 0, nothing * will be appended to the digest. Otherwise, a random string will be * generated (containing only letters and digits) and appended to the * digest. * <p> * Random digest chars is a <b>unique</b> key per one VM! * This key is initialized only once. * This is useful to automatically expire any cache that browsers may have in * JS and CSS files, so that changes in those files will be downloaded by the * browser. */ public void setRandomDigestChars(final int randomDigestChars) { this.randomDigestChars = randomDigestChars; if (randomDigestChars == 0) { uniqueDigestKey = null; } else { uniqueDigestKey = new RandomString().randomAlphaNumeric(randomDigestChars); } }
String boundary = StringUtil.repeat('-', 10) + RandomString.get().randomAlphaNumeric(10);