using System.Security.Cryptography;
using System.Text;

namespace NewRock.Sdk.Security
{
    public class Encryptor
    {
        /// <summary>
        /// 生成一个10位随机数字符串
        /// </summary>
        /// <returns></returns>
        public static string GenerateRandomNumber()
        {
            var sb = new StringBuilder();
            for (int i = 0; i < 10; i++)
            {
                sb.Append(Random.Shared.Next(0, 10));
            }
            return sb.ToString();
        }

        public static string GenerateTimestamp()
            => ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString();

        public static string Signature(string key, string nonce, string timestamp)
        {
            //signature=md5（API Password + nonce + timestamp）
            var content = key + nonce + timestamp;
            return MD5Encrypt(content);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <returns></returns>
        private static string MD5Encrypt(string input)
        {
            using var md5 = MD5.Create();
            var t = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
            var sb = new StringBuilder(32);
            for (var i = 0; i < t.Length; i++)
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            return sb.ToString();
        }

        /// <summary>
        /// MD5对文件流加密
        /// </summary>
        /// <returns></returns>
        private async Task<string> MD5EncryptAsync(Stream stream, CancellationToken cancellationToken)
        {
            var md5 = MD5.Create();
            var buffer = await md5.ComputeHashAsync(stream, cancellationToken);//md5serv.ComputeHash(stream);
            var sb = new StringBuilder();
            foreach (var var in buffer)
                sb.Append(var.ToString("x2"));
            return sb.ToString();
        }
        
    }
}
