This is really a digest/hash (not encryption). You could get similar
results doing:
String username = "user";
String password = "pass";
public String hash(String username, String password) throws Exception {
MessageDigest digest = MessageDigest.getInstance("SHA1");
byte[] bytes = (username + password).getBytes("UTF-8");
byte[] hash = digest.doFinal(bytes);
// now hex-encode the hash to get a nice string
StringBuffer s = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
s.append(Integer.toHexString((hash[i] >> 4) & 0x0f));
s.append(Integer.toHexString(hash[i] & 0x0f));
}
return s.toString();
}
While salting the password as above (i.e. with a portion/all of the
username) does reduce the possibility of a dictionary attack, it's still
possible to get a collision (i.e., user "cowb" with password "oys" and
user "cow" with password "boys" would have the same hash). You could
diffuse this a bit by using a MAC with the username as the key.
> Hi everybody,
> I would like to implement an authentication scheme that is used in PHP
[quoted text clipped - 42 lines]
>
> Any help is much appreciated, thanks, Jonck
Michael Amling - 12 Mar 2004 02:09 GMT
> This is really a digest/hash (not encryption). You could get similar
> results doing:
[quoted text clipped - 12 lines]
> s.append(Integer.toHexString(hash[i] & 0x0f));
> }
Note that this generates one String object per hex digit. While
that's fine in many environments, if the OP is getting many logins, GC
can be held down by reducing the number of ephemeral objects, e.g.
char[] hexed=new char[hash.length*2];
for (int jj=0, kk=0; jj<hash.length; ++jj) {
hexed[kk++]="0123456789ABCDEF".charAt((hash[jj]>>4) & 0x0F);
hexed[kk++]="0123456789ABCDEF".charAt(hash[jj] & 0x0F);
}
return new String(hexed);
> return s.toString();
> }
[quoted text clipped - 4 lines]
> user "cow" with password "boys" would have the same hash). You could
> diffuse this a bit by using a MAC with the username as the key.
Typically a collision is made impossible interposing a character that
is not legal in the username, such as
byte[] bytes=(username+':'+password).getBytes("UTF-8");
--Mike Amling
Jonck van der Kogel - 12 Mar 2004 11:29 GMT
Thanks very much for your responses guys, this is just what I was looking for!
Thanks again, Jonck
> > This is really a digest/hash (not encryption). You could get similar
> > results doing:
[quoted text clipped - 37 lines]
>
> --Mike Amling