Search code examples
java.netpasswordsbytesha1

Salt generated by java is not same as generated by. Net sha-1


Iam in process to migrate system from .Net to Java users passwords stored in database, the problem that java don't return same Hashed value as what calculated in .Net and the problem is due to bytes in java are signed while in c# unsigned, so any idea how to solve this using java ?

    public static string NetHash(int pSalt, string pPassword, string customerCode)
{
    // Create Byte array of password string
    ASCIIEncoding encoder = new ASCIIEncoding();
    Byte[] secretBytes = encoder.GetBytes(pPassword + customerCode.ToLower());

    // Create a new salt
    Byte[] saltBytes = new Byte[4];
    saltBytes[0] = (byte)(pSalt >> 24);
    saltBytes[1] = (byte)(pSalt >> 16);
    saltBytes[2] = (byte)(pSalt >> 8);
    saltBytes[3] = (byte)(pSalt);

    // append the two arrays
    Byte[] toHash = new Byte[secretBytes.Length + saltBytes.Length];
    Array.Copy(secretBytes, 0, toHash, 0, secretBytes.Length);
    Array.Copy(saltBytes, 0, toHash, secretBytes.Length, saltBytes.Length);

    SHA1 sha1 = SHA1.Create();
    Byte[] computedHash = sha1.ComputeHash(toHash);

    return encoder.GetString(computedHash);
}

same was changed to Java as following

    public String javaHash(int pSalt, String pPassword, String customerCode) {
    String result = "";
    String s = pPassword + customerCode.toLowerCase();
    byte[] secretBytes = s.getBytes();
    byte[] saltBytes = new byte[4];
    saltBytes[0] = (byte) (pSalt >> 24);
    saltBytes[1] = (byte) (pSalt >> 16);
    saltBytes[2] = (byte) (pSalt >> 8);
    saltBytes[3] = (byte) (pSalt);
    byte[] toHash = ArrayUtils.addAll(secretBytes, saltBytes);
    try {
        MessageDigest md = null;
        md = MessageDigest.getInstance("SHA-1");
        byte[] digest1 = md.digest(toHash);
        result = new String(digest1);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.error("Unable to check hash password for user [{}]", customerCode, e);
    }

    return result;
}

Solution

  • incase any one need similar thing, both resulting the same but the problem was in result string encoding , both should use the same encoding "i.e ISO-8859 or UTF8".