AntiTamper.cs
using System;
using System.Text.Json;
public record struct LockedData( string Contents, int Hash );
public static class AntiTamper
{
public static LockedData Lock<T>( T data, int magic )
{
string contents = JsonSerializer.Serialize( data );
var hash = HashCode.Combine( contents.GetHashCode(), magic );
return new LockedData( contents, hash );
}
public static T Unlock<T>( LockedData locked, int magic, T defaultValue = default( T ) )
{
if ( string.IsNullOrWhiteSpace( locked.Contents ) )
{
return defaultValue;
}
var hash = HashCode.Combine( locked.Contents.GetHashCode(), magic );
if ( locked.Hash != hash )
{
throw new Exception( "Hash mismatch" );
}
return JsonSerializer.Deserialize<T>( locked.Contents );
}
}