Saltar al contenido

Ejemplo de Secuencia de Comandos: Cifrar Archivo con Open PGP

Este complemento de C# cifra un archivo con cifrado Open PGP. "ascFile" es una cadena de ruta completa y nombre de archivo del archivo ASC (debe ser un archivo proporcionado para el cifrado).

Caso de Uso

Esto podría usarse cuando la empresa tiene un archivo que comparte con un tercero a través de MFT/SFTP y requiere que esté encriptado para mayor seguridad durante la transmisión para proteger los datos PII.

Referencias de Complementos

Columna Tipo de datos Descripción
ascFile String ruta completa y nombre de archivo del archivo ASC
InFile String ruta completa y nombre de archivo del archivo que se va a cifrar
OutFile String ruta completa y nombre de archivo deseado para el archivo de salida cifrado (normalmente {{InFile}}||'.pgp'o {{InFile}}||'.gpg'

Abrir Secuencia de Comandos de Cifrado de Archivos PGP

#r "BouncyCastle.Crypto.dll"
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Linq;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Asn1.Utilities;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Utilities.Encoders;
// This is the path to the ASC file
string ascFile = @"c:\PGP.asc";
// Script expects 2 cells in the row action
// "InFile" - full path to file to read (unencrypted file)
// "Outfile" - full path to file to write (encrypted file)
string inFile = Row["InFile"].Value.ToString();
string outFile = Row["OutFile"].Value.ToString();
// The following is from Org.BouncyCastle.Bcpg.OpenPgp.Examples.KeyBasedFileProcessor
EncryptFile(outFile,inFile,ascFile,armor: true,withIntegrityCheck: false);
        string GetAlgorithm(
            PublicKeyAlgorithmTag algId)
        {
            switch (algId)
            {
                case PublicKeyAlgorithmTag.RsaGeneral:
                    return "RsaGeneral";
                case PublicKeyAlgorithmTag.RsaEncrypt:
                    return "RsaEncrypt";
                case PublicKeyAlgorithmTag.RsaSign:
                    return "RsaSign";
                case PublicKeyAlgorithmTag.ElGamalEncrypt:
                    return "ElGamalEncrypt";
                case PublicKeyAlgorithmTag.Dsa:
                    return "DSA";
                case PublicKeyAlgorithmTag.ECDH:
                    return "ECDH";
                case PublicKeyAlgorithmTag.ECDsa:
                    return "ECDSA";
                case PublicKeyAlgorithmTag.ElGamalGeneral:
                    return "ElGamalGeneral";
                case PublicKeyAlgorithmTag.DiffieHellman:
                    return "DiffieHellman";
            }
            return "unknown";
        }
void EncryptFile(
            string  outputFileName,
            string  inputFileName,
            string  encKeyFileName,
            bool    armor,
            bool    withIntegrityCheck)
        {
            PgpPublicKey encKey = ReadPublicKey(encKeyFileName);
            using (Stream output = File.Create(outputFileName))
            {
                EncryptFilePGP(output, inputFileName, encKey, armor, withIntegrityCheck);
            }
        }
void EncryptFilePGP(
            Stream          outputStream,
            string          fileName,
            PgpPublicKey    encKey,
            bool            armor,
            bool            withIntegrityCheck)
        {
            if (armor)
            {
                outputStream = new ArmoredOutputStream(outputStream);
            }
            try
            {
                byte[] bytes = CompressFile(fileName, CompressionAlgorithmTag.Zip);
                PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator(
                    SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom());
                encGen.AddMethod(encKey);
                Stream cOut = encGen.Open(outputStream, bytes.Length);
                cOut.Write(bytes, 0, bytes.Length);
                cOut.Close();
                if (armor)
                {
                    outputStream.Close();
                }
            }
            catch (PgpException e)
            {
                Console.Error.WriteLine(e);
                Exception underlyingException = e.InnerException;
                if (underlyingException != null)
                {
                    Console.Error.WriteLine(underlyingException.Message);
                    Console.Error.WriteLine(underlyingException.StackTrace);
                }
            }
        }

PgpPublicKey ReadPublicKey(string fileName)
        {
            using (Stream keyIn = File.OpenRead(fileName))
            {
                return ReadPublicKey(keyIn);
            }
        }

PgpPublicKey ReadPublicKey(Stream input)
        {
            PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(
                PgpUtilities.GetDecoderStream(input));
            //
            // we just loop through the collection till we find a key suitable for encryption, in the real
            // world you would probably want to be a bit smarter about this.
            //
            foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings())
            {
                foreach (PgpPublicKey key in keyRing.GetPublicKeys())
                {
                    if (key.IsEncryptionKey)
                    {
                        return key;
                    }
                }
            }
            throw new ArgumentException("Can't find encryption key in key ring.");
}
byte[] CompressFile(string fileName, CompressionAlgorithmTag algorithm)
        {
            MemoryStream bOut = new MemoryStream();
            PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(algorithm);
            PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary,
                new FileInfo(fileName));
            comData.Close();
            return bOut.ToArray();
        }