+ Start a Discussion

EncodingUtil- Encode and Decode



I have a string which I am decoding using base64Decode method, then am encoding it back using base64Encode. Then ultimately I should have the initial string, but in certain case its been truncated.


Any idea, why is this happening or am I missing here something?




Do you have an example of teh text that isn't decoding back correctly?  Is there any special characters that may be causing an issue?




I have no idea. That string in encoded in .net





Here is my code I use in my org - I both encode & decode: 


trigger tr_encodeContactString on Contact (before insert, before update) {
    list<contact> contactTrigger = new list<contact>();
    for (Contact c: trigger.new){
        if (c.BlobDecode__c != NULL || c.BlobDecode__c != ''){
        Blob d = EncodingUtil.base64Decode(c.BlobDecode__c); //decoded string
            c.StringDecode__c = d.tostring(); //field = value of blob converted back to string
        if (c.StringEncode__c != NULL || c.StringEncode__c != ''){
            Blob b = blob.valueof(c.StringEncode__c); //decoded string
            c.BlobEncode__c = EncodingUtil.base64Encode(b);


This enables me to pass the blob back and forwards to our .NET program - I tested it within SF and special characters like * ^ etc don't seem to cause an error... I assume your encode/decode is similar?

I am facing an issue regarding this EncodingUtil.base64Encode function.
I have a field on visualforce page with the save button.
I am encrypting this field using crypto.encrypt and then encoding it using above function to save in database.
I saved the same value 3 4 times nd evry tym a different entry is saved in dB.
Ny idea ??
does this function compute different values at different times??
Roshni RahulRoshni Rahul

string before = 'Testing base 64 encode';
    // create a blob from our parameter value before we send it as part of the url
    Blob beforeblob = Blob.valueOf(before);
    // base64 encode the blob that contains our url param value
    string paramvalue = EncodingUtil.base64Encode(beforeblob);
    // print out the encoded value to the debug log so we can see it before/after base64 encode
    System.debug(before + ' is now encoded as: ' + paramvalue);
    // take the base64 encoded parameter and create base64 decoded Blob from it
    Blob afterblob = EncodingUtil.base64Decode(paramvalue);
    // Convert the blob back to a string and print it in the debug log 
    System.debug(paramvalue + 'is now decoded as: ' + afterblob.toString());
    string againEncode = EncodingUtil.base64Encode(afterblob);
    System.debug(afterblob.toString() +'####' +againEncode);

I have tried this code. But there is no issue like no string is truncated to it.