Ejemplo n.º 1
0
        // https://docs.deribit.com/v2/#authentication
        /// <summary>
        /// Sign the request
        public AuthRequest Sign()
        {
            // validate
            if (this.grant_type != GrantType.client_credentials)
            {
                throw new InvalidOperationException($"GrantType must be {GrantType.client_credentials} prior to signing.");
            }
            if (this.client_id == null || this.client_secret == null)
            {
                throw new InvalidOperationException($"ClientCredentials are not set.");
            }
            byte[] clientsecretbytes = Convert.FromBase64String(this.client_secret);
            // locals
            data = data ?? "";
            Random random     = new Random();
            var    hmacsha256 = new HMACSHA256(clientsecretbytes);

            // determine timestamp
            this.timestamp = this.timestamp != default ? this.timestamp : DateTime.UtcNow.UnixTimeStampDateTimeUtcToMillis();
            // determine nonce
            this.nonce = this.nonce != default ? this.nonce : random.Next(int.MaxValue).ToString();
            // determine string to sign
            string stringtosign = $"{timestamp}\n{nonce}\n{data}";

            byte[] stringtosignbytes = Encoding.UTF8.GetBytes(stringtosign);
            // sign
            byte[] signaturebytes = hmacsha256.ComputeHash(stringtosignbytes);
            this.signature = signaturebytes.ByteArrayToHexString()
                             .ToLowerInvariant();
            this.grant_type = GrantType.client_signature;
            // dispose resources
            hmacsha256.Dispose();
            // return
            return(this);
        }
Ejemplo n.º 2
0
        public string GetHash <T>(string token, DateTime expirationDate, T payload)
        {
            HMACSHA256 sha256 = null;

            try
            {
                byte[] keyBytes = Encoding.UTF8.GetBytes(_secret);
                sha256 = new HMACSHA256(keyBytes);

                var toHash = new Dictionary <string, object>
                {
                    { nameof(token), token },
                    { nameof(expirationDate), expirationDate },
                    { nameof(payload), payload }
                };

                string hashable = JsonConvert.SerializeObject(toHash);

                byte[] hash =
                    sha256.ComputeHash(Encoding.UTF8.GetBytes(hashable));

                return(Convert.ToBase64String(hash));
            }
            finally
            {
                sha256?.Dispose();
            }
        }
Ejemplo n.º 3
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         _httpClient.Dispose();
         _hashAlgorithm.Dispose();
     }
 }
 protected virtual void Dispose(bool disposing)
 {
     if (!disposedValue)
     {
         hmac.Dispose();
         disposedValue = true;
     }
 }
Ejemplo n.º 5
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposing)
     {
         _hmac.Dispose();
         _disposing = true;
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Securely hashes the specified input with the key. PLEASE use this in conjunction with ciphertext. This is for validation- just append this to the end of the byte array and check on the other side. It's a hashing algorithm, treat it as one.
        /// </summary>
        /// <param name="input">The input to hash.</param>
        /// <param name="key">The key to hash the input with. Can be any length.</param>
        /// <returns>HMAC-256 hashed result.</returns>
        public byte[] Hmac256(byte[] input, byte[] key)
        {
            HMACSHA256 hmac = new HMACSHA256(HashSha256(key));

            byte[] retVal = hmac.ComputeHash(input);
            hmac.Dispose();
            return(retVal);
        }
Ejemplo n.º 7
0
        private byte[] hmac256(byte[] input, byte[] key)
        {
            HMACSHA256 hmac = new HMACSHA256(key);

            byte[] retVal = hmac.ComputeHash(input);
            hmac.Dispose();
            return(retVal);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Generate salt from password.
        /// </summary>
        /// <param name="password">Password string.</param>
        /// <returns>Salt bytes.</returns>
        private static byte[] SaltFromPassword(string password)
        {
            var passwordBytes = Encoding.UTF8.GetBytes(password);
            var algorithm     = new HMACSHA256(passwordBytes);
            var salt          = algorithm.ComputeHash(passwordBytes);

            algorithm.Dispose();
            return(salt);
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Libera los recursos usados durante calculos de códigos HMAC. Complementa la
 /// llamada a 'Inicia'.
 /// </summary>
 internal void Termina()
 {
     if (algoritmo == null)
     {
         return;
     }
     //
     algoritmo.Dispose();
 }
Ejemplo n.º 10
0
 public static string hmac_base64(string pwd, string data)
 {
     byte[] key = new byte[64];
     key = Encoding.Default.GetBytes(pwd);
     Stream s = new MemoryStream(ASCIIEncoding.Default.GetBytes(data));
     HMACSHA256 pl = new HMACSHA256(key);
     byte[] hashValue = pl.ComputeHash(s);
     pl.Dispose();
     return System.Convert.ToBase64String(hashValue);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// Generate salt from password.
        /// </summary>
        /// <param name="password">Password string.</param>
        /// <returns>Salt bytes.</returns>
        private static byte[] SaltFromPassword(byte[] passwordBytes)
        {
            var algorithm = new HMACSHA256();

            algorithm.Key = passwordBytes;
            var salt = algorithm.ComputeHash(passwordBytes);

            algorithm.Dispose();
            return(salt);
        }
Ejemplo n.º 12
0
        private bool _Disposed = false; // To detect redundant calls

        void Dispose(bool disposing)
        {
            if (!_Disposed)
            {
                if (disposing)
                {
                    _Algorithm.Dispose();
                }
                _Disposed = true;
            }
        }
Ejemplo n.º 13
0
        private bool IsValidRequest(HttpRequest req, string AppId, string incomingBase64Signature, string nonce, string requestTimeStamp)
        {
            string requestContentBase64String = "";
            string absoluteUri = string.Concat(
                req.Scheme,
                "://",
                req.Host.ToUriComponent(),
                req.PathBase.ToUriComponent(),
                req.Path.ToUriComponent(),
                req.QueryString.ToUriComponent());
            string requestUri        = WebUtility.UrlEncode(absoluteUri).ToLower();
            string requestHttpMethod = req.Method;

            string authKey = Options.AuthKeys.GetValueOrDefault(AppId);

            if (string.IsNullOrEmpty(authKey))
            {
                return(false);
            }

            string sharedKey = authKey;

            if (IsReplayRequest(nonce, requestTimeStamp))
            {
                return(false);
            }

            byte[] hash = ComputeHash(req.Body);

            if (hash != null)
            {
                requestContentBase64String = Convert.ToBase64String(hash);
            }

            string data = String.Format("{0}{1}{2}{3}{4}{5}",
                                        AppId,
                                        requestHttpMethod,
                                        requestUri,
                                        requestTimeStamp,
                                        nonce,
                                        requestContentBase64String);

            byte[] secretKeyBytes = Convert.FromBase64String(sharedKey);

            byte[] signature = Encoding.UTF8.GetBytes(data);

            HMACSHA256 hmac = new HMACSHA256(secretKeyBytes);

            byte[] signatureBytes = hmac.ComputeHash(signature);
            hmac.Dispose();

            return(incomingBase64Signature.Equals(Convert.ToBase64String(signatureBytes), StringComparison.Ordinal));
        }
Ejemplo n.º 14
0
        public void InitializePasswordHash()
        {
            // Hashed password
            Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(PrivatePassword, 32, 1000);

            HMACSHA256 hmac = new HMACSHA256(deriveBytes.GetBytes(256));

            PasswordHashSalt = deriveBytes.Salt;
            PasswordHash     = hmac.ComputeHash(deriveBytes.Salt);
            hmac.Dispose();
            deriveBytes.Dispose();
        }
Ejemplo n.º 15
0
        protected virtual void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                if (disposing)
                {
                    _hmacsha256.Dispose();
                }

                isDisposed = true;
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 文字列のHMACハッシュコード取得
        /// </summary>
        /// <param name="password">パスワード</param>
        /// <returns>ハッシュデータとソルト</returns>
        public string[] GetHMAC(string password)
        {
            List <string>      passData    = new List <string>();
            Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, 32);
            HMACSHA256         hmac        = new HMACSHA256(deriveBytes.GetBytes(256));

            // ハッシュデータの出力
            passData.Add(BitConverter.ToString(hmac.ComputeHash(deriveBytes.Salt)).Replace("-", ""));
            passData.Add(BitConverter.ToString(deriveBytes.Salt).Replace("-", ""));
            hmac.Dispose();
            deriveBytes.Dispose();
            return(passData.ToArray());
        }
Ejemplo n.º 17
0
        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // Free other state (managed objects).
                }

                _httpClient.Dispose();
                _hashAlgorithm.Dispose();
                _disposed = true;
            }
        }
        private String createToken(String payload)
        {
            var header = JObject.FromObject(new { typ = "JWT", alg = "HS256" });

            String     h    = encodeBase64Safe(header.ToString());
            String     p    = encodeBase64Safe(payload);
            String     c    = String.Format("{0}.{1}", h, p);
            HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));

            byte[] signature = hmac.ComputeHash(Encoding.UTF8.GetBytes(c));
            String sig       = encodeBase64Safe(signature);

            hmac.Dispose();
            return(String.Format("{0}.{1}", c, sig));
        }
Ejemplo n.º 19
0
        private string Signature(string totalParams)
        {
            byte[] key     = Encoding.ASCII.GetBytes(this.APIsecret);
            byte[] message = Encoding.ASCII.GetBytes(totalParams);
            var    hmac    = new HMACSHA256(key);

            byte[]        hash    = hmac.ComputeHash(message);
            StringBuilder builder = new StringBuilder();

            for (int i = 0; i < hash.Length; i++)
            {
                builder.Append(hash[i].ToString("x2"));
            }
            hmac.Dispose();
            return(builder.ToString());
        }
Ejemplo n.º 20
0
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (initialized)
            {
                gzipStream.Dispose();

                aesStream.Dispose();
                aesTransform.Dispose();

                hmacStream.Dispose();
                hmacTransform.Dispose();
                hmacHash.Dispose();
            }
        }
Ejemplo n.º 21
0
        private bool disposedValue = false; // 要检测冗余调用

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                    _hmacsha256.Dispose();
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }
Ejemplo n.º 22
0
        private string GenerateJWTSignature(string key, string header, string payload)
        {
            var sb = new StringBuilder(header);

            sb.Append('.');
            sb.Append(payload);
            byte[]     headPayInBytes = Encoding.UTF8.GetBytes(sb.ToString());
            byte[]     keyInBytes     = Encoding.UTF8.GetBytes(key);
            HMACSHA256 hash           = new HMACSHA256(keyInBytes);

            byte[] signature = hash.ComputeHash(headPayInBytes);
            hash.Dispose();
            string encodedSignature = _encoder.CleanString(signature);

            return(encodedSignature);
        }
Ejemplo n.º 23
0
        private string GenerateTokenSignature(string encodedHeader,
                                              string encodedPayload,
                                              string key)
        {
            if (encodedHeader == null || encodedPayload == null ||
                key == null)
            {
                throw new ArgumentNullException("Null argument passed.");
            }
            byte[]     preSign = Encoding.UTF8.GetBytes(encodedHeader + "." + encodedPayload);
            byte[]     byteKey = Encoding.UTF8.GetBytes(key);
            HMACSHA256 hmac    = new HMACSHA256(byteKey);

            byte[] signature = hmac.ComputeHash(preSign);
            hmac.Dispose();
            return(_encoder.ToUrlSafeBase64Str(signature));
        }
Ejemplo n.º 24
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            if (string.IsNullOrWhiteSpace(context.Request.Headers["x-slack-request-timestamp"]) ||
                string.IsNullOrWhiteSpace(context.Request.Headers["x-slack-signature"]))
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Invalid signature");
                return;
            }

            string slackSignature = context.Request.Headers["x-slack-signature"];
            var timestamp = long.Parse(context.Request.Headers["x-slack-request-timestamp"]);
            var signingSecret = Environment.GetEnvironmentVariable("SLACK_SIGNING_SECRET");
            string content;

            context.Request.EnableBuffering();

            using (var reader = new StreamReader(context.Request.Body, Encoding.UTF8, true, 1024, true))
            {
                content = await reader.ReadToEndAsync();
            }

            context.Request.Body.Position = 0;

            var sigBase = $"v0:{timestamp}:{content}";

            var encoding = new UTF8Encoding();

            var hmac = new HMACSHA256(encoding.GetBytes(signingSecret));
            var hashBytes = hmac.ComputeHash(encoding.GetBytes(sigBase));

            var generatedSignature = "v0=" + BitConverter.ToString(hashBytes).Replace("-", "").ToLower();

            if (generatedSignature == slackSignature)
            {
                await next(context);
            }
            else
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync("Request signing failed");
            }

            hmac.Dispose();
        }
Ejemplo n.º 25
0
        protected override void Dispose(bool disposing)
        {
            if (!isDisposed)
            {
                isDisposed = true;
                base.Dispose(disposing);

                //Dispose in the reverse order of creation
                gzipStream.Dispose();

                aesStream.Dispose();
                aesTransform.Dispose();

                hmacStream.Dispose();
                hmacTransform.Dispose();
                hmacHash.Dispose();
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Generate salt from password.
        /// </summary>
        /// <param name="password">Password string.</param>
        /// <returns>Salt bytes.</returns>
        private static byte[] SaltFromPassword(string password)
        {
            var  passwordBytes = Encoding.UTF8.GetBytes(password);
            HMAC algorithm;

            switch (AesSaltAlgorithm)
            {
            case "HMACSHA1": algorithm = new HMACSHA1(); break;

            case "HMACSHA256": algorithm = new HMACSHA256(); break;

            default: algorithm = new HMACSHA256(); break;
            }
            algorithm.Key = passwordBytes;
            var salt = algorithm.ComputeHash(passwordBytes);

            algorithm.Dispose();
            return(salt);
        }
Ejemplo n.º 27
0
        public bool MatchPassword(string password, byte[] rawData)
        {
            byte[] passHash = new byte[32];
            byte[] passSalt = new byte[32];

            Buffer.BlockCopy(rawData, 16, passHash, 0, 32);
            Buffer.BlockCopy(rawData, 48, passSalt, 0, 32);

            // Hashed password
            Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, passSalt);

            HMACSHA256 hmac = new HMACSHA256(deriveBytes.GetBytes(256));

            byte[] tmpPassHash = hmac.ComputeHash(deriveBytes.Salt);
            hmac.Dispose();
            deriveBytes.Dispose();

            return(((IStructuralEquatable)tmpPassHash).Equals(passHash, StructuralComparisons.StructuralEqualityComparer));
        }
Ejemplo n.º 28
0
        private void VerifySignatureInfo()
        {
            int ikid = 0;

            if (!int.TryParse(_Envelope.kid, out ikid))
            {
                throw new ArgumentOutOfRangeException("Key ID should be a number more than 0, PassedVal:" + _Envelope.kid);
            }

            if (ikid > ConfigProvider.ConfigurationStore.LiveAuthKeyCount)
            {
                throw new ArgumentOutOfRangeException(string.Format("Key ID: {0}, is not configured properly or not loaded.", ikid));
            }

            _CurrentSecretKey = ConfigProvider.ConfigurationStore.LiveAuthKeys[ikid];

            byte[] bKey = SOSCodecs.UTF8Encoder.GetBytes(_CurrentSecretKey + "JWTSig");

            SHA256Managed SHAprovider = SecurityCodecs.SHA256CryptoProvider;

            byte[] bCryptKey = SHAprovider.ComputeHash(bKey);

            byte[] bCombined = SOSCodecs.UTF8Encoder.GetBytes(_RawToken.Envelope + "." + _RawToken.Claims);

            SecurityCodecs codec = new SecurityCodecs();

            HMACSHA256 HMACHACryptoProvider = codec.HMACSHA256Provider(bCryptKey);

            _IsTokenValid = SOSCodecs.UrlEncode(HMACHACryptoProvider.ComputeHash(bCombined)) == _RawToken.Signature;

            codec.Dispose();

            SHAprovider.Clear();
            SHAprovider.Dispose();

            HMACHACryptoProvider.Clear();
            HMACHACryptoProvider.Dispose();
        }
Ejemplo n.º 29
0
 public void Dispose()
 {
     _hmac.Dispose();
     GC.SuppressFinalize(this);
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
 /// </summary>
 public void Dispose()
 {
     _Hasher?.Dispose();
     _Hasher = null;
 }