Exemplo n.º 1
0
 private byte[] SetMiniStream(List <CompoundDocumentItem> dirs)
 {
     //Create the miniStream
     using (var ms = RecyclableMemory.GetStream())
     {
         var bwMiniFATStream = new BinaryWriter(ms);
         using (var msforBw = RecyclableMemory.GetStream())
         {
             var bwMiniFAT = new BinaryWriter(msforBw);
             int pos       = 0;
             foreach (var entity in dirs)
             {
                 if (entity.ObjectType != 5 && entity.StreamSize > 0 && entity.StreamSize <= _miniStreamCutoffSize)
                 {
                     bwMiniFATStream.Write(entity.Stream);
                     WriteStreamFullSector(bwMiniFATStream, miniFATSectorSize);
                     int size = _miniSectorSize;
                     entity.StartingSectorLocation = pos;
                     while (entity.StreamSize > size)
                     {
                         bwMiniFAT.Write(++pos);
                         size += _miniSectorSize;
                     }
                     bwMiniFAT.Write(END_OF_CHAIN);
                     pos++;
                 }
             }
             dirs[0].StreamSize = ms.Length;
             dirs[0].Stream     = ms.ToArray();
             WriteStreamFullSector(bwMiniFAT, _sectorSize);
             return(msforBw.ToArray());
         }
     }
 }
Exemplo n.º 2
0
 public CompoundDocumentFile(byte[] file)
 {
     using (var ms = RecyclableMemory.GetStream(file))
     {
         LoadFromMemoryStream(ms);
     }
 }
Exemplo n.º 3
0
        private byte[] CreateTransformInfoPrimary()
        {
            using (var ms = RecyclableMemory.GetStream())
            {
                BinaryWriter bw            = new BinaryWriter(ms);
                string       TransformID   = "{FF9A3F03-56EF-4613-BDD5-5A41C1D07246}";
                string       TransformName = "Microsoft.Container.EncryptionTransform";
                bw.Write(TransformID.Length * 2 + 12);
                bw.Write((int)1);
                bw.Write(TransformID.Length * 2);
                bw.Write(UTF8Encoding.Unicode.GetBytes(TransformID));
                bw.Write(TransformName.Length * 2);
                bw.Write(UTF8Encoding.Unicode.GetBytes(TransformName + "\0"));
                bw.Write((int)1);   //ReaderVersion
                bw.Write((int)1);   //UpdaterVersion
                bw.Write((int)1);   //WriterVersion

                bw.Write((int)0);
                bw.Write((int)0);
                bw.Write((int)0);       //CipherMode
                bw.Write((int)4);       //Reserved

                bw.Flush();
                return(ms.ToArray());
            }
        }
Exemplo n.º 4
0
 internal static void LoadXmlSafe(XmlDocument xmlDoc, string xml, Encoding encoding)
 {
     using (var stream = RecyclableMemory.GetStream(encoding.GetBytes(xml)))
     {
         LoadXmlSafe(xmlDoc, stream);
     }
 }
Exemplo n.º 5
0
        private byte[] EncryptData(byte[] key, byte[] data, bool useDataSize)
        {
#if (Core)
            var aes = Aes.Create();
#else
            RijndaelManaged aes = new RijndaelManaged();
#endif
            aes.KeySize = key.Length * 8;
            aes.Mode    = CipherMode.ECB;
            aes.Padding = PaddingMode.Zeros;

            //Encrypt the data
            var crypt = aes.CreateEncryptor(key, null);
            using (var ms = RecyclableMemory.GetStream())
            {
                var cs = new CryptoStream(ms, crypt, CryptoStreamMode.Write);
                cs.Write(data, 0, data.Length);

                cs.FlushFinalBlock();

                byte[] ret;
                if (useDataSize)
                {
                    ret = new byte[data.Length];
                    ms.Seek(0, SeekOrigin.Begin);
                    ms.Read(ret, 0, data.Length);  //Truncate any padded Zeros
                    return(ret);
                }
                else
                {
                    return(ms.ToArray());
                }
            }
        }
Exemplo n.º 6
0
        private byte[] GetStream(int startingSectorLocation, long streamSize, List <int> FAT, List <byte[]> sectors)
        {
            using (var ms = RecyclableMemory.GetStream())
            {
                var bw = new BinaryWriter(ms);

                var size       = 0;
                var nextSector = startingSectorLocation;
                while (size < streamSize)
                {
                    if (streamSize > size + sectors[nextSector].Length)
                    {
                        bw.Write(sectors[nextSector]);
                        size += sectors[nextSector].Length;
                    }
                    else
                    {
                        var part = new byte[streamSize - size];
                        Array.Copy(sectors[nextSector], part, (int)streamSize - size);
                        bw.Write(part);
                        size += part.Length;
                    }
                    nextSector = FAT[nextSector];
                }
                bw.Flush();
                return(ms.ToArray());
            }
        }
Exemplo n.º 7
0
 internal void Read(byte[] doc)
 {
     using (var ms = RecyclableMemory.GetStream(doc))
     {
         Read(ms);
     }
 }
Exemplo n.º 8
0
        internal static byte[] GetImageAsByteArray(Image image)
        {
            using (var ms = RecyclableMemory.GetStream())
            {
                if (image.RawFormat.Guid == ImageFormat.Gif.Guid)
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (image.RawFormat.Guid == ImageFormat.Bmp.Guid)
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (image.RawFormat.Guid == ImageFormat.Png.Guid)
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (image.RawFormat.Guid == ImageFormat.Tiff.Guid)
                {
                    image.Save(ms, ImageFormat.Tiff);
                }
                else
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }

                return(ms.ToArray());
            }
        }
Exemplo n.º 9
0
        private byte[] DecryptAgileFromKey(EncryptionInfoAgile.EncryptionKeyData encr, byte[] key, byte[] encryptedData, long size, byte[] iv)
        {
            SymmetricAlgorithm decryptKey = GetEncryptionAlgorithm(encr);

            decryptKey.BlockSize = encr.BlockSize << 3;
            decryptKey.KeySize   = encr.KeyBits;
#if (Core)
            decryptKey.Mode = CipherMode.CBC;
#else
            decryptKey.Mode = encr.CipherChaining == eChainingMode.ChainingModeCBC ? CipherMode.CBC : CipherMode.CFB;
#endif
            decryptKey.Padding = PaddingMode.Zeros;

            ICryptoTransform decryptor = decryptKey.CreateDecryptor(
                FixHashSize(key, encr.KeyBits / 8),
                FixHashSize(iv, encr.BlockSize, 0x36));


            using (var dataStream = RecyclableMemory.GetStream(encryptedData))
            {
                CryptoStream cryptoStream = new CryptoStream(dataStream,
                                                             decryptor,
                                                             CryptoStreamMode.Read);

                var decryptedData = new byte[size];

                cryptoStream.Read(decryptedData, 0, (int)size);
                return(decryptedData);
            }
        }
Exemplo n.º 10
0
 /// <summary>
 ///   Uncompress a GZip'ed byte array into a single string.
 /// </summary>
 ///
 /// <seealso cref="GZipStream.CompressString(String)"/>
 /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/>
 ///
 /// <param name="compressed">
 ///   A buffer containing GZIP-compressed data.
 /// </param>
 ///
 /// <returns>The uncompressed string</returns>
 public static String UncompressString(byte[] compressed)
 {
     using (var input = RecyclableMemory.GetStream(compressed))
     {
         Stream decompressor = new GZipStream(input, CompressionMode.Decompress);
         return(ZlibBaseStream.UncompressString(compressed, decompressor));
     }
 }
Exemplo n.º 11
0
        public void WriteBlock(ByteBuffer block)
        {
            using (MemoryStream ms = RecyclableMemory.GetStream(_header_block.BigBlockSize.GetBigBlockSize()))
            {
                _header_block.WriteData(ms);

                block.Write(ms.ToArray());
            }
        }
Exemplo n.º 12
0
        private byte[] GetContentHash(ExcelVbaProject proj)
        {
            //MS-OVBA 2.4.2
            var enc = System.Text.Encoding.GetEncoding(proj.CodePage);

            using (var ms = RecyclableMemory.GetStream())
            {
                BinaryWriter bw = new BinaryWriter(ms);
                bw.Write(enc.GetBytes(proj.Name));
                bw.Write(enc.GetBytes(proj.Constants));
                foreach (var reference in proj.References)
                {
                    if (reference.ReferenceRecordID == 0x0D)
                    {
                        bw.Write((byte)0x7B);
                    }
                    if (reference.ReferenceRecordID == 0x0E)
                    {
                        //var r = (ExcelVbaReferenceProject)reference;
                        //BinaryWriter bwTemp = new BinaryWriter(new MemoryStream());
                        //bwTemp.Write((uint)r.Libid.Length);
                        //bwTemp.Write(enc.GetBytes(r.Libid));
                        //bwTemp.Write((uint)r.LibIdRelative.Length);
                        //bwTemp.Write(enc.GetBytes(r.LibIdRelative));
                        //bwTemp.Write(r.MajorVersion);
                        //bwTemp.Write(r.MinorVersion);
                        foreach (byte b in BitConverter.GetBytes((uint)reference.Libid.Length))  //Length will never be an UInt with 4 bytes that aren't 0 (> 0x00FFFFFF), so no need for the rest of the properties.
                        {
                            if (b != 0)
                            {
                                bw.Write(b);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
                foreach (var module in proj.Modules)
                {
                    var lines = module.Code.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var line in lines)
                    {
                        if (!line.StartsWith("attribute", StringComparison.OrdinalIgnoreCase))
                        {
                            bw.Write(enc.GetBytes(line));
                        }
                    }
                }
                var buffer = ms.ToArray();

                var hp = System.Security.Cryptography.MD5.Create();
                return(hp.ComputeHash(buffer));
            }
        }
Exemplo n.º 13
0
        /// <summary>
        ///   Uncompress a DEFLATE'd byte array into a byte array.
        /// </summary>
        ///
        /// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
        /// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
        /// <seealso cref="GZipStream.UncompressBuffer(byte[])">GZipStream.UncompressBuffer(byte[])</seealso>
        /// <seealso cref="ZlibStream.UncompressBuffer(byte[])">ZlibStream.UncompressBuffer(byte[])</seealso>
        ///
        /// <param name="compressed">
        ///   A buffer containing data that has been compressed with DEFLATE.
        /// </param>
        ///
        /// <returns>The data in uncompressed form</returns>
        public static byte[] UncompressBuffer(byte[] compressed)
        {
            using (var input = RecyclableMemory.GetStream(compressed))
            {
                System.IO.Stream decompressor =
                    new DeflateStream(input, CompressionMode.Decompress);

                return(ZlibBaseStream.UncompressBuffer(compressed, decompressor));
            }
        }
Exemplo n.º 14
0
        public void WriteBlock(byte[] block)
        {
            using (MemoryStream ms = RecyclableMemory.GetStream(_header_block.BigBlockSize.GetBigBlockSize()))
            {
                _header_block.WriteData(ms);

                byte[] temp = ms.ToArray();
                Array.Copy(temp, 0, block, 0, temp.Length);
            }
        }
Exemplo n.º 15
0
 /// <summary>
 ///   Compress a string into a byte array using DEFLATE (RFC 1951).
 /// </summary>
 ///
 /// <remarks>
 ///   Uncompress it with <see cref="DeflateStream.UncompressString(byte[])"/>.
 /// </remarks>
 ///
 /// <seealso cref="DeflateStream.UncompressString(byte[])">DeflateStream.UncompressString(byte[])</seealso>
 /// <seealso cref="DeflateStream.CompressBuffer(byte[])">DeflateStream.CompressBuffer(byte[])</seealso>
 /// <seealso cref="GZipStream.CompressString(string)">GZipStream.CompressString(string)</seealso>
 /// <seealso cref="ZlibStream.CompressString(string)">ZlibStream.CompressString(string)</seealso>
 ///
 /// <param name="s">
 ///   A string to compress. The string will first be encoded
 ///   using UTF8, then compressed.
 /// </param>
 ///
 /// <returns>The string in compressed form</returns>
 public static byte[] CompressString(String s)
 {
     using (var ms = RecyclableMemory.GetStream())
     {
         System.IO.Stream compressor =
             new DeflateStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
         ZlibBaseStream.CompressString(s, compressor);
         return(ms.ToArray());
     }
 }
Exemplo n.º 16
0
 /// <summary>
 /// Converts a range to text in CSV format.
 /// Invariant culture is used by default.
 /// </summary>
 /// <param name="Format">Information how to create the csv text</param>
 /// <returns>A string containing the text</returns>
 public string ToText(ExcelOutputTextFormat Format)
 {
     using (var ms = RecyclableMemory.GetStream())
     {
         SaveToText(ms, Format);
         ms.Position = 0;
         var sr = new StreamReader(ms);
         return(sr.ReadToEnd());
     }
 }
Exemplo n.º 17
0
        private string WritePassword()
        {
            byte[] nullBits = new byte[3];
            byte[] nullKey  = new byte[4];
            byte[] nullHash = new byte[20];
            if (Protection.PasswordKey == null)
            {
                return(Encrypt(new byte[] { 0 }));
            }
            else
            {
                Array.Copy(Protection.PasswordKey, nullKey, 4);
                Array.Copy(Protection.PasswordHash, nullHash, 20);

                //Set Null bits
                for (int i = 0; i < 24; i++)
                {
                    byte bit = (byte)(128 >> (int)((i % 8)));
                    if (i < 4)
                    {
                        if (nullKey[i] == 0)
                        {
                            nullKey[i] = 1;
                        }
                        else
                        {
                            nullBits[0] |= bit;
                        }
                    }
                    else
                    {
                        if (nullHash[i - 4] == 0)
                        {
                            nullHash[i - 4] = 1;
                        }
                        else
                        {
                            int byteIndex = (i - i % 8) / 8;
                            nullBits[byteIndex] |= bit;
                        }
                    }
                }
                //Write the Password Hash Data Structure (2.4.4.1)
                using (var ms = RecyclableMemory.GetStream())
                {
                    BinaryWriter bw = new BinaryWriter(ms);
                    bw.Write((byte)0xFF);
                    bw.Write(nullBits);
                    bw.Write(nullKey);
                    bw.Write(nullHash);
                    bw.Write((byte)0);
                    return(Encrypt(ms.ToArray()));
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Validate the password
        /// </summary>
        /// <param name="key">The encryption key</param>
        /// <param name="encryptionInfo">The encryption info extracted from the ENCRYPTIOINFO stream inside the OLE document</param>
        /// <returns></returns>
        private bool IsPasswordValid(byte[] key, EncryptionInfoBinary encryptionInfo)
        {
#if (Core)
            var decryptKey = Aes.Create();
#else
            RijndaelManaged decryptKey = new RijndaelManaged();
#endif
            decryptKey.KeySize = encryptionInfo.Header.KeySize;
            decryptKey.Mode    = CipherMode.ECB;
            decryptKey.Padding = PaddingMode.None;

            ICryptoTransform decryptor = decryptKey.CreateDecryptor(
                key,
                null);


            //Decrypt the verifier
            MemoryStream dataStream;
            var          decryptedVerifier     = new byte[16];
            var          decryptedVerifierHash = new byte[16];
            using (dataStream = RecyclableMemory.GetStream(encryptionInfo.Verifier.EncryptedVerifier))
            {
                CryptoStream cryptoStream = new CryptoStream(dataStream,
                                                             decryptor,
                                                             CryptoStreamMode.Read);
                cryptoStream.Read(decryptedVerifier, 0, 16);
            }

            using (dataStream = RecyclableMemory.GetStream(encryptionInfo.Verifier.EncryptedVerifierHash))
            {
                var cryptoStream = new CryptoStream(dataStream,
                                                    decryptor,
                                                    CryptoStreamMode.Read);

                //Decrypt the verifier hash
                cryptoStream.Read(decryptedVerifierHash, 0, 16);
            }
            //Get the hash for the decrypted verifier
#if (Core)
            var sha = SHA1.Create();
#else
            var sha = new SHA1Managed();
#endif
            var hash = sha.ComputeHash(decryptedVerifier);

            //Equal?
            for (int i = 0; i < 16; i++)
            {
                if (hash[i] != decryptedVerifierHash[i])
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 19
0
        /// <summary>
        ///   Compress a byte array into a new byte array using ZLIB.
        /// </summary>
        ///
        /// <remarks>
        ///   Uncompress it with <see cref="ZlibStream.UncompressBuffer(byte[])"/>.
        /// </remarks>
        ///
        /// <seealso cref="ZlibStream.CompressString(string)"/>
        /// <seealso cref="ZlibStream.UncompressBuffer(byte[])"/>
        ///
        /// <param name="b">
        /// A buffer to compress.
        /// </param>
        ///
        /// <returns>The data in compressed form</returns>
        public static byte[] CompressBuffer(byte[] b)
        {
            using (var ms = RecyclableMemory.GetStream())
            {
                Stream compressor =
                    new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);

                ZlibBaseStream.CompressBuffer(b, compressor);
                return(ms.ToArray());
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// Converts a range to text in CSV format.
        /// Invariant culture is used by default.
        /// </summary>
        /// <param name="Format">Information how to create the csv text</param>
        /// <returns>A string containing the text</returns>
        public async Task <string> ToTextAsync(ExcelOutputTextFormat Format)
        {
            using (var ms = RecyclableMemory.GetStream())
            {
                await SaveToTextAsync(ms, Format).ConfigureAwait(false);

                ms.Position = 0;
                var sr = new StreamReader(ms);
                return(await sr.ReadToEndAsync().ConfigureAwait(false));
            }
        }
Exemplo n.º 21
0
 internal MemoryStream GetStream(FileMode fileMode, FileAccess fileAccess)
 {
     if (_stream == null || fileMode == FileMode.CreateNew || fileMode == FileMode.Create)
     {
         _stream = RecyclableMemory.GetStream();
     }
     else
     {
         _stream.Seek(0, SeekOrigin.Begin);
     }
     return(_stream);
 }
Exemplo n.º 22
0
        internal byte[] SignProject(ExcelVbaProject proj)
        {
            if (!Certificate.HasPrivateKey)
            {
                //throw (new InvalidOperationException("The certificate doesn't have a private key"));
                Certificate = null;
                return(null);
            }
            var hash = GetContentHash(proj);

            ContentInfo contentInfo;

            using (var ms = RecyclableMemory.GetStream())
            {
                BinaryWriter bw = new BinaryWriter(ms);
                bw.Write((byte)0x30);                                                                //Constructed Type
                bw.Write((byte)0x32);                                                                //Total length
                bw.Write((byte)0x30);                                                                //Constructed Type
                bw.Write((byte)0x0E);                                                                //Length SpcIndirectDataContent
                bw.Write((byte)0x06);                                                                //Oid Tag Indentifier
                bw.Write((byte)0x0A);                                                                //Lenght OId
                bw.Write(new byte[] { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x1D }); //Encoded Oid 1.3.6.1.4.1.311.2.1.29
                bw.Write((byte)0x04);                                                                //Octet String Tag Identifier
                bw.Write((byte)0x00);                                                                //Zero length

                bw.Write((byte)0x30);                                                                //Constructed Type (DigestInfo)
                bw.Write((byte)0x20);                                                                //Length DigestInfo
                bw.Write((byte)0x30);                                                                //Constructed Type (Algorithm)
                bw.Write((byte)0x0C);                                                                //length AlgorithmIdentifier
                bw.Write((byte)0x06);                                                                //Oid Tag Indentifier
                bw.Write((byte)0x08);                                                                //Lenght OId
                bw.Write(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 });             //Encoded Oid for 1.2.840.113549.2.5 (AlgorithmIdentifier MD5)
                bw.Write((byte)0x05);                                                                //Null type identifier
                bw.Write((byte)0x00);                                                                //Null length
                bw.Write((byte)0x04);                                                                //Octet String Identifier
                bw.Write((byte)hash.Length);                                                         //Hash length
                bw.Write(hash);                                                                      //Content hash

                contentInfo = new ContentInfo(ms.ToArray());
            }
            contentInfo.ContentType.Value = "1.3.6.1.4.1.311.2.1.4";
#if (Core)
            Verifier = new EnvelopedCms(contentInfo);
            var r = new CmsRecipient(Certificate);
            Verifier.Encrypt(r);
            return(Verifier.Encode());
#else
            Verifier = new SignedCms(contentInfo);
            var signer = new CmsSigner(Certificate);
            Verifier.ComputeSignature(signer, false);
            return(Verifier.Encode());
#endif
        }
Exemplo n.º 23
0
 /// <summary>
 /// MS-OVBA 2.3.4.1
 /// </summary>
 /// <returns></returns>
 private byte[] CreateVBAProjectStream()
 {
     using (var ms = RecyclableMemory.GetStream())
     {
         BinaryWriter bw = new BinaryWriter(ms);
         bw.Write((ushort)0x61CC); //Reserved1
         bw.Write((ushort)0xFFFF); //Version
         bw.Write((byte)0x0);      //Reserved3
         bw.Write((ushort)0x0);    //Reserved4
         return(ms.ToArray());
     }
 }
Exemplo n.º 24
0
        /// <summary>
        /// Loads a .thmx file, exported from a Spread Sheet Application like Excel
        /// </summary>
        /// <param name="thmxFile">The path to the thmx file</param>
        public void Load(FileInfo thmxFile)
        {
            if (!thmxFile.Exists)
            {
                throw (new FileNotFoundException($"{thmxFile.FullName} does not exist"));
            }

            using (var ms = RecyclableMemory.GetStream(File.ReadAllBytes(thmxFile.FullName)))
            {
                Load(ms);
            }
        }
Exemplo n.º 25
0
 private void GetMiniSectors(byte[] miniFATStream)
 {
     using (var ms = RecyclableMemory.GetStream(miniFATStream))
     {
         var br = new BinaryReader(ms);
         _miniSectors = new List <byte[]>();
         while (ms.Position < ms.Length)
         {
             _miniSectors.Add(br.ReadBytes(_miniSectorSize));
         }
     }
 }
Exemplo n.º 26
0
        public byte[] Serialize()
        {
            int size = DataSize + 4;

            using (MemoryStream baos = RecyclableMemory.GetStream(size))
            {
                Serialize(new LittleEndianOutputStream(baos));
                if (baos.Length != size)
                {
                    throw new Exception("write size mismatch");
                }
                return(baos.ToArray());
            }
        }
Exemplo n.º 27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="Password"></param>
        /// <param name="cancellationToken"></param>
        private async Task LoadAsync(Stream input, Stream output, string Password, CancellationToken cancellationToken)
        {
            ReleaseResources();
            if (input.CanSeek && input.Length == 0) // Template is blank, Construct new
            {
                _stream = output;
                await ConstructNewFileAsync(Password, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                Stream ms;
                _stream = output;
                if (Password != null)
                {
                    using (var encrStream = RecyclableMemory.GetStream())
                    {
                        await CopyStreamAsync(input, encrStream, cancellationToken).ConfigureAwait(false);

                        var eph = new EncryptedPackageHandler();
                        Encryption.Password = Password;
                        ms = eph.DecryptPackage(encrStream, Encryption);
                    }
                }
                else
                {
                    ms = RecyclableMemory.GetStream();
                    await CopyStreamAsync(input, ms, cancellationToken).ConfigureAwait(false);
                }

                try
                {
                    _zipPackage = new Packaging.ZipPackage(ms);
                }
                catch (Exception ex)
                {
                    if (Password == null && await CompoundDocumentFile.IsCompoundDocumentAsync((MemoryStream)_stream, cancellationToken).ConfigureAwait(false))
                    {
                        throw new Exception("Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password", ex);
                    }

                    throw;
                }
                finally
                {
                    ms.Dispose();
                }
            }
            //Clear the workbook so that it gets reinitialized next time
            this._workbook = null;
        }
Exemplo n.º 28
0
 private static byte[] blankWorksheet()
 {
     using (MemoryStream out1 = RecyclableMemory.GetStream())
     {
         try
         {
             new XSSFSheet().Write(out1);
         }
         catch (IOException e)
         {
             throw new RuntimeException(e);
         }
         return(out1.ToArray());
     }
 }
Exemplo n.º 29
0
        private async Task ConstructNewFileAsync(string password, CancellationToken cancellationToken)
        {
            var ms = RecyclableMemory.GetStream();

            if (_stream == null)
            {
                _stream = RecyclableMemory.GetStream();
            }
            File?.Refresh();
            if (File != null && File.Exists)
            {
                if (password != null)
                {
                    var encrHandler = new EncryptedPackageHandler();
                    Encryption.IsEncrypted = true;
                    Encryption.Password    = password;
                    ms.Dispose();
                    ms = encrHandler.DecryptPackage(File, Encryption);
                }
                else
                {
                    await WriteFileToStreamAsync(File.FullName, ms, cancellationToken).ConfigureAwait(false);
                }
                try
                {
                    _zipPackage = new Packaging.ZipPackage(ms);
                }
                catch (Exception ex)
                {
                    if (password == null && await CompoundDocumentFile.IsCompoundDocumentAsync(File, cancellationToken).ConfigureAwait(false))
                    {
                        throw new Exception("Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password", ex);
                    }

                    throw;
                }
                finally
                {
                    ms.Dispose();
                }
            }
            else
            {
                _zipPackage = new Packaging.ZipPackage(ms);
                ms.Dispose();
                CreateBlankWb();
            }
        }
Exemplo n.º 30
0
        private byte[] CreateStrongEncryptionDataSpaceStream()
        {
            MemoryStream ms = RecyclableMemory.GetStream();
            BinaryWriter bw = new BinaryWriter(ms);

            bw.Write((int)8);       //HeaderLength
            bw.Write((int)1);       //EntryCount

            string tr = "StrongEncryptionTransform";

            bw.Write((int)tr.Length * 2);
            bw.Write(UTF8Encoding.Unicode.GetBytes(tr + "\0")); // end \0 is for padding

            bw.Flush();
            return(ms.ToArray());
        }