views:

354

answers:

3

Is there an easy way in Java to generate password hashes in same form as generated by "openssl passwd -1".

Example:

# openssl passwd -1 test
$1$Gt24/BL6$E4ZsrluohHFxtcdqCH7jo.

I'm looking for a pure java solution that does not call openssl or any other external program.

Thanks Raffael

A: 

Perhaps something like this?

MessageDigest md = null;
md = MessageDigest.getInstance("SHA");
md.update(pPassword.getBytes("UTF-8"));
byte raw[] = md.digest();
String hash = BASE64Encoder.encodeBuffer(raw);

The Java BASE64Encoder source can be found on the net.

Waverick
Or you can use the base64encoder from Commons Coded : http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html
Valentin Rocher
`$` is not a valid Base64 code. I think there is more going on than just Base64 encoding.
Alexander Pogrebnyak
+3  A: 

The openssl docs describe the -1 option as: "Use the MD5 based BSD password algorithm 1."

Jasypt is a java cryptogrqphy library, as is jBCrypt. Jasypt is slightly more complicated, but more configurable.

I don't know that much about crypto, but my guess is that the password generated by openssl breaks down as:
$1$ - specifies that this was generated using the MD5 scheme
Gt24/BL6 - 8 byte salt
$ - delimiter
E4ZsrluohHFxtcdqCH7jo. - hash

so it looks like Jasypt's BasicPasswordEncryptor might be what you want-

Jordan Stewart
I doubt it, unless BasicPasswordEncryptor is intentionally designed to be compatible with the flaky FreeBSD MD5Crypt.
GregS
well it uses MD5, an 8 byte salt, and 1000 iterations (which appears to be what the crypt algorithm uses - http://www.mail-archive.com/[email protected]/msg23405.html), which leaves the implementation itself I guess . . .
Jordan Stewart
A: 

You can find source code for the C language version here. It should be straightforward to convert it to pure Java.

GregS