0

I am trying to encrypt and decrypt file using apex but getting below error while decryption of file. Goal is to encrypt the file in salesforce and send it to third party. Third party should be able to decrypt it.

System.SecurityException: last block incomplete in decryption

First I am encrypting file and storing the encrypted file.(encrypted file will be sent to third party) -- Encryption code

  List<ContentVersion> cv = new List<ContentVersion>();
  cv = [SELECT Title, VersionData FROM ContentVersion WHERE Id='CVIDPLACEHOLDER'];
  String originalStr;
  Blob source ;
  for (ContentVersion cv1: cv) {
      source = cv1.VersionData;
    }
    Blob encrypted = Crypto.encryptWithManagedIV('AES256', key, source);
    //String encrypted64 = EncodingUtil.base64Encode(encrypted);
    ContentVersion cv2 = new ContentVersion();
    cv2.Title = 'encryptedDoc1';
    cv2.PathOnClient = 'encryptedDoc1.txt.pgp';
    cv2.VersionData = encrypted ;
     //Blob.valueOf(encrypted64);
    cv2.IsMajorVersion = true;
    Insert cv2;

Now fetching the encrypted file stored from above code and decrypting it using its blob.

    List<ContentVersion> cv = new List<ContentVersion>();
    cv = [SELECT Title, VersionData FROM ContentVersion WHERE Id=:cvId];
    String originalStr;
    blob fileBlob ;
    for (ContentVersion cv1: cv) {
        fileBlob = cv1.VersionData;
    }
    Blob decrypted = Crypto.decryptWithManagedIv('AES256', key, fileBlob);
    String decryptedText = decrypted.toString();
    ContentVersion cv2 = new ContentVersion();
    cv2.Title = 'decrypted1';
    cv2.PathOnClient = 'decrypted1.txt';
    cv2.VersionData = Blob.valueOf(decryptedText);
    cv2.IsMajorVersion = true;
    Insert cv2;
    system.debug('CV2 '+cv2);

Not sure what I am doing wrong, can someone please help. Any kind of help is much appreciated.

Also, is it the correct way? For example, we can encrypt a file with linux commands, do they also encrypt base64/blob of file? if not, how a file is encrypted?

1 Answer 1

0

You performed base64encode on the encrypted file, so you'd have to perform a base64decode before decrypting the file. Either remove the base64encode from the encryption process, or add base64decode before calling the decryption.

1
  • I tried removing base64encode and encrypted directly with file blob and decrypting same blob. still getting same error. Commented Nov 28, 2022 at 7:43

You must log in to answer this question.

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