Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BinaryFormatter should be replaced #49

Open
njannink opened this issue Dec 15, 2020 · 3 comments
Open

BinaryFormatter should be replaced #49

njannink opened this issue Dec 15, 2020 · 3 comments

Comments

@njannink
Copy link

I updated my project to Net5 and now I get an exception because the BinaryFormatter has been marked insecure and throws and exception

https://docs.microsoft.com/nl-nl/dotnet/standard/serialization/binaryformatter-security-guide

@acarteas
Copy link
Owner

acarteas commented Sep 7, 2021

Closed in PR #52

@acarteas acarteas closed this as completed Sep 7, 2021
@acarteas acarteas reopened this Sep 7, 2021
@acarteas
Copy link
Owner

acarteas commented Sep 7, 2021

Reopened because serialization is still used in some cases.

@palenshus
Copy link

I got bit by this in a way I couldn't workaround with EnableUnsafeBinaryFormatterSerialization, so I ended up making a quick replacement using https://github.com/Cysharp/MemoryPack, hope this helps someone else experiencing the same issue until this gets fixed:

public partial class FileCache<T>
{
    private readonly string path;
    private readonly Dictionary<string, (DateTimeOffset, T)> cache;

    public FileCache(string path)
    {
        this.path = path;
        if (File.Exists(path))
        {
            var bytes = File.ReadAllBytes(path);
            this.cache = MemoryPackSerializer.Deserialize<Dictionary<string, (DateTimeOffset, T)>>(bytes);
        }
        else
        {
            this.cache = new();
        }
    }

    public async Task<T> GetOrAddAsync(string key, Func<Task<T>> valueFactory, DateTimeOffset absoluteExpiration)
    {
        if (!this.cache.ContainsKey(key) || DateTime.Now > this.cache[key].Item1)
        {
            this.cache[key] = (absoluteExpiration, await valueFactory());
            var bytes = MemoryPackSerializer.Serialize(this.cache);
            await File.WriteAllBytesAsync(this.path, bytes);
        }

        return this.cache[key].Item2;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants