Domanda

Using user email (that by default it's a unique identifier) and if I need current timestamp, I'd like to generate an alphanumeric string of 11 characters (or less) that represent a unique identifier.

First to create an ad hoc (irreversible) algorithm to do it, I'd like to know if in Java there is something.

È stato utile?

Soluzione

As others pointed out, it is not possible to generate a unique alphanumeric string with length 11 from each email address, as the alphanumeric strings with length 11 are less than all the possible email addresses. So there will always be two different email addresses e1 and e2 such that F(e1) = F(e2) = S for some string S which you generate.

Still, given an email address e1, you can generate a string which is (let's call it) "pseudo-unique" i.e. a string S = F(e1) for which it is practically very hard to find another email address e2 != e1 such that F(e2) = S. And as others pointed out, you can use e.g. MD5 to achieve this.

Look at this class and call it on the byte array obtained from your email address.

http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html

Actually here is an example using MD5.

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Test003 {

    public static void main(String[] args) throws Exception {
        System.out.println(getPseudoUniqueString("test1@test.com"));
        System.out.println(getPseudoUniqueString("test2@test.com"));            
    }

    private static String getPseudoUniqueString(String str) 
        throws NoSuchAlgorithmException 
    {
        MessageDigest md1 = MessageDigest.getInstance("MD5");
        md1.update(str.getBytes());
        byte[] bd1 = md1.digest();

        StringBuffer hexString = new StringBuffer();
        for (int i=0;i<bd1.length;i++) {
            String hex=Integer.toHexString(0xff & bd1[i]);
            if(hex.length()==1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString().substring(0,11);
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top