Exemple #1
0
        /// <summary>
        /// Initialize this class with a key file path.
        /// <para>If the key exixts, permissions are tested, otherwise this path is used as the new key path and file name.</para>
        /// </summary>
        ///
        /// <param name="KeyStream">The stream used to create or extract the key file</param>
        /// <param name="Authority">The local KeyAuthority credentials structure</param>
        public PackageFactory(Stream KeyStream, KeyAuthority Authority)
        {
            // store authority
            m_keyOwner = Authority;
            // file or memory stream
            m_keyStream = KeyStream;

            if (m_keyStream.Length > 0)
            {
                AccessScope = Authenticate();
            }
        }
        private void PackageKeyTest()
        {
            CipherDescription cd1 = new CipherDescription(
                SymmetricEngines.RHX,
                192, IVSizes.V128,
                CipherModes.CTR,
                PaddingModes.None,
                BlockSizes.B128,
                RoundCounts.R22);

            CSPPrng rnd = new CSPPrng();

            byte[] di = new byte[16];
            byte[] oi = new byte[16];
            byte[] pi = new byte[16];
            byte[] pd = new byte[32];
            byte[] ti = new byte[16];
            rnd.GetBytes(di);
            rnd.GetBytes(oi);
            rnd.GetBytes(pi);
            rnd.GetBytes(pd);
            rnd.GetBytes(ti);
            KeyAuthority ka1 = new KeyAuthority(di, oi, pi, pd, KeyPolicies.IdentityRestrict | KeyPolicies.NoExport | KeyPolicies.NoNarrative, 1, ti);

            MemoryStream mk  = new MemoryStream();
            PackageKey   pk1 = new PackageKey(ka1, cd1, 100);

            PackageFactory pf = new PackageFactory(mk, ka1);

            pf.Create(pk1);

            byte[]     bpk = pk1.ToBytes();
            PackageKey pk2 = new PackageKey(bpk);

            if (!pk1.Equals(pk2))
            {
                throw new Exception("KeyFactoryTest: PackageKey serialization has failed!");
            }

            PackageKey pk3 = new PackageKey(mk);

            if (!pk1.Equals(pk3))
            {
                throw new Exception("KeyFactoryTest: PackageKey serialization has failed!");
            }
            if (pk1.GetHashCode() != pk2.GetHashCode() || pk1.GetHashCode() != pk3.GetHashCode())
            {
                throw new Exception("KeyFactoryTest: PackageKey hash code test has failed!");
            }
            pf.Dispose();
        }
        private void KeyAuthorityTest()
        {
            CSPPrng rnd = new CSPPrng();

            byte[] di = new byte[16];
            byte[] oi = new byte[16];
            byte[] pi = new byte[16];
            byte[] pd = new byte[32];
            byte[] ti = new byte[16];
            rnd.GetBytes(di);
            rnd.GetBytes(oi);
            rnd.GetBytes(pi);
            rnd.GetBytes(pd);
            rnd.GetBytes(ti);
            KeyAuthority ka1 = new KeyAuthority(di, oi, pi, pd, KeyPolicies.IdentityRestrict | KeyPolicies.NoExport | KeyPolicies.NoNarrative, 1, ti);

            byte[]       bcd = ka1.ToBytes();
            KeyAuthority ka2 = new KeyAuthority(bcd);

            if (!ka1.Equals(ka2))
            {
                throw new Exception("KeyFactoryTest: KeyAuthority serialization has failed!");
            }
            MemoryStream mcd = ka2.ToStream();
            KeyAuthority ka3 = new KeyAuthority(mcd);

            if (!ka1.Equals(ka3))
            {
                throw new Exception("KeyFactoryTest: KeyAuthority serialization has failed!");
            }

            int x = ka1.GetHashCode();

            if (x != ka2.GetHashCode() || x != ka3.GetHashCode())
            {
                throw new Exception("KeyFactoryTest: KeyAuthority hash code test has failed!");
            }
        }
Exemple #4
0
        /// <summary>
        /// Create a key file using a <see cref="VTDev.Libraries.CEXEngine.Crypto.Processing.Structure.PackageKey"/> structure; containing the cipher description and operating ids and flags.
        /// </summary>
        ///
        /// <param name="Package">The PackageKeyKey containing the cipher description and operating ids and flags</param>
        /// <param name="SeedEngine">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Common.CipherDescription">Random Generator</see> used to create the stage 1 seed material during key generation.</param>
        /// <param name="DigestEngine">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Common.CipherDescription">Digest Engine</see> used in the stage II phase of key generation.</param>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if a key file exists at the path specified, the path is read only, the CipherDescription or KeyAuthority structures are invalid, or
        /// number of SubKeys specified is either less than 1 or more than the maximum allowed (100,000)</exception>
        public void Create(PackageKey Package, SeedGenerators SeedEngine = SeedGenerators.CSPRsg, Digests DigestEngine = Digests.SHA512)
        {
            // if you are getting exceptions.. read the docs!
            if (!CipherDescription.IsValid(Package.Description))
            {
                throw new CryptoProcessingException("PackageFactory:Create", "The key package cipher settings are invalid!", new FormatException());
            }
            if (!KeyAuthority.IsValid(Package.Authority))
            {
                throw new CryptoProcessingException("PackageFactory:Create", "The key package key authority settings are invalid!", new FormatException());
            }
            if (Package.SubKeyCount < 1)
            {
                throw new CryptoProcessingException("PackageFactory:Create", "The key package must contain at least 1 key!", new ArgumentOutOfRangeException());
            }
            if (Package.SubKeyCount > SUBKEY_MAX)
            {
                throw new CryptoProcessingException("PackageFactory:Create", String.Format("The key package can not contain more than {0} keys!", SUBKEY_MAX), new ArgumentOutOfRangeException());
            }

            // get the size of a subkey set
            int subKeySize = Package.Description.KeySize + EXTKEY_SIZE;

            if (Package.Description.IvSize > 0)
            {
                subKeySize += Package.Description.IvSize;
            }

            if (Package.Description.MacKeySize > 0)
            {
                subKeySize += Package.Description.MacKeySize;
            }

            if (subKeySize < 1)
            {
                throw new CryptoProcessingException("PackageFactory:Create", "The key package cipher settings are invalid!", new Exception());
            }

            try
            {
                // store the auth struct and policy
                m_keyOwner = Package.Authority;
                KeyPolicy  = Package.KeyPolicy;
                // get the serialized header
                byte[] header = Package.ToBytes();
                // size key buffer
                byte[] buffer = new byte[subKeySize * Package.SubKeyCount];

                // generate the keying material
                using (KeyGenerator keyGen = new KeyGenerator(SeedEngine, DigestEngine))
                    keyGen.GetBytes(buffer);

                BinaryWriter keyWriter = new BinaryWriter(m_keyStream);
                // pre-set the size to avoid fragmentation
                keyWriter.BaseStream.SetLength(PackageKey.GetHeaderSize(Package) + (subKeySize * Package.SubKeyCount));

                if (IsEncrypted(Package.KeyPolicy))
                {
                    // add policy flags, only part of key not encrypted
                    keyWriter.Write(Package.KeyPolicy);
                    // get salt, return depends on auth flag settings
                    byte[] salt = GetSalt();
                    // create a buffer for encrypted data
                    int    hdrLen = header.Length - PackageKey.GetPolicyOffset();
                    byte[] data   = new byte[buffer.Length + hdrLen];
                    // copy header and key material
                    Buffer.BlockCopy(header, PackageKey.GetPolicyOffset(), data, 0, hdrLen);
                    Buffer.BlockCopy(buffer, 0, data, hdrLen, buffer.Length);
                    // encrypt the key and header
                    TransformBuffer(data, salt);
                    // write to file
                    keyWriter.Write(data);
                    // don't wait for gc
                    Array.Clear(salt, 0, salt.Length);
                    Array.Clear(data, 0, data.Length);
                }
                else
                {
                    // write the keypackage header
                    keyWriter.Write(header, 0, header.Length);
                    // write the keying material
                    keyWriter.Write(buffer, 0, buffer.Length);
                }

                // cleanup
                m_keyStream.Seek(0, SeekOrigin.Begin);
                Array.Clear(header, 0, header.Length);
                Array.Clear(buffer, 0, buffer.Length);
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #5
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.RHX, 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(new FileStream(path, FileMode.Open, FileAccess.ReadWrite), 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, FileAccess.Read))
                    kp2 = PackageKey.AtIndex(stream, i);

                // read the package from id
                using (PackageFactory pf = new PackageFactory(new FileStream(path, FileMode.Open, FileAccess.ReadWrite), authority))
                    pf.Extract(id, out desc2, out kp1);

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