Created
October 18, 2023 13:49
-
-
Save d1820/e7e3f29cbf851368245108e18757e91f to your computer and use it in GitHub Desktop.
JsonConverter Obfuscator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ObfuscatorConverter : JsonConverter | |
{ | |
private readonly IEnumerable<Type> _types; | |
private readonly int _charsToShow; | |
private readonly char _obfuscateChar; | |
public ObfuscatorConverter() : this(2, '*') | |
{ | |
} | |
public ObfuscatorConverter(int charsToShow = 2, char obfuscateChar = '*') | |
{ | |
_types = new List<Type> | |
{ | |
typeof(string), | |
typeof(Guid) | |
}; | |
_charsToShow = charsToShow; | |
_obfuscateChar = obfuscateChar; | |
} | |
public override bool CanConvert(Type objectType) | |
{ | |
return _types.Any(t => t == objectType); | |
} | |
public override bool CanWrite => true; | |
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) | |
{ | |
if (value != null) | |
{ | |
var currentValue = value.ToString(); | |
if (!string.IsNullOrWhiteSpace(currentValue)) | |
{ | |
//encode the string | |
var array = currentValue.ToCharArray(); | |
var stopIndex = array.Length - _charsToShow; | |
for (var i = 0; i < array.Length; i++) | |
{ | |
if (i < stopIndex) | |
{ | |
array[i] = _obfuscateChar; | |
} | |
} | |
var newValue = new string(array); | |
writer.WriteValue(newValue); | |
} | |
} | |
} | |
public override bool CanRead => false; | |
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) | |
{ | |
throw new NotImplementedException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment