-1

How can i reduce the length of sh1 hash to less than 10 digits? Is it possible ?

I have tried with the following code

 /**
 * 
 * @param id
 * @return
 */
public static final String getGeneratedId(final String id) {

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(id);
        oos.close();
        MessageDigest m = MessageDigest.getInstance("SHA1");
        m.update(baos.toByteArray());
        return new BigInteger(1, m.digest()).toString(16);
    } catch (Exception e) {
        ICAMPPLogger.logException(CLASSNAME, "error in creating uuid" + e);
        ICAMPPUtils.getStackTraceToString(e);
        return BigInteger.ZERO.toString();
    }
}
public static void main(String[] args) {
    String token = getGeneratedId("testing");
    System.out.println(token);
}
ouput is : 1305340859400297508806692338645894167742475232778
But i would like to limit length to less than 10 . is it posssible
PRASANTHMV
  • 299
  • 4
  • 17
  • 2
    `getGeneratedId("foobar").substring(0, 10)` -- very simple. Of course the chances of a collision are increased when you do that. – Erwin Bolwidt Jul 01 '17 at 09:38
  • It's also misleading to talk about `UUID`, when you're not creating a `UUID`. – Kayaman Jul 01 '17 at 09:39
  • 1
    And you should not use Java serialization to transform a String to a byte array. Just use string.getBytes(StandardCharsets.UTF8). – JB Nizet Jul 01 '17 at 09:40
  • @Erwin Bolwidt :Substring.. Very wrong thing. then how can i regain the string i give from that token. That is not i mean – PRASANTHMV Jul 01 '17 at 09:43
  • 2
    @PRASANTHMV by definition, a cryptographic hash does not allow getting back the original text from the hash. That's the whole principle of a hash. Whether you take a substring of it or not doesn't change anything. – JB Nizet Jul 01 '17 at 09:45
  • You can get down to 20 characters with usage of all characters (not only digits) from any 8bit charset/encoding. If you go with 16bit charset, you can get down to 10 characters. You can however not get under 10 numbers without increasing chances of collisions. SHA1 digest will always be 160 bits long. – Matej Kormuth Jul 01 '17 at 09:49
  • Okay . Thank you all for your information – PRASANTHMV Jul 01 '17 at 10:09
  • @PRASANTHMV Message digests are incompressible [* only the good ones, like SHA]. There is no way in which you can get a shorter version of a message digest and get back to the longer one (short of a table lookup) – Erwin Bolwidt Jul 01 '17 at 10:13

1 Answers1

-1

SHA1 produces 160 bits of data, that means 20bytes. If you represent this as HEX you need 40 characters.

Its all in the encoding. You might be able to find some encoding which will will need less than 40 characters.

Check this: What is the most efficient binary to text encoding?

Farooq Khan
  • 570
  • 4
  • 11