C# Signature Generator

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace SignatureGenerator
{
    public interface ISignature
    {
        string Hash { get; set; }
        string Salt { get; set; }
    }

    public class SignatureGenerator
    {
        public ISignature Generate(string url, object parameters, string secret, string salt = "")
        {
            var uri = new Uri(url);
            var path = uri.AbsolutePath;

            var values = GetValues(parameters);
            var toSign = path + string.Join("", values) + salt;

            var hash = HmacSha256(toSign, Encoding.UTF8.GetBytes(secret));

            return new ISignature
            {
                Hash = hash,
                Salt = salt
            };
        }

        private IEnumerable<string> GetValues(object obj)
        {
            var values = new List<string>();

            obj = (obj.GetType()
                .GetProperties()
                .OrderBy(x => x.Name)
                .ToDictionary(x => x.Name, x => x.GetValue(obj, null)));

            foreach (var kvp in obj as Dictionary<string, object>)
            {
                var value = kvp.Value;
                if (value is IEnumerable<object> || value is object)
                {
                    values.AddRange(GetValues(value));
                    continue;
                }

                if (value is bool)
                {
                    values.Add((bool)value ? "1" : "0");
                    continue;
                }

                values.Add(value != null ? value.ToString() : "");
            }

            return values;
        }

        private string HmacSha256(string message, byte[] key)
        {
            using (var hmac = new HMACSHA256(key))
            {
                var msgBuffer = Encoding.UTF8.GetBytes(message);
                var hashBuffer = hmac.ComputeHash(msgBuffer);
                var hashArray = hashBuffer.Select(b => b.ToString("X2")).ToArray();

                return string.Join("", hashArray);
            }
        }
    }
}
ssofyKnowledge Base
At our core, we believe that staying up-to-date with the latest trends and advancements in Authentication and related areas is essential. That's why we take great pride in keeping you informed with the latest insights, updates, and news in this rapidly evolving landscape.


Do you need support?
SSOfy is by Cubelet Ltd.
Copyright © 2024 Cubelet Ltd. All rights reserved.