Reputation: 32221
I'm trying to make a method for encoding to SHA(128,256,512) with or without salt. The method for no salt is
private static String crypt(String chain, String method) {
MessageDigest md;
try {
md = MessageDigest.getInstance(method);
md.update(chain.getBytes("UTF-8"));
byte[] mb = md.digest();
String out = "";
for (int i = 0; i < mb.length; i++) {
byte temp = mb[i];
String s = Integer.toHexString(new Byte(temp));
while (s.length() < 2) {
s = "0" + s;
}
s = s.substring(s.length() - 2);
out += s;
}
return out;
} catch (Exception e) {
System.out.println("ERROR: " + e.getMessage());
}
return null;
}
where the method can be
private final static String MD5="MD5";
private final static String SHA_128="SHA-1";
private final static String SHA_256="SHA-256";
private final static String SHA_384="SHA-384";
but I'd like also to have a method crypt(String chain,String salt, String method). I tried changing the line to:
byte[] mb=md.digest(salt.getBytes("UTF-8");
But it doesn't return the correct chain (compared with the php call hash_hmac('sha256','pass','salt')). How can I fix that or where can I find a method with optional salt for those algorithms? Thanks
Upvotes: 2
Views: 702
Reputation: 19961
See How are these 2 lines of PHP different? for the difference between HMAC and just concatenating with salt.
Upvotes: 3