We need to RSA encrypt XML data before sending to a third party web service. The encryption has to happen in Salesforce using public key provided by the service provider.

I have looked at code here by Mats Roshauw https://gist.github.com/karmats/4270441be5a34fff7062. The code seems to work but has a limitation where the length of XML data cannot be more than length of modulus part of public key.

Can someone please help with RSA encrypting XML data without such length restrictions?

Thank you for your time.

1 Answer 1


That length restriction is by design (see this Crypto SE answer). You don't directly encrypt the XML data. Instead you generate a hash of the XML (typically a SHA1 hash) using the Apex Crypto.generateDigest() method and then encrypt that hash. The generated hash will be unique to the original XML but it will be relatively very short. This allows you to use the Crypto.encrypt() methods taking the Hash as the input string.

  • abd3721 My requirement is a bit different, perhaps you can help. with RSA encryption in Salesforce using public/private key? I have a requirement to decrypt a file uploaded through the customer portal (The file is encrypted using c#, I'm assuming that is not important but rather the algorithm being used) and perform actions based on the contents. I have tried with the Crypto class example and it seems limited. I dont have much knowledge of encryption so anything to lead me in the right direction will help.
    – user8310
    Mar 20, 2018 at 5:44
  • @user8310 I'd suggest you post this as a new question. I don't have time to dig into this with you at the moment.
    – abd3721
    Mar 22, 2018 at 17:13

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .