/// <summary> /// Reads and checks the anti-tamper hash code from given stream. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="s">The stream.</param> /// <param name="v">The value.</param> public static void ReadAntiTamperHashCode <T>(Stream s, T v) where T : class, IObjectWithHashCode64 { LongToBytesConverter c; try { c = new LongToBytesConverter { Byte1 = (byte)s.ReadByte(), Byte2 = (byte)s.ReadByte(), Byte3 = (byte)s.ReadByte(), Byte4 = (byte)s.ReadByte(), Byte5 = (byte)s.ReadByte(), Byte6 = (byte)s.ReadByte(), Byte7 = (byte)s.ReadByte(), Byte8 = (byte)s.ReadByte() }; } catch (Exception ex) { // Probably, the hash was missing at all. throw new InvalidDataException(ErrorMessages.HashNotFound, ex); } // Value is valid if hashes match. if (c.Long != v.GetHashCode64()) { throw new InvalidDataException(string.Format(ErrorMessages.HashMismatch, v.GetHashCode64(), c.Long)); } }
/// <summary> /// Writes an anti-tamper hash code into given stream. /// </summary> /// <typeparam name="T">The type of the value.</typeparam> /// <param name="s">The stream.</param> /// <param name="v">The value.</param> public static void WriteAntiTamperHashCode <T>(Stream s, T v) where T : class, IObjectWithHashCode64 { var c = new LongToBytesConverter { Long = v.GetHashCode64() }; s.WriteByte(c.Byte1); s.WriteByte(c.Byte2); s.WriteByte(c.Byte3); s.WriteByte(c.Byte4); s.WriteByte(c.Byte5); s.WriteByte(c.Byte6); s.WriteByte(c.Byte7); s.WriteByte(c.Byte8); }