c# Пишем аналог КриптоАРМ Подписать и зашифровать с архивированием перед шифрованием.

Для создания Zip используем библиотеку:
using Ionic.Zip;

Сам код:
        static bool SigZipEnc(string _path, bool _pin, X509Certificate2 cert,X509Certificate2 recipientCert)
        {
            try
            {
                Sign(_path,cert);
                CreateZipArhive(_path+".sig");
                EncryptMsg(_path+".zip", recipientCert);
            }
            catch
            {
                return false;
            }
            return true;
        }

        static void CreateZipArhive(string _pathin)
        {

            using (ZipFile zip = new ZipFile())
            {
                zip.AddFile(_pathin);
                zip.Save(_pathin+".zip");
            }
        }

        static void EncryptMsg(
            string _path,
            X509Certificate2 recipientCert)
        {
            Byte[] msg = System.IO.File.ReadAllBytes(_path);
            ContentInfo contentInfo = new ContentInfo(msg);
            EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo);
            CmsRecipient recip1 = new CmsRecipient(recipientCert);
            envelopedCms.Encrypt(recip1);
            byte[] encodedMsg = envelopedCms.Encode();
            System.IO.File.WriteAllBytes(_path + ".enc", encodedMsg);
        }

        public static void Sign(string _path, X509Certificate2 cert)
        {
            byte[] msgBytes = System.IO.File.ReadAllBytes(_path);
            ContentInfo contentInfo = new ContentInfo(msgBytes);
            SignedCms signedCms = new SignedCms(contentInfo);
            CmsSigner cmsSigner = new CmsSigner(cert);
            signedCms.ComputeSignature(cmsSigner);
            byte[] encodedMsg = signedCms.Encode();
            System.IO.File.WriteAllBytes(_path + ".sig", encodedMsg);
        }

No comments:

Post a Comment