Created
October 19, 2018 15:42
-
-
Save robotdan/2f8a9e5b9349e4d14619258f15e869e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.inversoft.util; | |
import java.security.SecureRandom; | |
import java.util.Base64; | |
/** | |
* @author Daniel DeGroff | |
*/ | |
public class SecurityTools { | |
/** | |
* Return a URL safe random string. | |
* <p> | |
* Several sources indicate that 16 bytes (128 bits) are sufficiently long to provide enough entropy. <p> 32 bytes should be very | |
* sufficient. | |
* <p> | |
* CWE-6: <a href="http://cwe.mitre.org/data/definitions/6.html">J2EE Misconfiguration: Insufficient Sesssion-ID length</a> | |
* <p> | |
* OWASP: <a href="https://www.owasp.org/index.php/Insufficient_Session-ID_Length">Insufficient Session-ID Length</a> | |
* <p> | |
* Stack Exchange: <a href="https://security.stackexchange.com/a/54126">Answer to Length of CSRF Token</a> | |
* <p> | |
* A Base64 encoded character has 62 possible values, and a entropy per character of 5.954 bits. <p> A 16 byte token provides approx 131 | |
* bits of entropy (22 characters * 5.954) <p> A 32 byte token provides approx 256 bits of entropy (43 characters * 5.954) | |
* | |
* @return a random string. | |
*/ | |
public static String secureRandom() { | |
return secureRandom(32); | |
} | |
/** | |
* Return a URL safe random string. | |
* | |
* @param bytes the number of bytes used to generate the random byte array to be encoded. | |
* @return a random string. | |
*/ | |
public static String secureRandom(int bytes) { | |
SecureRandom random = new SecureRandom(); | |
byte[] buf = new byte[bytes]; | |
random.nextBytes(buf); | |
return Base64.getUrlEncoder().withoutPadding().encodeToString(buf); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment