From cebaac553c4164c9a70b0fa9c85e114cb7372727 Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Tue, 8 Aug 2023 00:20:52 +0100 Subject: [PATCH] feat: add gravatar hash calculation --- OliverBooth/Data/Blog/Author.cs | 35 ++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/OliverBooth/Data/Blog/Author.cs b/OliverBooth/Data/Blog/Author.cs index 9fd09a8..9a5aa26 100644 --- a/OliverBooth/Data/Blog/Author.cs +++ b/OliverBooth/Data/Blog/Author.cs @@ -1,10 +1,43 @@ -namespace OliverBooth.Data.Blog; +using System.ComponentModel.DataAnnotations.Schema; +using System.Security.Cryptography; +using System.Text; + +namespace OliverBooth.Data.Blog; /// /// Represents an author of a blog post. /// public sealed class Author : IEquatable { + [NotMapped] + public string AvatarHash + { + get + { + if (EmailAddress is null) + { + return string.Empty; + } + + using var md5 = MD5.Create(); + ReadOnlySpan span = EmailAddress.AsSpan(); + int byteCount = Encoding.UTF8.GetByteCount(span); + Span bytes = stackalloc byte[byteCount]; + Encoding.UTF8.GetBytes(span, bytes); + + Span hash = stackalloc byte[16]; + md5.TryComputeHash(bytes, hash, out _); + + var builder = new StringBuilder(); + foreach (byte b in hash) + { + builder.Append(b.ToString("x2")); + } + + return builder.ToString(); + } + } + /// /// Gets or sets the email address of the author. ///