| | | 1 | | using System.Text; |
| | | 2 | | using Microsoft.AspNetCore.DataProtection; |
| | | 3 | | |
| | | 4 | | namespace ArturRios.Heimdall.Command.Services; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Default <see cref="ITotpSecretProtector" />, wrapping ASP.NET Core's Data Protection API |
| | | 8 | | /// (UC-36 step 3, FR-2F-02). Registered from <c>CommandServiceCollectionExtensions.AddTwoFactorServices</c>, |
| | | 9 | | /// after <c>DataServiceCollectionExtensions.AddDataProtectionKeyRing</c> has added |
| | | 10 | | /// <c>AddDataProtection()</c> to the container this protector's <see cref="IDataProtector" /> is |
| | | 11 | | /// resolved from. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <remarks> |
| | | 14 | | /// A single, fixed purpose string scopes the protector to this one use — Data Protection derives |
| | | 15 | | /// a different key for every distinct purpose, so a secret protected here cannot be unprotected |
| | | 16 | | /// by any other component that also happens to call <c>CreateProtector</c>. |
| | | 17 | | /// </remarks> |
| | | 18 | | public class TotpSecretProtector : ITotpSecretProtector |
| | | 19 | | { |
| | | 20 | | private const string Purpose = "ArturRios.Heimdall.TwoFactorAuth.TotpSecret.v1"; |
| | | 21 | | |
| | | 22 | | private readonly IDataProtector _protector; |
| | | 23 | | |
| | 194 | 24 | | public TotpSecretProtector(IDataProtectionProvider provider) |
| | | 25 | | { |
| | 194 | 26 | | _protector = provider.CreateProtector(Purpose); |
| | 194 | 27 | | } |
| | | 28 | | |
| | | 29 | | public byte[] Protect(string base32Secret) => |
| | 19 | 30 | | _protector.Protect(Encoding.UTF8.GetBytes(base32Secret)); |
| | | 31 | | |
| | | 32 | | public string Unprotect(byte[] protectedSecret) => |
| | 40 | 33 | | Encoding.UTF8.GetString(_protector.Unprotect(protectedSecret)); |
| | | 34 | | } |