Powered By Blogger

How to Encrypt file in pgp format

To encrypt file in pgp, first we should write logic in c# and use reference in d365 project.

Below is the code for Encryption. 

 public static void EncryptFilecheck(string inputFile, string ouptfile, Stream publicKeyStream, bool armor, bool withIntegrityChec)

        {

            try

{

PgpPublicKey encKey = ReadPublicKey(publicKeyStream);

                using (MemoryStream bOut = new MemoryStream())

                {

                    PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);

                    PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary, new FileInfo(inputFile));

                    comData.Close();


                    PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, withIntegrityChec, new SecureRandom());

                    cPk.AddMethod(encKey);

                    byte[] bytes = bOut.ToArray();

                    using (Stream outputStream = File.Create(ouptfile))

                    {

                        if (armor)

                        {

                            using (ArmoredOutputStream armoredStream = new                        ArmoredOutputStream(outputStream))

                            {

                                using (Stream cOut = cPk.Open(armoredStream, bytes.Length))

                                {

                                    cOut.Write(bytes, 0, bytes.Length);

                                }

                            }

                        }

                        else

                        {

                            using (Stream cOut = cPk.Open(outputStream, bytes.Length))

                            {

                                cOut.Write(bytes, 0, bytes.Length);

                            }

                        }

           }

                }

                PgpPublicKey ReadPublicKey(Stream inputStream)

                {

                    inputStream = PgpUtilities.GetDecoderStream(inputStream);


                    PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);


                    foreach (PgpPublicKeyRing kRing in pgpPub.GetKeyRings())

                    {

                        foreach (PgpPublicKey k in kRing.GetPublicKeys())

                        {

                            if (k.IsEncryptionKey)

                                return k;

                        }

                    }

                    throw new ArgumentException("Can’t find encryption key in key ring.");

                }

            }



            catch (PgpException e)

            {

                throw;

            }


        }


static byte[] ConvertStreamToByteArray(Stream inputStream)

{

using (MemoryStream memoryStream = new MemoryStream())

{

// Copy the data from the input stream to the memory stream

inputStream.CopyTo(memoryStream);


// Return the byte array

return memoryStream.ToArray();

}

}

public static byte[] EncryptFile(string inputFile, Stream inputStreamLoc, Stream publicKeyStream, bool armor, bool withIntegrityChec)

        {

byte[] binarytobytes;

string fillename = inputFile +".txt";

string pgpfilename = inputFile + ".pgp";

string fileToWriteTo = Path.Combine(Path.GetTempPath(), fillename);

// Create a StreamReader to read from the stream

using (StreamReader reader = new StreamReader(inputStreamLoc))

{

// Read the content of the stream into a string

string content = reader.ReadToEnd();


// Write the content to the new text file

File.WriteAllText(fileToWriteTo, content);

}

string Encryptfile= Path.Combine(Path.GetTempPath(), pgpfilename);

EncryptFilecheck(fileToWriteTo, Encryptfile, publicKeyStream, false, true);

string txt = Encryptfile; // Path to the original text file

            using (Stream inputStream = File.OpenRead(txt))

            {

binarytobytes = ConvertStreamToByteArray(inputStream);

            }


if (File.Exists(fileToWriteTo))

{

File.Delete(fileToWriteTo);

}

if (File.Exists(Encryptfile))

{

File.Delete(Encryptfile);

}


return binarytobytes;

        }

X++ code:

First we need to attach a file to encrypt data. here i have attached a file in vendparameter. see below code for file attachment code also.

public void sendFileToSFTP(System.IO.Stream sourceStream)

    {

        str            FileName;

        str            sftpFileName;

        VendParameters vendParameters;

        str            inputFile;

        DocuRef        docuRef;

        DocuType       docuType;

        System.IO.Stream sourceStreamEnc, docuStream;

        System.IO.MemoryStream sourcemStreamEnc;

        System.Byte[] sourceByte;

        vendParameters = VendParameters::find();

        str success;


        try

        {

            FileName    = strReplace(vendParameters.ERBFilenameNew,'%1',integrationStaging.ExecutionId);

            select firstonly docuRef

                where  docuRef.RefRecId == vendParameters.RecId

                && docuRef.RefTableId == vendParameters.TableId

                && docuRef.RefCompanyId == vendParameters.DataAreaId

                && docuRef.IsKyribaEncryptionPublicKey == NoYes::Yes

                join docuType

                where docuType.TypeId == docuRef.TypeId

                && docuType.TypeGroup == DocuTypeGroup::File;


            if(docuRef.isValueAttached())

            {

                docuStream =  DocuAction::newDocuRef(docuRef).getStream(docuRef);

            }


            // str  path     = "/in";

            if (vendParameters.ERBEncrypt)

            {

                sourceByte =  sftpConnection.SFTPConnect::EncryptFile(FileName, sourceStream, docuStream, true, true);

                sourcemStreamEnc = new System.IO.MemoryStream(sourceByte);

                sourceStreamEnc = sourcemStreamEnc;


                 success = sftpConnection.SFTPConnect::uploadSFTPFile(vendParameters.ERBHostName,vendParameters.ERBUserId,

                                vendParameters.ERBPassword, sourceStreamEnc,

                                vendParameters.ERBExportFilePath,vendParameters.ERBPort, FileName);

            }


         

            }

No comments:

Post a Comment

DisableStandredButton

 My requirement is to disable the delete button for journals that were posted:- After Posting the button is enabled fig:- Line level also th...