0

We want to prevent duplicate records of a custom object. The key is built from 20 fields of the record, for example: Let's say a record has Name = "Test", Date="01/01/2018", Number="5" the key would be Test010120185 and we want to prevent a creation of a record with the same values (same key).

The problem is that the key can be very long (more than 255 characters) and we can't use long text field (you can't make it unique).

So we thought about hashing the key with

String hash = EncodingUtil.convertToHex(Crypto.generateDigest('SHA256', Blob.valueOf(key)));

And it works.

BUT can I rely on it ? Is there a possibility that 2 records with different keys would generate the same hash ?

5

BUT can I rely on it ? Is there a possibility that 2 records with different keys would generate the same hash ?

Yes, there is. There must be, because you're compressing more than 256 bits of data down to 256 bits, so there must be some nonunitary number of inputs that map to each hash output.

Given a perfect hash algorithm, the probability would be 1 in 2^256 that any two keys hash to the same value. It's hard to express how unlikely that is, which is why 256-bit hashes are widely used as identifiers in software systems (e.g., Git commit identifiers).

In real-world use, you should be completely fine. If you were building code to run a nuclear power plant hash collisions would be worth worrying about.

  • Sounds good ! So it means I can rely on it, thanks :) – osos9 Dec 16 '18 at 13:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.