using FastEndpoints; using GB5Shared.DTO.Framework.Login; using GB5Shared.DTO.Framework.ResponseStandard; using GB5Shared.FastEndPoint; using static GB5Shared.GB5Constant.Constant; using System; using System.Text; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; namespace FrameworkSL.Endpoints.Decrypt { public class GetDecrypt : BaseEndpoint> { public override void Configure() { Get("/Decrypt/GetDecrypt"); AllowAnonymous(); } public record GetDecryptParameters( [property: FromHeader] string Login, [property: QueryParam] string EncryptedText, [property: QueryParam] string Key ); protected override async Task> ExecuteAsync( GetDecryptParameters req, LoginDTO LoginDTO, CancellationToken ct) { try { var result = Decrypt(req.EncryptedText, req.Key); return await GB5Shared.ResponseStandard.Response .CreateSuccessResponse(result, CacheKeyLevel.USER_LEVEL, LoginDTO); } catch (Exception ex) { return await GB5Shared.ResponseStandard.Response .CreateExceptionError(ex, CacheKeyLevel.USER_LEVEL, LoginDTO, ex.Message, 500); } } private string Decrypt(string encryptedText, string key) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Key cannot be null or empty."); if (string.IsNullOrWhiteSpace(encryptedText)) throw new ArgumentException("EncryptedText cannot be null or empty."); byte[] fullCipher = Convert.FromBase64String(encryptedText); // SHA256 hash of key (32 bytes) using SHA256 sha256 = SHA256.Create(); byte[] keyBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(key)); // AES-GCM standard sizes const int ivSize = 12; const int tagSize = 16; if (fullCipher.Length < ivSize + tagSize) throw new ArgumentException("Invalid encrypted payload."); byte[] iv = new byte[ivSize]; byte[] tag = new byte[tagSize]; byte[] ciphertext = new byte[fullCipher.Length - ivSize - tagSize]; // Extract IV Buffer.BlockCopy(fullCipher, 0, iv, 0, ivSize); // Extract ciphertext Buffer.BlockCopy(fullCipher, ivSize, ciphertext, 0, ciphertext.Length); // Extract tag (last 16 bytes) Buffer.BlockCopy(fullCipher, fullCipher.Length - tagSize, tag, 0, tagSize); byte[] plaintext = new byte[ciphertext.Length]; using AesGcm aes = new AesGcm(keyBytes); aes.Decrypt(iv, ciphertext, tag, plaintext); return Encoding.UTF8.GetString(plaintext); } } }