This is how it would look like in APEX:
String md5 = EncodingUtil.base64Encode(Crypto.generateDigest('MD5', Blob.valueOf(String.valueOf(DateTime.now().getTime()))));
system.debug(md5);
String var1 = 'The String value 1';
String var2 = 'The String value 2';
String sha1 = EncodingUtil.base64Encode(Crypto.generateDigest('SHA1', Blob.valueOf(EncodingUtil.base64Encode(Crypto.generateDigest('SHA1', Blob.valueOf(var1 + var2))) + var2)));
system.debug(sha1);
String bin2hex = EncodingUtil.base64Encode(Blob.valueOf(var1));
system.debug(bin2hex);
manpreet
Best Answer
2 years ago
I got a PHP script to generate an encoded URL. I need to translate this script into Apex code to generate the same URL. However, the PHP encode functions seem to work differently from Apex.
The relevant PHP encoding functions are:
The code I used to generate them in Apex:
String microTimeTemp = String.valueOf(DateTime.now().getTime()); Blob microtime = EncodingUtil.base64Decode(microTimeTemp); Blob hashMicrotime = Crypto.generateDigest('MD5', microtime); hashTime = EncodingUtil.base64Encode(hashMicrotime);
The closest thing I can think of to PHP microtime() is
DateTime.now().getTime().
However, it seems they return different values:Salesforce explained that the DateTime.now().getTime() returns the value of the time count since 1970.
String var1 = 'The String value 1'; String var2 = 'The String value 2';
String var3 = var1 + var2; Blob blob1 = Blob.valueOf(var3); Blob hash1 = Crypto.generateDigest('SHA1', blob1);
String var4 = EncodingUtil.base64Encode(hash1) + var2; Blob blob2 = Blob.valueOf(var4); Blob hash2 = Crypto.generateDigest('SHA1', blob2); String key = EncodingUtil.base64Encode(hash2);
String hex = EncodingUtil.convertToHex(Blob.valueOf(var1));
When I combined them together, I am pretty sure it was not the same URL generated by the PHP script. Is there a way for Apex to generate the same URL as PHP? Also need to do something encoding as "ASCII"?