| | | 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>Startup.AddDependencies</c>, which also adds |
| | | 9 | | /// <c>AddDataProtection()</c> to the container this protector's <see cref="IDataProtector" /> is |
| | | 10 | | /// resolved from. |
| | | 11 | | /// </summary> |
| | | 12 | | /// <remarks> |
| | | 13 | | /// A single, fixed purpose string scopes the protector to this one use — Data Protection derives |
| | | 14 | | /// a different key for every distinct purpose, so a secret protected here cannot be unprotected |
| | | 15 | | /// by any other component that also happens to call <c>CreateProtector</c>. |
| | | 16 | | /// </remarks> |
| | | 17 | | public class TotpSecretProtector : ITotpSecretProtector |
| | | 18 | | { |
| | | 19 | | private const string Purpose = "ArturRios.Heimdall.TwoFactorAuth.TotpSecret.v1"; |
| | | 20 | | |
| | | 21 | | private readonly IDataProtector _protector; |
| | | 22 | | |
| | 188 | 23 | | public TotpSecretProtector(IDataProtectionProvider provider) |
| | | 24 | | { |
| | 188 | 25 | | _protector = provider.CreateProtector(Purpose); |
| | 188 | 26 | | } |
| | | 27 | | |
| | | 28 | | public byte[] Protect(string base32Secret) => |
| | 19 | 29 | | _protector.Protect(Encoding.UTF8.GetBytes(base32Secret)); |
| | | 30 | | |
| | | 31 | | public string Unprotect(byte[] protectedSecret) => |
| | 33 | 32 | | Encoding.UTF8.GetString(_protector.Unprotect(protectedSecret)); |
| | | 33 | | } |