29

What's the best way to produce a SALT value in Java as a String that's at least 32 bytes long?

Tom Bell
  • 489
  • 2
  • 6
  • 15
  • 1
    A salt value is just a randomly produced values. What range of characters do you want? Note: characters uses 2-bytes. Do you mean you want a `byte[32]` as a salt? – Peter Lawrey Aug 16 '13 at 07:58
  • 2
    I wanted 32 random bytes encoded as a String as Shamim suggests. – Tom Bell Aug 16 '13 at 15:46

2 Answers2

44
final Random r = new SecureRandom();
byte[] salt = new byte[32];
r.nextBytes(salt);
/** String encodedSalt = Base64.encodeBase64String(salt); */
Shamim Ahmmed
  • 8,265
  • 6
  • 25
  • 36
3

In SpringSecurity you can use org.springframework.security.crypto.keygen.KeyGenerators

http://static.springsource.org/spring-security/site/docs/3.1.x/apidocs/org/springframework/security/crypto/keygen/KeyGenerators.html

http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#spring-security-crypto-keygenerators

Michael
  • 10,063
  • 18
  • 65
  • 104