Beispiel #1
0
        private byte[] CreateTransformInfoPrimary()
        {
            MemoryStream ms            = RecyclableMemoryStream.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());
        }
        internal static byte[] GetImageAsByteArray(Image image)
        {
            var ms = RecyclableMemoryStream.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());
        }
Beispiel #3
0
        private byte[] EncryptDataAgile(byte[] data, EncryptionInfoAgile encryptionInfo, HashAlgorithm hashProvider)
        {
            var ke = encryptionInfo.KeyEncryptors[0];

#if Core
            var aes = Aes.Create();
#else
            RijndaelManaged aes = new RijndaelManaged();
#endif
            aes.KeySize = ke.KeyBits;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = PaddingMode.Zeros;

            int pos     = 0;
            int segment = 0;

            //Encrypt the data
            var ms = RecyclableMemoryStream.GetStream();
            ms.Write(BitConverter.GetBytes((ulong)data.Length), 0, 8);
            while (pos < data.Length)
            {
                var segmentSize = (int)(data.Length - pos > 4096 ? 4096 : data.Length - pos);

                var ivTmp = new byte[4 + encryptionInfo.KeyData.SaltSize];
                Array.Copy(encryptionInfo.KeyData.SaltValue, 0, ivTmp, 0, encryptionInfo.KeyData.SaltSize);
                Array.Copy(BitConverter.GetBytes(segment), 0, ivTmp, encryptionInfo.KeyData.SaltSize, 4);
                var iv = hashProvider.ComputeHash(ivTmp);

                EncryptAgileFromKey(ke, ke.KeyValue, data, pos, segmentSize, iv, ms);
                pos += segmentSize;
                segment++;
            }
            ms.Flush();
            return(ms.ToArray());
        }
Beispiel #4
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));


            MemoryStream dataStream = RecyclableMemoryStream.GetStream(encryptedData);

            CryptoStream cryptoStream = new CryptoStream(dataStream,
                                                         decryptor,
                                                         CryptoStreamMode.Read);

            var decryptedData = new byte[size];

            cryptoStream.Read(decryptedData, 0, (int)size);
            return(decryptedData);
        }
Beispiel #5
0
        public Stream GetZipStream()
        {
            MemoryStream    ms = RecyclableMemoryStream.GetStream();
            ZipOutputStream os = new ZipOutputStream(ms);

            return(os);
        }
Beispiel #6
0
        private byte[] GetStream(int startingSectorLocation, long streamSize, List <int> FAT, List <byte[]> sectors)
        {
            var ms = RecyclableMemoryStream.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());
        }
Beispiel #7
0
        private byte[] SetMiniStream(List <CompoundDocumentItem> dirs)
        {
            //Create the miniStream
            var ms = RecyclableMemoryStream.GetStream();
            var bwMiniFATStream = new BinaryWriter(ms);
            var bwMiniFAT       = new BinaryWriter(RecyclableMemoryStream.GetStream());
            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(((MemoryStream)bwMiniFAT.BaseStream).ToArray());
        }
Beispiel #8
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);
            var ms    = RecyclableMemoryStream.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());
            }
        }
Beispiel #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="input"></param>
        /// <param name="output"></param>
        /// <param name="Password"></param>
        private void Load(Stream input, Stream output, string Password)
        {
            //Release some resources:
            if (this._package != null)
            {
                this._package.Close();
                this._package = null;
            }
            if (this._stream != null)
            {
                this._stream.Close();
                this._stream.Dispose();
                this._stream = null;
            }
            _isExternalStream = true;
            if (input.Length == 0) // Template is blank, Construct new
            {
                _stream = output;
                ConstructNewFile(Password);
            }
            else
            {
                Stream ms;
                this._stream = output;
                if (Password != null)
                {
                    Stream encrStream = RecyclableMemoryStream.GetStream();
                    CopyStream(input, ref encrStream);
                    EncryptedPackageHandler eph = new EncryptedPackageHandler();
                    Encryption.Password = Password;
                    ms = eph.DecryptPackage((MemoryStream)encrStream, Encryption);
                }
                else
                {
                    ms = RecyclableMemoryStream.GetStream();
                    CopyStream(input, ref ms);
                }

                try
                {
                    //this._package = Package.Open(this._stream, FileMode.Open, FileAccess.ReadWrite);
                    _package = new Packaging.ZipPackage(ms);
                }
                catch (Exception ex)
                {
                    EncryptedPackageHandler eph = new EncryptedPackageHandler();
                    if (Password == null && CompoundDocument.IsCompoundDocument((MemoryStream)_stream))
                    {
                        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);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            //Clear the workbook so that it gets reinitialized next time
            this._workbook = null;
        }
Beispiel #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 = RecyclableMemoryStream.GetStream(compressed))
     {
         Stream decompressor = new GZipStream(input, CompressionMode.Decompress);
         return(ZlibBaseStream.UncompressString(compressed, decompressor));
     }
 }
Beispiel #11
0
        /// <summary>
        /// MS-OVBA 2.3.4.1
        /// </summary>
        /// <returns></returns>
        private byte[] CreateVBAProjectStream()
        {
            BinaryWriter bw = new BinaryWriter(RecyclableMemoryStream.GetStream());

            bw.Write((ushort)0x61CC); //Reserved1
            bw.Write((ushort)0xFFFF); //Version
            bw.Write((byte)0x0);      //Reserved3
            bw.Write((ushort)0x0);    //Reserved4
            return(((MemoryStream)bw.BaseStream).ToArray());
        }
Beispiel #12
0
 /// <summary>
 ///   Compress a string into a byte array using GZip.
 /// </summary>
 ///
 /// <remarks>
 ///   Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>.
 /// </remarks>
 ///
 /// <seealso cref="GZipStream.UncompressString(byte[])"/>
 /// <seealso cref="GZipStream.CompressBuffer(byte[])"/>
 ///
 /// <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 = RecyclableMemoryStream.GetStream())
     {
         System.IO.Stream compressor =
             new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);
         ZlibBaseStream.CompressString(s, compressor);
         return(ms.ToArray());
     }
 }
Beispiel #13
0
        private void GetMiniSectors(byte[] miniFATStream)
        {
            var br = new BinaryReader(RecyclableMemoryStream.GetStream(miniFATStream));

            _miniSectors = new List <byte[]>();
            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                _miniSectors.Add(br.ReadBytes(_miniSectorSize));
            }
        }
Beispiel #14
0
        /// <summary>
        /// Close the internal stream
        /// </summary>
        internal void CloseStream()
        {
            // Issue15252: Clear output buffer
            if (_stream != null)
            {
                _stream.Close();
                _stream.Dispose();
            }

            _stream = RecyclableMemoryStream.GetStream();
        }
        /// <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 = RecyclableMemoryStream.GetStream())
            {
                Stream compressor =
                    new ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression);

                ZlibBaseStream.CompressBuffer(b, compressor);
                return(ms.ToArray());
            }
        }
Beispiel #16
0
 internal MemoryStream GetStream(FileMode fileMode, FileAccess fileAccess)
 {
     if (_stream == null || fileMode == FileMode.CreateNew || fileMode == FileMode.Create)
     {
         _stream = RecyclableMemoryStream.GetStream();
     }
     else
     {
         _stream.Seek(0, SeekOrigin.Begin);
     }
     return(_stream);
 }
Beispiel #17
0
        private byte[] GetContentHash(ExcelVbaProject proj)
        {
            //MS-OVBA 2.4.2
            var          enc = System.Text.Encoding.GetEncoding(proj.CodePage);
            BinaryWriter bw  = new BinaryWriter(RecyclableMemoryStream.GetStream());

            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(RecyclableMemoryStream.GetStream());
                    //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 = (bw.BaseStream as MemoryStream).ToArray();
            var hp     = System.Security.Cryptography.MD5.Create();

            return(hp.ComputeHash(buffer));
        }
Beispiel #18
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)
                BinaryWriter bw = new BinaryWriter(RecyclableMemoryStream.GetStream());
                bw.Write((byte)0xFF);
                bw.Write(nullBits);
                bw.Write(nullKey);
                bw.Write(nullHash);
                bw.Write((byte)0);
                return(Encrypt(((MemoryStream)bw.BaseStream).ToArray()));
            }
        }
Beispiel #19
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   = RecyclableMemoryStream.GetStream(encryptionInfo.Verifier.EncryptedVerifier);
            CryptoStream cryptoStream = new CryptoStream(dataStream,
                                                         decryptor,
                                                         CryptoStreamMode.Read);
            var decryptedVerifier = new byte[16];
            cryptoStream.Read(decryptedVerifier, 0, 16);

            dataStream = RecyclableMemoryStream.GetStream(encryptionInfo.Verifier.EncryptedVerifierHash);

            cryptoStream = new CryptoStream(dataStream,
                                            decryptor,
                                            CryptoStreamMode.Read);

            //Decrypt the verifier hash
            var decryptedVerifierHash = new byte[16];
            cryptoStream.Read(decryptedVerifierHash, 0, (int)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);
        }
Beispiel #20
0
        internal byte[] EncryptedVerifierHash; //(variable): An array of bytes that contains the encrypted form of the hash of the randomly generated Verifier value. The length of the array MUST be the size of the encryption block size multiplied by the number of blocks needed to encrypt the hash of the Verifier. If the encryption algorithm is RC4, the length MUST be 20 bytes. If the encryption algorithm is AES, the length MUST be 32 bytes.
        internal byte[] WriteBinary()
        {
            MemoryStream ms = RecyclableMemoryStream.GetStream();
            BinaryWriter bw = new BinaryWriter(ms);

            bw.Write(SaltSize);
            bw.Write(Salt);
            bw.Write(EncryptedVerifier);
            bw.Write(0x14);                 //Sha1 is 20 bytes  (Encrypted is 32)
            bw.Write(EncryptedVerifierHash);

            bw.Flush();
            return(ms.ToArray());
        }
Beispiel #21
0
        private void ReadDirectory(List <byte[]> sectors, int index, List <CompoundDocumentItem> l)
        {
            var br = new BinaryReader(RecyclableMemoryStream.GetStream(sectors[index]));

            while (br.BaseStream.Position < br.BaseStream.Length)
            {
                var e = new CompoundDocumentItem();
                e.Read(br);
                if (e.ObjectType != 0)
                {
                    l.Add(e);
                }
            }
        }
Beispiel #22
0
        private void ConstructNewFile(string password)
        {
            var ms = RecyclableMemoryStream.GetStream();

            if (_stream == null)
            {
                _stream = RecyclableMemoryStream.GetStream();
            }
            if (File != null)
            {
                File.Refresh();
            }
            if (File != null && File.Exists)
            {
                if (password != null)
                {
                    var encrHandler = new EncryptedPackageHandler();
                    Encryption.IsEncrypted = true;
                    Encryption.Password    = password;
                    ms          = encrHandler.DecryptPackage(File, Encryption);
                    encrHandler = null;
                }
                else
                {
                    WriteFileToStream(File.FullName, ms);
                }
                try
                {
                    //_package = Package.Open(_stream, FileMode.Open, FileAccess.ReadWrite);
                    _package = new Packaging.ZipPackage(ms);
                }
                catch (Exception ex)
                {
                    if (password == null && CompoundDocument.IsCompoundDocument(File))
                    {
                        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);
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            else
            {
                //_package = Package.Open(_stream, FileMode.Create, FileAccess.ReadWrite);
                _package = new Packaging.ZipPackage(ms);
                CreateBlankWb();
            }
        }
Beispiel #23
0
        private byte[] CreateProjectwmStream()
        {
            BinaryWriter bw = new BinaryWriter(RecyclableMemoryStream.GetStream());

            foreach (var module in Modules)
            {
                bw.Write(Encoding.GetEncoding(CodePage).GetBytes(module.Name)); //Name
                bw.Write((byte)0);                                              //Null
                bw.Write(Encoding.Unicode.GetBytes(module.Name));               //Name
                bw.Write((ushort)0);                                            //Null
            }
            bw.Write((ushort)0);                                                //Null
            return(((MemoryStream)bw.BaseStream).ToArray());
        }
Beispiel #24
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);

            BinaryWriter bw = new BinaryWriter(RecyclableMemoryStream.GetStream());

            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 contentInfo = new ContentInfo(((MemoryStream)bw.BaseStream).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
        }
Beispiel #25
0
        private List <int> ReadFAT(List <byte[]> sectors, DocWriteInfo dwi)
        {
            var l = new List <int>();

            foreach (var i in dwi.DIFAT)
            {
                var br = new BinaryReader(RecyclableMemoryStream.GetStream(sectors[i]));
                while (br.BaseStream.Position < _sectorSize)
                {
                    var d = br.ReadInt32();
                    l.Add(d);
                }
            }
            return(l);
        }
Beispiel #26
0
        private byte[] CreateVersionStream()
        {
            MemoryStream ms = RecyclableMemoryStream.GetStream();
            BinaryWriter bw = new BinaryWriter(ms);

            bw.Write((short)0x3C);  //Major
            bw.Write((short)0);     //Minor
            bw.Write(UTF8Encoding.Unicode.GetBytes("Microsoft.Container.DataSpaces"));
            bw.Write((int)1);       //ReaderVersion
            bw.Write((int)1);       //UpdaterVersion
            bw.Write((int)1);       //WriterVersion

            bw.Flush();
            return(ms.ToArray());
        }
Beispiel #27
0
 /// <summary>
 /// Create a new file from a template
 /// </summary>
 /// <param name="template">An existing xlsx file to use as a template</param>
 /// <param name="password">The password to decrypt the package.</param>
 /// <returns></returns>
 private void CreateFromTemplate(FileInfo template, string password)
 {
     if (template != null)
     {
         template.Refresh();
     }
     if (template.Exists)
     {
         if (_stream == null)
         {
             _stream = RecyclableMemoryStream.GetStream();
         }
         var ms = RecyclableMemoryStream.GetStream();
         if (password != null)
         {
             Encryption.IsEncrypted = true;
             Encryption.Password    = password;
             var encrHandler = new EncryptedPackageHandler();
             ms          = encrHandler.DecryptPackage(template, Encryption);
             encrHandler = null;
         }
         else
         {
             WriteFileToStream(template.FullName, ms);
         }
         try
         {
             //_package = Package.Open(_stream, FileMode.Open, FileAccess.ReadWrite);
             _package = new Packaging.ZipPackage(ms);
         }
         catch (Exception ex)
         {
             if (password == null && CompoundDocument.IsCompoundDocument(ms))
             {
                 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);
             }
             else
             {
                 throw;
             }
         }
     }
     else
     {
         throw new Exception("Passed invalid TemplatePath to Excel Template");
     }
     //return newFile;
 }
Beispiel #28
0
        // Set the dataintegrity
        private void SetHMAC(EncryptionInfoAgile ei, HashAlgorithm hashProvider, byte[] salt, byte[] data)
        {
            var iv = GetFinalHash(hashProvider, BlockKey_HmacKey, ei.KeyData.SaltValue);
            var ms = RecyclableMemoryStream.GetStream();

            EncryptAgileFromKey(ei.KeyEncryptors[0], ei.KeyEncryptors[0].KeyValue, salt, 0L, salt.Length, iv, ms);
            ei.DataIntegrity.EncryptedHmacKey = ms.ToArray();

            var h         = GetHmacProvider(ei.KeyEncryptors[0], salt);
            var hmacValue = h.ComputeHash(data);

            ms = RecyclableMemoryStream.GetStream();
            iv = GetFinalHash(hashProvider, BlockKey_HmacValue, ei.KeyData.SaltValue);
            EncryptAgileFromKey(ei.KeyEncryptors[0], ei.KeyEncryptors[0].KeyValue, hmacValue, 0L, hmacValue.Length, iv, ms);
            ei.DataIntegrity.EncryptedHmacValue = ms.ToArray();
        }
Beispiel #29
0
        private byte[] CreateStrongEncryptionDataSpaceStream()
        {
            MemoryStream ms = RecyclableMemoryStream.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());
        }
        internal byte[] WriteBinary()
        {
            MemoryStream ms = RecyclableMemoryStream.GetStream();
            BinaryWriter bw = new BinaryWriter(ms);

            bw.Write(MajorVersion);
            bw.Write(MinorVersion);
            bw.Write((int)Flags);
            byte[] header = Header.WriteBinary();
            bw.Write((uint)header.Length);
            bw.Write(header);
            bw.Write(Verifier.WriteBinary());

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