2017-07-01 28 views
-1

我怎样才能减少sh1哈希到少于10位数的长度?可能吗 ?是否可以将sh1令牌的长度限制为小于10?

我试图用下面的代码

/** 
* 
* @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 
+2

'getGeneratedId( “FOOBAR”)子(0,10)' - 很简单的。当然,碰撞的可能性会增加。 –

+0

当您没有创建“UUID”时,讨论'UUID'也是误导。 – Kayaman

+1

而且您不应该使用Java序列化将字符串转换为字节数组。只需使用string.getBytes(StandardCharsets.UTF8)。 –

回答

-1

SHA1产生数据的160个比特,这意味着20字节。如果您将其表示为HEX,则需要40个字符。

它的全部在编码。您可能能够找到一些编码,这将需要少于40个字符。

检查:。What is the most efficient binary to text encoding?

相关问题