function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Encrypted and Decrypted pdf attachment in salesforce

Hi Everyone,
My requirement is that i have to encrpted and decrpted the attachment and for this i have write a trigger on attachment and my code is:

trigger encryptAttachment on Attachment (before insert) {
    EncryptionKey__c keySetting = EncryptionKey__c.getOrgDefaults();
    Blob aesKey;
    if(String.isBlank(keySetting.aeskey__c)) {
        keySetting.aeskey__c = EncodingUtil.base64Encode(Crypto.generateAesKey(256));       = 'testencrypted';
        upsert keySetting;
    aesKey = EncodingUtil.base64Decode(keySetting.AesKey__c);
    for(Attachment {
        record.body = Crypto.encryptWithManagedIV('AES256', aesKey, record.body);

i used this code for encryption and for decryption i created a vf page and the controller which is used to browse the encrypted file and used decrpted method show the page in the iframe.

Code of the vf page and controller is :

Vf Page

<apex:page standardController="Attachment" extensions="decryptAttachment">
    <apex:Form >
        <apex:inputFile value="{!attched.body}" filename="{!}"/>
        <apex:commandButton value="Decrypted" action="{!decryptAttachment}"/>
            <iframe src="data:{!attched.ContentType};base64,{!decryptfile}" ></iframe>

Controller :
public with sharing class decryptAttachment {
    public Attachment attched{get;set;}
    public string decryptfile{get;set;}
    public decryptAttachment(ApexPages.StandardController controller) {       
        attched = new Attachment();
    public void decryptAttachment() {       
        EncryptionKey__c keySetting = EncryptionKey__c.getOrgDefaults();
        Blob aesKey = EncodingUtil.base64Decode(keySetting.AesKey__c);         
        decryptfile   =  EncodingUtil.Base64Encode(Crypto.decryptWithManagedIV('AES256', aesKey, attched.Body)); 

Now everything is working fine for text and doc format but it is not supported in the pdf file because when i attach pdf file and click on the view button then it show "Failed to load file" and another problem with pdf file its not supported for the large pdf file.

Thanks in advance for the solution..