[SalesForce] Generate random string using Crypto.generateAesKey

I need to generate an unique alphanumeric string of length of 30 characters which will be used very similar to the record id.
Is it okay to use Crypto.generateAesKey() method to generate this 30 characters string? I'll be converting it to Hex and use String.subString(0,30) to achieve this.
Is this enough to generate random string for every insertion? My custom objects can have up to 50 millions of records.

Best Answer

30 hex digits yields 1.329228e+36 possible values; you're looking at having up to 50,000,000 (5.0e+7) records. This results in an extraordinarily large number of possible ID values (on the order of 2.7e29) per record.

The Crypto documentation does not specify exactly how an AES key is generated. If we can assume Salesforce uses a high quality source of entropy to generate true cryptographically random keys, you should be able to assume your ID values are evenly distributed through the keyspace to enough precision that it won't make any difference to your application.

Collisions will not be likely, to say the least. But it's also not impossible. If you make your Id field a unique External Id field, you could build some fairly simple logic into your before insert trigger to run a query against your generated values to ensure they're not duplicated before you populate the field.

Related Topic