+ Start a Discussion
Saikishore Reddy AengareddySaikishore Reddy Aengareddy 

Generate Unique String



I have a requirement where I will have to convert a unique 64 character string to a unique 20 character string. 




Output: asdf123asdf123asdf12


Everytime i give the same input i should get the same output. We have around 5+ Million records to be updated.


Please let me know if you have any ideas around solving the problem.




Create an MD5 hash and only take the first 20 characters of the hash.


String s = 'test string';
Blob hash = Crypto.generateDigest('MD5', Blob.valueOf(s));
String uniqueString = EncodingUtil.convertToHex(hash).substring(0,20);




Hi Scott,


How can you be sure that first 20 characters will make string unique? I think MD5 encrypted string is 32 characters long. According to me, taking only first 20 characters will not work. What do you think?




One little change in the input string will affect every character in the MD5 hash, so I think it's safe to assume that the first 20 characters will be just as unique as the entire 32 character string.
Saikishore Reddy AengareddySaikishore Reddy Aengareddy

Sounds great to me but our bussiness rejected this solution. Bummer!


I have a similar problem.  I need to supply a unique five-character value to a web service.


I'll explain the code below.


	public string getCorrelationId(string seed, integer attempt)
		long epoch = DateTime.NewInstance(2013, 1, 1).getTime();
		if (seed == null) {
			string unique = CarsAPI.AsBase36((DateTime.Now().getTime() - epoch) / 10);
			return String.Format('{0}0', new string[] { unique }); 
		return seed.mid(0, seed.length() - 1) + attempt;

 In-case the value returned by the timestamp is rejected by the server, I'm using the last character as a retry-counter.  The first retry would be 1, the second 2, and so on.


For example, if the first was rejected and the second was required it would generate OF6WF30 then OF6WF31.


Because Apex lacks radix methods anywhere I can find, I'm not keen on translating the string back to a long to add one to it to try again--though that wouldn't be too hard.


Of course, even with base36 my string is still 7-characters long.  Perhaps I should add some puntuation characters.