Ali Bdeir
Ali Bdeir

Reputation: 4375

How can I generate an SHA1 in android like most sites and programs do?

http://www.sha1-online.com/ , http://passwordsgenerator.net/sha1-hash-generator/ , http://www.miraclesalad.com/webtools/sha1.php

-all return 40BD001563085FC35165329EA1FF5C5ECBDBBEEF for the SHA-1 of 123

However, with my code:

public static String SHA1(String clearString)
{
    try
    {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.update(clearString.getBytes("UTF-8"));
        byte[] bytes = messageDigest.digest();
        StringBuilder buffer = new StringBuilder();
        for (byte b : bytes)
        {
            buffer.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
        }
        return buffer.toString();
    }
    catch (Exception ignored)
    {
        ignored.printStackTrace();
        return null;
    }
}

and many other codes I've tried, I get something different. With the above code I get: 9c9598069a40434b500d862e1a13ab9d5a969fc8 for 123.

Seeing that all sites use the same algorithm, it seems like I'm doing something wrong.

Upvotes: 0

Views: 2011

Answers (1)

j2ko
j2ko

Reputation: 2539

Looks like the problem is in the way you converting to String.

public static String byteArrayToString(byte[] bytes) {
    StringBuilder buffer = new StringBuilder();
    for (byte b : bytes) {
        buffer.append(String.format(Locale.getDefault(), "%02x", b));
    }
    return buffer.toString();
}

public static String SHA1(String clearString)
{
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA-1");
        messageDigest.update(clearString.getBytes("UTF-8"));
        return byteArrayToString(messageDigest.digest());
    } catch (Exception ignored) {
        ignored.printStackTrace();
        return null;
    }
}

So SHA1("123") will result in : 40bd001563085fc35165329ea1ff5c5ecbdbbeef

Upvotes: 2

Related Questions