Search code examples
c#azure-storageopenpgp

How to use OpenPGP to decrypt from one blob to another


I get several PGP encrypted files per day imported to my blob store. I need to be able to decrypt them into another location in the same blob container.

I already know that I have to create a custom batch activity to do this in ADF, I am just unable to figure out how to get the blobs to OpenPgp

This sample code from bitscry.com suggests using streams for an example:

using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open))
using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__decrypted2.txt"))
using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open))
    pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password");

I've tried opening the blobs as streams but its not working.

This is the code that tries to use the blobs as streams:

        Stream sourceStream = keyBlockBlob.OpenRead();
        Stream keyStream = sourceCloudBlockBlob.OpenRead();
        Stream targetStream = targetCloudBlockBlob.OpenWrite();

        pgp.DecryptStream(sourceStream, targetStream, keyStream, "password");

Solution

  • I figured out what I was doing wrong. I was not resetting the stream positions to zero before passing to the DecryptStream. This code works:

            var sourceStream = new MemoryStream();
            var keyStream = new MemoryStream();
            var targetStream = new MemoryStream();
    
            sourceCloudBlockBlob.DownloadToStream(sourceStream);
            sourceStream.Position = 0;
    
            keyBlockBlob.DownloadToStream(keyStream);
            keyStream.Position = 0;
    
    
            pgp.DecryptStream(sourceStream, targetStream, keyStream, "password");
            targetStream.Position = 0;
            targetCloudBlockBlob.UploadFromStream(targetStream);