Esempio n. 1
0
        public void When_a_Sensitive_is_constructed_with_a_value_then_the_string_representation_of_the_Sensitive_does_not_contain_that_of_the_input_type(dynamic input)
        {
            var sensitive = new Sensitive <dynamic>(input);

            Assert.DoesNotContain(input.ToString(), sensitive.ToString());
            Assert.Equal("*****", sensitive.ToString());
        }
 private void SensitiveClick(object sender, RoutedEventArgs e)
 {
     if (mainControl.OriginalGrayscaleImage != null)
     {
         mainControl.ProcessedGrayscaleImage = Sensitive.Sensitive_Method(mainControl.OriginalGrayscaleImage);
     }
 }
Esempio n. 3
0
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public int AddList(string str)
        {
            List <Sensitive> list = new List <Sensitive>();

            String[] strs = str.Split('\n');
            foreach (var s in strs)
            {
                string[]  t    = s.Split('=');
                Sensitive temp = new Sensitive();
                try
                {
                    temp.SensitiveText = t[0].Trim();
                    switch (t[1].Trim())
                    {
                    case "{BANNED}":
                        temp.Banned = true;
                        break;

                    case "{MOD}":
                        temp.Mod = true;
                        break;
                    }
                    list.Add(temp);
                }
                catch (Exception)
                {
                }
            }
            return(AddList(list));
        }
Esempio n. 4
0
        /// <summary>
        /// Creates a *software* root key.  The key will be random (not created from a seed).  The key can be used
        /// as the root of a software hierarchy that can be translated into a duplication blob ready for import into
        /// a TPM.  Depending on the type of key, the software root key can be a parent for other root keys that can
        /// comprise a migration group.  The caller should specify necessary key parameters in Public.
        /// </summary>
        /// <returns></returns>
        public static TssObject CreateStorageParent(TpmPublic keyParameters, AuthValue authVal)
        {
            var newKey = new TssObject();
            // Create a new asymmetric key from the supplied parameters
            IPublicIdUnion           publicId;
            ISensitiveCompositeUnion sensitiveData = CreateSensitiveComposite(keyParameters, out publicId);

            // fill in the public data
            newKey.publicPart        = keyParameters.Copy();
            newKey.publicPart.unique = publicId;

            // Create the associated symmetric key -
            SymDefObject symDef = GetSymDef(keyParameters);

            byte[] symmKey;
            if (symDef.Algorithm != TpmAlgId.Null)
            {
                using (var symmCipher = SymmCipher.Create(symDef))
                {
                    symmKey = symmCipher.KeyData;
                }
            }
            else
            {
                symmKey = new byte[0];
            }
            // Fill in the fields for the symmetric private-part of the asymmetric key
            var sens = new Sensitive(authVal.AuthVal, symmKey, sensitiveData);

            newKey.sensitivePart = sens;

            // And return the new key
            return(newKey);
        }
Esempio n. 5
0
        public Cvv(string cvv)
        {
            if (string.IsNullOrWhiteSpace(cvv) || cvv.Any(c => !char.IsDigit(c)))
            {
                throw new ArgumentException("Card CVV must be non-empty. Only the characters 0-9 are allowed.");
            }

            Value = new Sensitive <string>(cvv);
        }
Esempio n. 6
0
        public Pan(string pan)
        {
            if (string.IsNullOrWhiteSpace(pan) || pan.Length != 16 || pan.Any(c => !char.IsDigit(c)))
            {
                throw new ArgumentException("Card PAN must be exactly 16 characters. Only the characters 0-9 are allowed.");
            }

            Value = new Sensitive <string>(pan);
        }
Esempio n. 7
0
        /// <summary>
        /// 添加一条信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Add(Sensitive model)
        {
            int count = 0;

            //判断数据是否存在 再添加
            if (!dal.Exists(model.SensitiveText))
            {
                count = dal.Insert(model);
            }
            return(count);
        }
Esempio n. 8
0
        public void Can_serialize_string_Sensitive()
        {
            var jsonSerializerOptions = new JsonSerializerOptions();

            jsonSerializerOptions.Converters.Add(new SensitiveJsonConverterFactory());
            var input     = "stringvalue" + Guid.NewGuid().ToString();
            var sensitive = new Sensitive <string>(input);

            var json = JsonSerializer.Serialize(sensitive, jsonSerializerOptions);

            Assert.Equal(@$ "" "{input}" "", json);
        }
Esempio n. 9
0
        public void AddSensitiveWithoutSetupName_Should_AddSensitiveDetail()
        {
            var logEvent = new LogEvent <StandardLoglevel>(_ => { }, StandardLoglevel.Warning);

            SensitiveExtensions.Sensitive <StandardLoglevel>(logEvent).Should().BeSameAs(logEvent);

            var sensitive = new Sensitive(true, null);

            sensitive.IsSensitive.Should().BeTrue();
            sensitive.SetupName.Should().BeNull();
            sensitive.ToString().Should().StartWith("Sensitive");
        }
 public override void Write(
     Utf8JsonWriter writer,
     Sensitive <TValue> sensitiveValue,
     JsonSerializerOptions options)
 {
     if (_valueConverter != null)
     {
         _valueConverter.Write(writer, sensitiveValue.Value, options);
     }
     else
     {
         JsonSerializer.Serialize(writer, sensitiveValue.Value, options);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// Creates a *software* key.  The key will be random (not created from
        /// a seed).  The key can be used as the root of a software hierarchy that
        /// can be translated into a duplication blob ready for import into a TPM.
        /// Depending on the type of key, the software root key can be a parent for
        /// other root keys that can comprise a migration group.  The caller should
        /// specify necessary key parameters in Public.
        ///
        /// Parameter keyData is used only with symmetric or HMAC keys. If non-null
        /// on entry, it contains the key bytes supplied by the caller, otherwise the
        /// key will be randomly generated. For asymmetric keys keyData must be null.
        ///
        /// Parameter authVal specifies the authorization value associated with the key.
        /// If it is null, then an random value will be used.
        /// </summary>
        /// <param name="pub"></param>
        /// <param name="authVal"></param>
        /// <param name="keyData"></param>
        /// <returns></returns>
        public static TssObject Create(TpmPublic pub,
                                       AuthValue authVal = null,
                                       byte[] keyData    = null)
        {
            var newKey = new TssObject();

            // Create a new key from the supplied parameters
            IPublicIdUnion publicId;
            var            sensData = CreateSensitiveComposite(pub, ref keyData, out publicId);

            var nameSize = CryptoLib.DigestSize(pub.nameAlg);

            // Create the associated seed value
            byte[] seed = Globs.GetRandomBytes(nameSize);

            // Fill in the fields for the symmetric private-part of the asymmetric key
            var sens = new Sensitive(authVal ?? AuthValue.FromRandom(nameSize),
                                     seed, sensData);

            newKey.Sensitive = sens;
            newKey.Private   = new TpmPrivate(sens.GetTpm2BRepresentation());

            // fill in the public data
            newKey.Public = pub.Copy();

            if (pub.type == TpmAlgId.Keyedhash || pub.type == TpmAlgId.Symcipher)
            {
                byte[] unique = null;
                if (pub.objectAttributes.HasFlag(ObjectAttr.Restricted | ObjectAttr.Decrypt))
                {
                    unique = CryptoLib.Hmac(pub.nameAlg, seed, keyData);
                }
                else
                {
                    unique = CryptoLib.HashData(pub.nameAlg, seed, keyData);
                }
                newKey.Public.unique = pub.type == TpmAlgId.Keyedhash
                                     ? new Tpm2bDigestKeyedhash(unique) as IPublicIdUnion
                                     : new Tpm2bDigestSymcipher(unique);
            }
            else
            {
                newKey.Public.unique = publicId;
            }

            // And return the new key
            return(newKey);
        }
Esempio n. 12
0
        /// <summary>
        /// Create an enveloped (encrypted and integrity protected) private area from a provided sensitive.
        /// </summary>
        /// <param name="iv"></param>
        /// <param name="sens"></param>
        /// <param name="nameHash"></param>
        /// <param name="publicName"></param>
        /// <param name="symWrappingAlg"></param>
        /// <param name="symKey"></param>
        /// <param name="parentNameAlg"></param>
        /// <param name="parentSeed"></param>
        /// <param name="f"></param>
        /// <returns></returns>
        public static byte[] CreatePrivateFromSensitive(
            SymDefObject symWrappingAlg,
            byte[] symKey,
            byte[] iv,
            Sensitive sens,
            TpmAlgId nameHash,
            byte[] publicName,
            TpmAlgId parentNameAlg,
            byte[] parentSeed,
            TssObject.Transformer f = null)
        {
            // ReSharper disable once InconsistentNaming
            byte[] tpm2bIv = Marshaller.ToTpm2B(iv);
            Transform(tpm2bIv, f);

            byte[] sensitive = sens.GetTpmRepresentation();
            Transform(sensitive, f);

            // ReSharper disable once InconsistentNaming
            byte[] tpm2bSensitive = Marshaller.ToTpm2B(sensitive);
            Transform(tpm2bSensitive, f);

            byte[] encSensitive = SymCipher.Encrypt(symWrappingAlg, symKey, iv, tpm2bSensitive);
            Transform(encSensitive, f);
            byte[] decSensitive = SymCipher.Decrypt(symWrappingAlg, symKey, iv, encSensitive);
            Debug.Assert(f != null || Globs.ArraysAreEqual(decSensitive, tpm2bSensitive));

            var hmacKeyBits = CryptoLib.DigestSize(parentNameAlg) * 8;

            byte[] hmacKey = KDF.KDFa(parentNameAlg, parentSeed, "INTEGRITY", new byte[0], new byte[0], hmacKeyBits);
            Transform(hmacKey, f);

            byte[] dataToHmac = Marshaller.GetTpmRepresentation(tpm2bIv,
                                                                encSensitive,
                                                                publicName);
            Transform(dataToHmac, f);

            byte[] outerHmac = CryptoLib.Hmac(parentNameAlg, hmacKey, dataToHmac);
            Transform(outerHmac, f);

            byte[] priv = Marshaller.GetTpmRepresentation(Marshaller.ToTpm2B(outerHmac),
                                                          tpm2bIv,
                                                          encSensitive);
            Transform(priv, f);
            return(priv);
        }
Esempio n. 13
0
        /// <summary>
        /// 添加一条记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Insert(Sensitive model)
        {
            string sql = "insert into [dbo].[T_Sensitive] values(@text,@banned,@mod) ";

            SqlParameter[] pms =
            {
                new SqlParameter("@text",   SqlDbType.NVarChar, 32)
                {
                    Value = model.SensitiveText
                },
                new SqlParameter("@banned", SqlDbType.Bit)
                {
                    Value = model.Banned == true?1:0
                },
                new SqlParameter("@mod",    SqlDbType.Bit)
                {
                    Value = model.Mod == true?1:0
                }
            };
            return(SqlHelper.ExecuteNonQuery(sql, CommandType.Text, pms));
        }
Esempio n. 14
0
        /// <summary>
        /// Creates a *software* root key.  The key will be random (not created from a seed).  The key can be used
        /// as the root of a software hierarchy that can be translated into a duplication blob ready for import into
        /// a TPM.  Depending on the type of key, the software root key can be a parent for other root keys that can
        /// comprise a migration group.  The caller should specify necessary key parameters in Public.
        /// </summary>
        /// <returns></returns>
        public static TssObject CreateStorageParent(TpmPublic keyParameters, AuthValue authVal)
        {
            var newKey = new TssObject();
            // Create a new asymmetric key from the supplied parameters
            IPublicIdUnion           publicId;
            ISensitiveCompositeUnion sensitiveData = CreateSensitiveComposite(keyParameters, out publicId);

            // fill in the public data
            newKey.publicPart        = keyParameters.Copy();
            newKey.publicPart.unique = publicId;

            // Create the associated symmetric key
            byte[] symmKey = Globs.GetRandomBytes(CryptoLib.DigestSize(keyParameters.nameAlg));
            // Fill in the fields for the symmetric private-part of the asymmetric key
            var sens = new Sensitive(authVal.AuthVal, symmKey, sensitiveData);

            newKey.sensitivePart = sens;

            // And return the new key
            return(newKey);
        }
Esempio n. 15
0
        /// <summary>
        ///  row 转 model  得到一个对象实体
        /// </summary>
        public Sensitive DataRowToModel(DataRow row)
        {
            Sensitive model = new Sensitive();

            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = int.Parse(row["Id"].ToString());
                }
                if (row["Sensitive"] != null)
                {
                    model.SensitiveText = row["Sensitive"].ToString();
                }
                if (row["Banned"] != null && row["Banned"].ToString() != "")
                {
                    if ((row["Banned"].ToString() == "1") || (row["Banned"].ToString().ToLower() == "true"))
                    {
                        model.Banned = true;
                    }
                    else
                    {
                        model.Banned = false;
                    }
                }
                if (row["Mod"] != null && row["Mod"].ToString() != "")
                {
                    if ((row["Mod"].ToString() == "1") || (row["Mod"].ToString().ToLower() == "true"))
                    {
                        model.Mod = true;
                    }
                    else
                    {
                        model.Mod = false;
                    }
                }
            }
            return(model);
        }
Esempio n. 16
0
            } // class PrivateKeyBlob


            // Trailing parameters are used to populate TpmPublic generated for the key from the blob.
            public static TpmPrivate CspToTpm(byte[] cspPrivateBlob, out TpmPublic tpmPub,
                                              TpmAlgId nameAlg        = TpmAlgId.Sha1,
                                              ObjectAttr keyAttrs     = ObjectAttr.Decrypt | ObjectAttr.UserWithAuth,
                                              IAsymSchemeUnion scheme = null,
                                              SymDefObject symDef     = null)
            {
                if (scheme == null)
                {
                    scheme = new NullAsymScheme();
                }
                if (symDef == null)
                {
                    symDef = new SymDefObject();
                }

                var m          = new Marshaller(cspPrivateBlob, DataRepresentation.LittleEndian);
                var cspPrivate = m.Get <Csp.PrivateKeyBlob>();
                var keyAlg     = cspPrivate.publicKeyStruc.aiKeyAlg;

                if (keyAlg != Csp.AlgId.CAlgRsaKeyX && keyAlg != Csp.AlgId.CAlgRsaSign)
                {
                    Globs.Throw <NotSupportedException>("CSP blobs for keys of type " + keyAlg.ToString("X") + " are not supported");
                    tpmPub = new TpmPublic();
                    return(new TpmPrivate());
                }

                var rsaPriv = new Tpm2bPrivateKeyRsa(Globs.ReverseByteOrder(cspPrivate.prime1));
                var sens    = new Sensitive(new byte[0], new byte[0], rsaPriv);

                tpmPub = new TpmPublic(nameAlg, keyAttrs, new byte[0],
                                       new RsaParms(symDef,
                                                    scheme,
                                                    (ushort)cspPrivate.rsaPubKey.bitlen,
                                                    cspPrivate.rsaPubKey.pubexp),
                                       new Tpm2bPublicKeyRsa(Globs.ReverseByteOrder(cspPrivate.modulus)));

                return(new TpmPrivate(sens.GetTpm2BRepresentation()));
            }
Esempio n. 17
0
        void LoadExternalFullRsaKeySample(Tpm2 tpm, TestContext testCtx)
        {
            var hashAlg = TpmAlgId.Sha256;
            var inPub   = new TpmPublic(hashAlg,
                                        ObjectAttr.Decrypt | ObjectAttr.UserWithAuth | ObjectAttr.SensitiveDataOrigin,
                                        null,
                                        new RsaParms(new SymDefObject(), new SchemeOaep(hashAlg), 2048, 0),
                                        new Tpm2bPublicKeyRsa());

            // Create a software RSA key
            var swKey = new AsymCryptoSystem(inPub);

            // The crucial point in loading a software key is preparing the TPM-formatted private part of the key
            Sensitive sens = swKey.GetSensitive();

            TpmHandle extKey = tpm.LoadExternal(sens, swKey.GetPublicParms(), TpmRh.Null);

            //
            // Make sure that the key was loaded correctly
            //

            // This particular label is used by the TPM while doing OAEP for its internal protocols
            // (though in n general any label can be used).
            byte[] label   = RawRsa.GetLabel("OaepLabel");
            byte[] origMsg = Substrate.RandomBytes(64);

            // Encrypt using software key (the paublic part is used)
            byte[] encMsg = swKey.EncryptOaep(origMsg, label);

            testCtx.AssertNotEqual("SwEnc", origMsg, encMsg);

            // Decrypt using the TPM (the private part is used)
            byte[] decMsg = tpm.RsaDecrypt(extKey, encMsg, null, label);

            testCtx.AssertEqual("CrossEncDec", origMsg, decMsg);

            tpm.FlushContext(extKey);
        }
        /// <summary>
        /// Create an enveloped (encrypted and integrity protected) private area from a provided sensitive.
        /// </summary>
        /// <param name="iv"></param>
        /// <param name="sens"></param>
        /// <param name="nameHash"></param>
        /// <param name="publicName"></param>
        /// <param name="symWrappingAlg"></param>
        /// <param name="symKey"></param>
        /// <param name="parentNameAlg"></param>
        /// <param name="parentSeed"></param>
        /// <param name="f"></param>
        /// <returns></returns>
        public static byte[] CreatePrivateFromSensitive(
            SymDefObject symWrappingAlg,
            byte[] symKey,
            byte[] iv,
            Sensitive sens,
            TpmAlgId nameHash,
            byte[] publicName,
            TpmAlgId parentNameAlg,
            byte[] parentSeed)
        {
            // ReSharper disable once InconsistentNaming
            byte[] tpm2bIv = Marshaller.ToTpm2B(iv);

            byte[] sensitive = sens.GetTpmRepresentation();

            // ReSharper disable once InconsistentNaming
            byte[] tpm2bSensitive = Marshaller.ToTpm2B(sensitive);

            byte[] encSensitive = SymmCipher.Encrypt(symWrappingAlg, symKey, iv, tpm2bSensitive);
            byte[] decSensitive = SymmCipher.Decrypt(symWrappingAlg, symKey, iv, encSensitive);

            var hmacKeyBits = CryptoLib.DigestSize(parentNameAlg) * 8;

            byte[] hmacKey = KDF.KDFa(parentNameAlg, parentSeed, "INTEGRITY", new byte[0], new byte[0], hmacKeyBits);

            byte[] dataToHmac = Marshaller.GetTpmRepresentation(tpm2bIv,
                                                                encSensitive,
                                                                publicName);

            byte[] outerHmac = CryptoLib.HmacData(parentNameAlg, hmacKey, dataToHmac);

            byte[] priv = Marshaller.GetTpmRepresentation(Marshaller.ToTpm2B(outerHmac),
                                                          tpm2bIv,
                                                          encSensitive);
            return(priv);
        }
Esempio n. 19
0
        public void When_a_Sensitive_is_constructed_with_a_value_then_the_value_can_be_retrieved(dynamic input)
        {
            var sensitive = new Sensitive <dynamic>(input);

            Assert.Equal(input, sensitive.Value);
        }
Esempio n. 20
0
        private bool ReadStorageInfo(string path)
        {
            var   encoding = Encoding.UTF8;
            short vmajor; byte vminor, vbuild; // Version
            short yy, mm, dd, hh, mi, ss;      // Date
            var   datetime = DateTime.MinValue;
            var   appdate  = DateTime.MinValue;
            var   sysver   = new Version();
            var   appver   = new Version();
            var   vzero    = new Version(0, 0, 0);

            if (!File.Exists(path))
            {
                lastError = "File Not Found";
                return(false);
            }

            var decrypted = Sensitive.DecryptICF(path);

            if (decrypted == null)
            {
                lastError = "Invalid ICF file"; return(false);
            }

            var data = new byte[decrypted.Length - 4];

            Array.Copy(decrypted, 4, data, 0, data.Length);
            var dtc1 = Checksum.CRC32(data);

            using (var rd = new BinaryReader(new MemoryStream(decrypted)))
            {
                // Check Main CRC32
                var crc1 = rd.ReadUInt32();
                if (crc1 != dtc1)
                {
                    lastError = "Main Data Error"; return(false);
                }
                // Check Size
                var size = rd.ReadUInt32();
                if (size != decrypted.Length)
                {
                    lastError = "Data Size Error"; return(false);
                }
                // Check padding
                var padding = rd.ReadUInt64();
                if (padding != 0)
                {
                    lastError = "Data Padding Error"; return(false);
                }

                // Entry count
                var count = (int)rd.ReadUInt64();
                var expsz = 0x40 * (count + 1);
                if (expsz != decrypted.Length)
                {
                    lastError = "Data Info Error"; return(false);
                }
                // Read App Id
                var appid = encoding.GetString(rd.ReadBytes(4));
                // Read Platform Id
                var platid = encoding.GetString(rd.ReadBytes(3));
                // Read Platform Generation
                var platgen = rd.ReadByte();

                // Check Sub CRC32
                var  crc2 = rd.ReadUInt32();
                uint dtc2 = 0;
                for (int i = 1; i <= count; i++)
                {
                    data = new byte[0x40];
                    Array.Copy(decrypted, 0x40 * i, data, 0, data.Length);
                    if (data[0] == 2 && data[1] == 1)
                    {
                        dtc2 ^= Checksum.CRC32(data);
                    }
                }
                if (crc2 != dtc2)
                {
                    lastError = "Sub Data Error"; return(false);
                }
                // Check padding
                for (int i = 0; i < 7; i++)
                {
                    padding = rd.ReadUInt32();
                    if (padding != 0)
                    {
                        lastError = "Data Padding Error"; return(false);
                    }
                }

                // Begin Parse Data
                dataList = new List <string>();
                for (int c = 0; c < count; c++)
                {
                    // Begin Entry
                    data = rd.ReadBytes(4);
                    // Part Start
                    var enabled = (data[0] == 2 && data[1] == 1);
                    // Part Type
                    // 00 00 : System, 01 00 : Main , 01 01 : Patch , 02 00 : Option
                    var type = rd.ReadUInt32();
                    // Check padding
                    for (int i = 0; i < 3; i++)
                    {
                        padding = rd.ReadUInt64();
                        if (padding != 0)
                        {
                            lastError = "Data Padding Error"; return(false);
                        }
                    }
                    switch (type)
                    {
                    case 0x0000:     // SYSTEM
                        vbuild = rd.ReadByte();
                        vminor = rd.ReadByte();
                        vmajor = rd.ReadInt16();
                        sysver = new Version(vmajor, vminor, vbuild);
                        yy     = rd.ReadInt16();
                        mm     = rd.ReadByte();
                        dd     = rd.ReadByte();
                        hh     = rd.ReadByte();
                        mi     = rd.ReadByte();
                        ss     = rd.ReadByte();
                        rd.ReadByte();     // ms, not use
                        datetime = new DateTime(yy, mm, dd, hh, mi, ss);
                        // Check SystemVersion Requirement
                        vbuild = rd.ReadByte();
                        vminor = rd.ReadByte();
                        vmajor = rd.ReadInt16();
                        var ver = new Version(vmajor, vminor, vbuild);
                        if (!ver.Equals(sysver))
                        {
                            lastError = "System Version Error"; return(false);
                        }
                        // Check Padding
                        for (int i = 0; i < 2; i++)
                        {
                            padding = rd.ReadUInt64();
                            if (padding != 0)
                            {
                                lastError = "Data Padding Error"; return(false);
                            }
                        }
                        dataList.Add(String.Format("{0}_{1:D4}.{2:D2}.{3:D2}_{4:yyyyMMddHHmmss}_0.pack", platid, sysver.Major, sysver.Minor, sysver.Build, datetime));
                        break;

                    case 0x0001:     // APP
                        vbuild = rd.ReadByte();
                        vminor = rd.ReadByte();
                        vmajor = rd.ReadInt16();
                        appver = new Version(vmajor, vminor, vbuild);
                        yy     = rd.ReadInt16();
                        mm     = rd.ReadByte();
                        dd     = rd.ReadByte();
                        hh     = rd.ReadByte();
                        mi     = rd.ReadByte();
                        ss     = rd.ReadByte();
                        rd.ReadByte();     // ms, not use
                        appdate = new DateTime(yy, mm, dd, hh, mi, ss);
                        // Check SystemVersion Requirement
                        vbuild = rd.ReadByte();
                        vminor = rd.ReadByte();
                        vmajor = rd.ReadInt16();
                        ver    = new Version(vmajor, vminor, vbuild);
                        if (!ver.Equals(sysver))
                        {
                            lastError = "System Version Error"; return(false);
                        }
                        // Check Padding
                        for (int i = 0; i < 2; i++)
                        {
                            padding = rd.ReadUInt64();
                            if (padding != 0)
                            {
                                lastError = "Data Padding Error"; return(false);
                            }
                        }
                        dataList.Add(String.Format("{0}_{1:D}.{2:D2}.{3:D2}_{4:yyyyMMddHHmmss}_0.app", appid, appver.Major, appver.Minor, appver.Build, appdate));
                        break;

                    case 0x0101:     // PATCH
                        var vers = new List <Version>();
                        var dats = new List <DateTime>();
                        for (int i = 0; i < 2; i++)
                        {
                            vbuild = rd.ReadByte();
                            vminor = rd.ReadByte();
                            vmajor = rd.ReadInt16();
                            vers.Add(new Version(vmajor, vminor, vbuild));
                            yy = rd.ReadInt16();
                            mm = rd.ReadByte();
                            dd = rd.ReadByte();
                            hh = rd.ReadByte();
                            mi = rd.ReadByte();
                            ss = rd.ReadByte();
                            rd.ReadByte();     // ms, not use
                            dats.Add(new DateTime(yy, mm, dd, hh, mi, ss));
                            // Check SystemVersion Requirement
                            vbuild = rd.ReadByte();
                            vminor = rd.ReadByte();
                            vmajor = rd.ReadInt16();
                            ver    = new Version(vmajor, vminor, vbuild);
                            if (!ver.Equals(sysver) && !ver.Equals(vzero))
                            {
                                lastError = "System Version Error"; return(false);
                            }
                        }
                        // Check Patch Info
                        if (!vers[1].Equals(appver))
                        {
                            lastError = "Application Version Error"; return(false);
                        }
                        if (!dats[1].Equals(appdate))
                        {
                            lastError = "Application Timestamp Error"; return(false);
                        }
                        dataList.Add(String.Format("{0}_{1:D}.{2:D2}.{3:D2}_{4:yyyyMMddHHmmss}_1_{5:D}.{6:D2}.{7:D2}.app", appid, vers[0].Major, vers[0].Minor, vers[0].Build, dats[0], vers[1].Major, vers[1].Minor, vers[1].Build));
                        break;

                    case 0x0002:     // OPTION
                        var optid = encoding.GetString(rd.ReadBytes(4));
                        yy = rd.ReadInt16();
                        mm = rd.ReadByte();
                        dd = rd.ReadByte();
                        hh = rd.ReadByte();
                        mi = rd.ReadByte();
                        ss = rd.ReadByte();
                        rd.ReadByte();     // ms, not use
                        datetime = new DateTime(yy, mm, dd, hh, mi, ss);
                        // Check SystemVersion Requirement
                        vbuild = rd.ReadByte();
                        vminor = rd.ReadByte();
                        vmajor = rd.ReadInt16();
                        ver    = new Version(vmajor, vminor, vbuild);
                        if (!ver.Equals(sysver) && !ver.Equals(vzero))
                        {
                            lastError = "System Version Error"; return(false);
                        }
                        // Check Padding
                        for (int i = 0; i < 2; i++)
                        {
                            padding = rd.ReadUInt64();
                            if (padding != 0)
                            {
                                lastError = "Data Padding Error"; return(false);
                            }
                        }
                        dataList.Add(String.Format("{0}_{1}_{2:yyyyMMddHHmmss}_0.opt", appid, optid, datetime));
                        break;

                    default:
                        rd.ReadBytes(0x20);
                        break;
                    }
                }
                // dataList.Sort();
                currentAppName = appid;
                return(true);
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Creates a duplication blob for the current key that can be Imported as a child
        /// of newParent. Three forms are possible. GetPlaintextDuplicationBlob() allows
        /// plaintext-import. This function enables duplication with and without an
        /// inner wrapper (depending on whether innerWrapper is null)
        /// </summary>
        /// <param name="newParent"></param>
        /// <param name="innerWrapper"></param>
        /// <param name="encSecret"></param>
        /// <returns></returns>
        public TpmPrivate GetDuplicationBlob(
            TpmPublic pubNewParent,
            SymCipher innerWrapper,
            out byte[] encSecret)
        {
            byte[] encSensitive;
            if (innerWrapper == null)
            {
                // No inner wrapper
                encSensitive = Marshaller.ToTpm2B(Sensitive.GetTpmRepresentation());
                Transform(encSensitive);
            }
            else
            {
                byte[] sens   = Marshaller.ToTpm2B(Sensitive.GetTpmRepresentation());
                byte[] toHash = Globs.Concatenate(sens, GetName());
                Transform(toHash);
                byte[] innerIntegrity = Marshaller.ToTpm2B(CryptoLib.HashData(
                                                               Public.nameAlg, toHash));
                byte[] innerData = Globs.Concatenate(innerIntegrity, sens);
                Transform(innerData);
                encSensitive = innerWrapper.Encrypt(innerData);
                Transform(encSensitive);
            }

            byte[]       seed;
            SymDefObject symDef = GetSymDef(pubNewParent).Copy();

            // TPM duplication procedures always use CFB mode
            symDef.Mode = TpmAlgId.Cfb;

            using (var swNewParent = AsymCryptoSystem.CreateFrom(pubNewParent))
            {
                switch (pubNewParent.type)
                {
                case TpmAlgId.Rsa:
                    // The seed should be the same size as the scheme hash
                    LastSeed =
                        seed = Globs.GetRandomBytes(
                            CryptoLib.DigestSize(swNewParent.OaepHash));
                    encSecret = swNewParent.EncryptOaep(seed, DuplicateEncodingParms);
                    break;

                case TpmAlgId.Ecc:
                    EccPoint pubEphem;
                    seed = swNewParent.EcdhGetKeyExchangeKey(DuplicateEncodingParms,
                                                             pubNewParent.nameAlg,
                                                             out pubEphem);
                    encSecret = Marshaller.GetTpmRepresentation(pubEphem);
                    break;

                default:
                    Globs.Throw <NotImplementedException>(
                        "GetDuplicationBlob: Unsupported algorithm");
                    encSecret = new byte[0];
                    return(new TpmPrivate());
                }
            }
            Transform(seed);
            Transform(encSecret);

            byte[] symKey = KDF.KDFa(pubNewParent.nameAlg, seed, "STORAGE",
                                     Public.GetName(), new byte[0], symDef.KeyBits);
            Transform(symKey);

            byte[] dupSensitive;
            using (SymCipher enc2 = SymCipher.Create(symDef, symKey))
            {
                if (enc2 == null)
                {
                    return(null);
                }

                dupSensitive = enc2.Encrypt(encSensitive);
            }
            Transform(dupSensitive);

            var npNameNumBits = CryptoLib.DigestSize(pubNewParent.nameAlg) * 8;

            byte[] hmacKey = KDF.KDFa(pubNewParent.nameAlg, seed, "INTEGRITY",
                                      new byte[0], new byte[0], npNameNumBits);

            byte[] outerDataToHmac = Globs.Concatenate(dupSensitive, Public.GetName());
            Transform(outerDataToHmac);

            byte[] outerHmac = Marshaller.ToTpm2B(CryptoLib.Hmac(pubNewParent.nameAlg,
                                                                 hmacKey, outerDataToHmac));
            Transform(outerHmac);

            byte[] dupBlob = Globs.Concatenate(outerHmac, dupSensitive);
            Transform(dupBlob);

            return(new TpmPrivate(dupBlob));
        }
Esempio n. 22
0
 /// <summary>
 /// Create a plaintext duplication blob that can be imported into a TPM
 /// </summary>
 /// <returns></returns>
 public TpmPrivate GetPlaintextDuplicationBlob()
 {
     return(new TpmPrivate(Sensitive.GetTpm2BRepresentation()));
 }