示例#1
0
        /// <remarks>
        /// This method demonstrates using a PackageFactory to extract a key.
        /// StreamMac to verify with a keyed HMAC, that tests the encrypted file before it is conditionally decrypted. 
        /// If accepted the stream is then decrypted using the StreamCipher class.
        /// </remarks>
        private void Decrypt()
        {
            CipherDescription cipherDesc;
            KeyParams keyParam;
            byte[] extKey;

            try
            {
                using (FileStream inStream = new FileStream(_inputPath, FileMode.Open, FileAccess.Read))
                {
                    byte[] keyId = MessageHeader.GetKeyId(inStream);

                    // get the keyheader and key material from the key file
                    using (PackageFactory keyFactory = new PackageFactory(_keyFilePath, _container.Authority))
                    {
                        if (keyFactory.AccessScope == KeyScope.NoAccess)
                        {
                            MessageBox.Show(keyFactory.LastError);
                            return;
                        }
                        keyFactory.Extract(keyId, out cipherDesc, out keyParam, out extKey);
                    }

                    // offset start position is base header + Mac size
                    int hdrOffset = MessageHeader.GetHeaderSize + cipherDesc.MacSize;

                    // decrypt file extension and create a unique path
                    _outputPath = Utilities.GetUniquePath(_outputPath + MessageHeader.GetExtension(inStream, extKey));

                    // if a signing key, test the mac: (MacSize = 0; not signed)
                    if (cipherDesc.MacSize > 0)
                    {
                        // get the hmac for the encrypted file; this could be made selectable
                        // via the KeyHeaderStruct MacDigest and MacSize members.
                        using (StreamMac mstrm = new StreamMac(new SHA512HMAC(keyParam.IKM)))
                        {
                            // get the message header mac
                            byte[] chksum = MessageHeader.GetMessageMac(inStream, cipherDesc.MacSize);

                            // initialize mac stream
                            inStream.Seek(hdrOffset, SeekOrigin.Begin);
                            mstrm.Initialize(inStream);

                            // get the mac; offset by header length + Mac and specify adjusted length
                            byte[] hash = mstrm.ComputeMac(inStream.Length - hdrOffset, hdrOffset);

                            // compare, notify and abort on failure
                            if (!Compare.AreEqual(chksum, hash))
                            {
                                MessageBox.Show("Message hash does not match! The file has been tampered with.");
                                return;
                            }
                        }
                    }

                    // with this constructor, the StreamCipher class creates the cryptographic
                    // engine using the description contained in the CipherDescription structure.
                    // The (cipher and) engine are automatically destroyed in the cipherstream dispose
                    using (StreamCipher cstrm = new StreamCipher(false, cipherDesc, keyParam))
                    {
                        using (FileStream outStream = new FileStream(_outputPath, FileMode.Create, FileAccess.Write))
                        {
                            // start at an input offset equal to the message header size
                            inStream.Seek(hdrOffset, SeekOrigin.Begin);
                            // use a percentage counter
                            cstrm.ProgressPercent += new StreamCipher.ProgressDelegate(OnProgressPercent);
                            // initialize internals
                            cstrm.Initialize(inStream, outStream);
                            // write the decrypted output to file
                            cstrm.Write();
                        }
                    }
                }
                // destroy the key
                keyParam.Dispose();
            }
            catch (Exception ex)
            {
                if (File.Exists(_outputPath))
                    File.Delete(_outputPath);

                string message = ex.Message == null ? "" : ex.Message;
                MessageBox.Show("An error occured, the file could not be encrypted! " + message);
            }
            finally
            {
                Invoke(new MethodInvoker(() => { Reset(); }));
            }
        }
示例#2
0
        /// <summary>
        /// Creates a temporary PackageKey on disk, extracts and compares the copy
        /// <para>Throws an Exception on failure</</para>
        /// </summary>
        public static void PackageFactoryTest()
        {
            string path = GetTempPath();
            KeyGenerator kgen = new KeyGenerator();
            // populate a KeyAuthority structure
            KeyAuthority authority = new KeyAuthority(kgen.GetBytes(16), kgen.GetBytes(16), kgen.GetBytes(16), kgen.GetBytes(32), 0);

            // cipher paramaters
            CipherDescription desc = new CipherDescription(
                SymmetricEngines.RDX, 32,
                IVSizes.V128,
                CipherModes.CTR,
                PaddingModes.X923,
                BlockSizes.B128,
                RoundCounts.R14,
                Digests.Keccak512,
                64,
                Digests.Keccak512);

            // create the package key
            PackageKey pkey = new PackageKey(authority, desc, 10);

            // write a key file
            using (PackageFactory pf = new PackageFactory(path, authority))
                pf.Create(pkey);

            for (int i = 0; i < pkey.SubKeyCount; i++)
            {
                CipherDescription desc2;
                KeyParams kp1;
                KeyParams kp2;
                byte[] ext;
                byte[] id = pkey.SubKeyID[i];

                // get at index
                using (FileStream stream = new FileStream(path, FileMode.Open))
                    kp2 = PackageKey.AtIndex(stream, i);

                // read the package from id
                using (PackageFactory pf = new PackageFactory(path, authority))
                    pf.Extract(id, out desc2, out kp1, out ext);

                // compare key material
                if (!Compare.AreEqual(kp1.Key, kp2.Key))
                    throw new Exception();
                if (!Compare.AreEqual(kp1.IV, kp2.IV))
                    throw new Exception();
                if (!Compare.AreEqual(pkey.ExtensionKey, ext))
                    throw new Exception();
                if (!desc.Equals(desc2))
                    throw new Exception();
            }
            if (File.Exists(path))
                File.Delete(path);
        }