public bool VerifySignedToken(string nounce, string ticketLeft, string ticketRight)
        {
            System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(UTF8Encoding.UTF8.GetBytes(MasterKey));
            string hash = BitConverter.ToString(hmac.ComputeHash(UTF8Encoding.UTF8.GetBytes(nounce))).Replace("-", "");

            return(hash == ticketLeft.Trim() + ticketRight.Trim());
        }
 public Rfc2898DeriveBytes_HMACSHA256(byte[] password, byte[] salt, int iterations)
 {
     Salt = salt;
     IterationCount = iterations;
     _hmacsha256 = new HMACSHA256(password);
     Initialize();
 }
Beispiel #3
0
        public string GenerateStorageSasTokenWrite(string resourceName, string storageAccountUrl, string storageAccountKey)
        {
            var storageAccountName = storageAccountUrl.Remove(0, 8).Split('.')[0];
            var version            = "2018-03-28";
            var startTime          = DateTime.UtcNow;
            var startTimeIso       = startTime.ToString("s") + "Z";
            var endTimeIso         = startTime.AddMinutes(10).ToString("s") + "Z";
            var hmacSha256         = new System.Security.Cryptography.HMACSHA256 {
                Key = Convert.FromBase64String(storageAccountKey)
            };
            var payLoad = string.Format(
                "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n\n\n\n\n",
                "rw",
                startTimeIso,
                endTimeIso,
                "/blob/" + storageAccountName + "/" + resourceName,
                "",
                "",
                "https",
                "2018-03-28");
            var sasToken = storageAccountUrl + resourceName +
                           "?" +
                           "sp=rw&st=" + startTimeIso + "&se=" + endTimeIso + "&spr=https" +
                           "&sv=" + version +
                           "&sig=" + Uri.EscapeDataString(Convert.ToBase64String(hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad)))) +
                           "&sr=b";

            return(sasToken);
        }
        /// <summary>
        /// This creates the authorization header. This is required, and must be built
        ///   exactly following the instructions. This will return the authorization header
        ///   for most storage service calls.
        /// Create a string of the message signature and then encrypt it.
        /// </summary>
        /// <param name="storageAccountName">The name of the storage account to use.</param>
        /// <param name="storageAccountKey">The access key for the storage account to be used.</param>
        /// <param name="now">Date/Time stamp for now.</param>
        /// <param name="httpRequestMessage">The HttpWebRequest that needs an auth header.</param>
        /// <param name="ifMatch">Provide an eTag, and it will only make changes
        /// to a blob if the current eTag matches, to ensure you don't overwrite someone else's changes.</param>
        /// <param name="md5">Provide the md5 and it will check and make sure it matches the blob's md5.
        /// If it doesn't match, it won't return a value.</param>
        /// <returns></returns>

        internal static string AuthorizationHeader(string storageAccountName, string storageAccountKey,
                                                   string method, DateTime now, HttpWebRequest request, string ifMatch = "", string md5 = "")
        {
            string MessageSignature;

            //this is the raw representation of the message signature
            MessageSignature = String.Format("{0}\n\n\n{1}\n{5}\n\n\n\n{2}\n\n\n\n{3}{4}",
                                             method,
                                             (method == "GET" || method == "HEAD") ? String.Empty : request.ContentLength.ToString(),
                                             ifMatch,
                                             GetCanonicalizedHeaders(request),
                                             GetCanonicalizedResource(request.RequestUri, storageAccountName),
                                             md5
                                             );

            //now turn it into a byte array
            byte[] SignatureBytes = System.Text.Encoding.UTF8.GetBytes(MessageSignature);

            //create the HMACSHA256 version of the storage key
            System.Security.Cryptography.HMACSHA256 SHA256 =
                new System.Security.Cryptography.HMACSHA256(Convert.FromBase64String(storageAccountKey));

            //Compute the hash of the SignatureBytes and convert it to a base64 string.
            string signature = Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));

            //this is the actual header that will be added to the list of request headers
            string AuthorizationHeader = "SharedKey " + storageAccountName
                                         + ":" + Convert.ToBase64String(SHA256.ComputeHash(SignatureBytes));

            return(AuthorizationHeader);
        }
Beispiel #5
0
        public static string BuildBase64Signature(
                string apiKey,
                string appId,
                Uri rawUri,
                HttpMethod httpMethod,
                HttpContent content,
                string nonce,
                string requestTimeStamp
            )
        {
            var requestUri = HttpUtility.UrlEncode(rawUri.AbsoluteUri.ToLower());
            var requestHttpMethod = httpMethod.Method;

            // Get the content string out of the content.
            string requestContentBase64String = ComputeBase64RequestContent(content);

            // Rebuild the signature raw data.
            var signatureRawData =
            $"{appId}{requestHttpMethod}{requestUri}{requestTimeStamp}{nonce}{requestContentBase64String}";

            // Get the api key bytes.
            var secretKeyBytes = Convert.FromBase64String(apiKey);

            // Get the signature.
            var signature = Encoding.UTF8.GetBytes(signatureRawData);

            // Create HMAC SHA class with key data.
            using (var hmac = new HMACSHA256(secretKeyBytes))
            {
                return Convert.ToBase64String(hmac.ComputeHash(signature));
            }
        }
Beispiel #6
0
                public static Digest /*!*/ Initialize(Digest /*!*/ self, [NotNull] MutableString /*!*/ algorithmName)
                {
                    Crypto.HMAC algorithm;

#if SILVERLIGHT
                    switch (algorithmName.ToString())
                    {
                    case "SHA1": algorithm = new Crypto.HMACSHA1(); break;

                    case "SHA256": algorithm = new Crypto.HMACSHA256(); break;

                    default: algorithm = null; break;
                    }
#else
                    algorithm = Crypto.HMAC.Create("HMAC" + algorithmName.ConvertToString());
#endif

                    if (algorithm == null)
                    {
                        throw RubyExceptions.CreateRuntimeError("Unsupported digest algorithm ({0}).", algorithmName);
                    }

                    self._algorithm = algorithm;
                    return(self);
                }
 public static byte[] GenerateMac(byte[] clearText, byte[] key)
 {
     using (HMACSHA256 hmac = new HMACSHA256(key))
     {
         return hmac.ComputeHash(clearText);
     }
 }
Beispiel #8
0
 static byte[] hmacSHA256(String data, String key)
 {
     using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
     {
         return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
     }
 }
 public byte[] ComputeHmac(string input)
 {
     using (var hmac = new HMACSHA256(this.signingKey))
     {
         return hmac.ComputeHash(this.encoding.GetBytes(input));
     }
 }
Beispiel #10
0
 public static string CreateToken(string message, string key)
 {
     var myhmacsha1 = new HMACSHA256(Encoding.ASCII.GetBytes(key));
     var byteArray = Encoding.ASCII.GetBytes(message);
     var stream = new MemoryStream(byteArray);
     return myhmacsha1.ComputeHash(stream).Aggregate("", (s, e) => s + $"{e:x2}", s => s);
 }
 public byte[] ComputeHmac(byte[] sessionKey, byte[] encrpytedData)
 {
     using (var hmac = new HMACSHA256(sessionKey))
     {
         return hmac.ComputeHash(encrpytedData);
     }
 }
Beispiel #12
0
		public static void Main (string[] args)
		{
			var host = "https://api.coinbase.com/";
			var apiKey = "yourApiKey";
			var apiSecret = "youApiSecret";

			var unixTimestamp = (Int32)(DateTime.UtcNow.Subtract (new DateTime (1970, 1, 1))).TotalSeconds;
			var currency = "USD";
			var message = string.Format ("{0}GET/v2/prices/spot?currency={1}", unixTimestamp.ToString (), currency);

			byte[] secretKey = Encoding.UTF8.GetBytes (apiSecret);
			HMACSHA256 hmac = new HMACSHA256 (secretKey);
			hmac.Initialize ();
			byte[] bytes = Encoding.UTF8.GetBytes (message);
			byte[] rawHmac = hmac.ComputeHash (bytes);
			var signature = rawHmac.ByteArrayToHexString ();

			var price = host
				.AppendPathSegment ("v2/prices/spot")
				.SetQueryParam ("currency", currency)
				.WithHeader ("CB-ACCESS-SIGN", signature)
				.WithHeader ("CB-ACCESS-TIMESTAMP", unixTimestamp)
				.WithHeader ("CB-ACCESS-KEY", apiKey)
				.GetJsonAsync<dynamic> ()
				.Result;

			Console.WriteLine (price.ToString (Formatting.None));
			Console.ReadLine ();
		}
        bool m_isCheckAmazonAwsInstancesEmailWasSent = false;  // to avoid sending the same warning email many times; send only once

        //# Key derivation functions. See: 
        //# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
        internal byte[] sign(byte[] key, string msg)
        {
            HMACSHA256 hmac = new HMACSHA256(key);
            var computedDigest = hmac.ComputeHash(Encoding.UTF8.GetBytes(msg));
            return computedDigest;
            //return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest();
        }
Beispiel #14
0
 public static string HMACSHA256(string key, string message)
 {
     using (var hasher = new crypto.HMACSHA256(Encoding.UTF8.GetBytes(key)))
     {
         return(hasher.ComputeHash(Encoding.UTF8.GetBytes(message)).ToHexString());
     }
 }
Beispiel #15
0
 public static bool Verify(string apikey, string token, string timestamp, string signature)
 {
     var hmac = new HMACSHA256(Encoding.ASCII.GetBytes(apikey));
     var sigBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(timestamp + token));
     string sigString = BitConverter.ToString(sigBytes).Replace("-", "");
     return signature.Equals(sigString, StringComparison.OrdinalIgnoreCase);
 }
Beispiel #16
0
        public static string issueAzureHTTPRequest(string URI)
        {
            /** code borrowed & adapted from: http://www.csharp-station.com/HowTo/HttpWebFetch.aspx **/

            // used to build entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create(URI);

              String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);

            WebHeaderCollection myWebHeaders = request.Headers;
            myWebHeaders.Add("x-ms-version","2009-09-19");
            myWebHeaders.Add("x-ms-date",dateInRfc1123Format);
            //do SHA-256 hash of key
            string toSign =
            "GET\n\n\n\n\n\n\n\n\n\n\n\nx-ms-date:"+dateInRfc1123Format+"\nx-ms-version:2009-09-19\n/"+AccountInfo.AccountName+"/\ncomp:list";    /*CanonicalizedResource*/

            byte[] signBytes = System.Text.Encoding.UTF8.GetBytes(toSign);
            byte[] hash = new HMACSHA256(Convert.FromBase64String(AccountInfo.AccountKey)).ComputeHash(signBytes);
            string signature = System.Convert.ToBase64String(hash);
            string authHeaderValue = string.Format(CultureInfo.InvariantCulture, "SharedKey {0}:{1}", AccountInfo.AccountName, signature);

            myWebHeaders.Add("Authorization",authHeaderValue);

            // execute the request
            HttpWebResponse response = (HttpWebResponse)
                request.GetResponse();

            // we will read data via the response stream
            Stream resStream = response.GetResponseStream();

            string tempString = null;
            int count = 0;

            do
            {
                // fill the buffer with data
                count = resStream.Read(buf, 0, buf.Length);

                // make sure we read some data
                if (count != 0)
                {
                    // translate from bytes to ASCII text
                    tempString = Encoding.ASCII.GetString(buf, 0, count);

                    // continue building the string
                    sb.Append(tempString);
                }
            }
            while (count > 0); // any more data to read?

            // print out page source
            return sb.ToString();
        }
Beispiel #17
0
        private static byte[] PHash(byte[] secret, byte[] seed, int iterations)
        {
            using (HMACSHA256 hmac = new HMACSHA256(secret))
            {
                byte[][] a = new byte[iterations + 1][];

                a[0] = seed;

                for (int i = 0; i < iterations; i++)
                {
                    a[i + 1] = hmac.ComputeHash(a[i]);
                }

                byte[] prf = new byte[iterations * 32];

                byte[] buffer = new byte[32 + seed.Length];
                Buffer.BlockCopy(seed, 0, buffer, 32, seed.Length);

                for (int i = 0; i < iterations; i++)
                {
                    Buffer.BlockCopy(a[i + 1], 0, buffer, 0, 32);

                    byte[] hash = hmac.ComputeHash(buffer);

                    Buffer.BlockCopy(hash, 0, prf, 32 * i, 32);
                }

                return prf;
            }
        }
Beispiel #18
0
        /// <summary>
        /// Computes the hmacSha256 hash of the data using the key given
        /// </summary>
        /// <param name="keyBytes">The key to use to calculate the hash</param>
        /// <param name="dataBytes">The data to use to calculate the hash</param>
        /// <returns>The hmacSha256 hash of the data using the key</returns>
		private static byte[] ComputeHash( byte[] keyBytes, byte[] dataBytes ) {
			byte[] hash;
			using( var hmacSha256 = new HMACSHA256( keyBytes ) ) {
				hash = hmacSha256.ComputeHash( dataBytes );
			}
			return hash;
		}
Beispiel #19
0
    /// <summary>Hash new password.</summary>
    public static string HashPassword(string password, int security = 256)
    {
        // You can limit security to 128-bit which will produce
        // base64 string, which will fit into a varchar(44) field on the database.
        // This will allow to store encrypted password in old password field if its size is limited.
        var size      = security / 8;
        var algorithm = new System.Security.Cryptography.HMACSHA256();
        // ----------------------------------------------------------------
        // Convert string to bytes.
        // Use Unicode, because ASCII doesn't work worldwide and SQL server doesn't support UTF8.
        var bytes = System.Text.Encoding.Unicode.GetBytes(password);
        // Generate random salt.
        var salt      = new byte[size];
        var generator = System.Security.Cryptography.RandomNumberGenerator.Create();

        generator.GetBytes(salt);
        // Compute hash.
        algorithm.Key = salt;
        var hash = algorithm.ComputeHash(bytes);
        // Combine salt and hash and convert to HEX.
        var baseBytes = new byte[size * 2];

        Array.Copy(salt, 0, baseBytes, 0, size);
        Array.Copy(hash, 0, baseBytes, size, size);
        Console.WriteLine("HashPassword:"******"  Salt: {0}", string.Join("", salt.Select(x => x.ToString("X2"))));
        Console.WriteLine("  Hash: {0}", string.Join("", hash.Take(size).Select(x => x.ToString("X2"))));
        // Convert salt and hash to Base64 string.
        var base64 = System.Convert.ToBase64String(baseBytes);

        return(base64);
    }
Beispiel #20
0
 /// <summary>
 /// Every time is created new instance of class to guarantee thread safety
 /// </summary>
 /// <param name="function"></param>
 /// <returns></returns>
 private HMAC GetAlgorithmByFunctionName(string function)
 {
     HMAC a;
     switch(Util.Convertion.EnumNameToValue<HMACFunction>(function))
     {
         case HMACFunction.HMACMD5:
             a = new HMACMD5();
             break;
         case HMACFunction.HMACSHA1:
             a = new HMACSHA1();
             break;
         case HMACFunction.HMACSHA256:
             a = new HMACSHA256();
             break;
         case HMACFunction.HMACSHA384:
             a = new HMACSHA384();
             break;
         case HMACFunction.HMACSHA512:
             a = new HMACSHA512();
             break;
         default:
             throw new ArgumentException("Unknown function", "function");
     }
     return a;
 }
 /// <summary>
 /// Computes a new hash of <paramref name="data"/> usign the <paramref name="key"/> specified.
 /// </summary>
 /// <param name="key">A byte array containing the key (secret) to use to generate a hash.</param>
 /// <param name="data">A byte arrasy containing the data to be hashed.</param>
 /// <returns>A new byte array containing the hash result.</returns>
 public byte[] ComputeHash(byte[] key, byte[] data)
 {
     using (var hasher = new System.Security.Cryptography.HMACSHA256(key))
     {
         return(hasher.ComputeHash(data));
     }
 }
Beispiel #22
0
        public override string ToString()
        {
            StringBuilder content = new StringBuilder();

            content.Append("Issuer=").Append(this.Issuer);


            for (int i = 0; i < this.claims.Count; i++)
            {
                var claim = claims[i];
                if (i == 0)
                    content.Append('&').Append("Claims").Append('=');
                content.AppendFormat("{0}:{1}:{2}", claim.ClaimType, claim.Resource, claim.Right);
                if (i < this.claims.Count - 1)
                    content.Append(',');
            }

            content.Append("&ExpiresOn=").Append(this.ExpiresOn);

            if (!string.IsNullOrWhiteSpace(this.Audience))
            {
                content.Append("&Audience=").Append(this.Audience);
            }

            using (HMACSHA256 hmac = new HMACSHA256(keyBytes))
            {
                byte[] signatureBytes = hmac.ComputeHash(Encoding.ASCII.GetBytes(content.ToString()));

                string signature = System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(signatureBytes));

                content.Append("&HMACSHA256=").Append(signature);
            }

            return content.ToString();
        }
Beispiel #23
0
 public static byte[] HMACSHA256(byte[] key, byte[] data)
 {
     using (var hmac = new HMACSHA256(key))
     {
         return hmac.ComputeHash(data);
     }
 }
		protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			string requestContentBase64String = string.Empty;
			string requestUri = System.Web.HttpUtility.UrlEncode(request.RequestUri.AbsoluteUri.ToLower());

			//Checking if the request contains body, usually will be null wiht HTTP GET
			if (request.Content != null)
			{
				using (var md5 = MD5.Create())
				{
					var content = await request.Content.ReadAsByteArrayAsync();
				
					//Hashing the request body, any change in request body will result in different hash, we'll incure message integrity
					var requestContentHash = md5.ComputeHash(content);
					requestContentBase64String = Convert.ToBase64String(requestContentHash);
				}
			}

			//create random nonce for each request
			var nonce = Guid.NewGuid().ToString("N");

			//Creating the raw signature string
			var signatureRawData = string.Concat(_apiKey, "POST", requestUri, nonce, requestContentBase64String);	
			var secretKeyByteArray = Convert.FromBase64String(_apiSecret);
			var signature = Encoding.UTF8.GetBytes(signatureRawData);
			using (var hmac = new HMACSHA256(secretKeyByteArray))
			{
				var signatureBytes = hmac.ComputeHash(signature);
				var requestSignatureBase64String = Convert.ToBase64String(signatureBytes);

				//Setting the values in the Authorization header using custom scheme (amx)
				request.Headers.Authorization = new AuthenticationHeaderValue("amx", string.Format("{0}:{1}:{2}", _apiKey, requestSignatureBase64String, nonce));
			}
			return await base.SendAsync(request, cancellationToken);
		}
Beispiel #25
0
 // Decrypt the encoded file and compare to original file.
 public static bool DecodeFile(byte[] key, String sourceFile)
 {
     // Initialize the keyed hash object.
     HMACSHA256 hmacsha256 = new HMACSHA256(key);
     // Create an array to hold the keyed hash value read from the file.
     byte[] storedHash = new byte[hmacsha256.HashSize / 8];
     // Create a FileStream for the source file.
     FileStream inStream = new FileStream(sourceFile, FileMode.Open);
     // Read in the storedHash.
     inStream.Read(storedHash, 0, storedHash.Length);
     // Compute the hash of the remaining contents of the file.
     // The stream is properly positioned at the beginning of the content,
     // immediately after the stored hash value.
     byte[] computedHash = hmacsha256.ComputeHash(inStream);
     // compare the computed hash with the stored value
     for (int i = 0; i < storedHash.Length; i++)
     {
         if (computedHash[i] != storedHash[i])
         {
             Console.WriteLine("Hash values differ! Encoded file has been tampered with!");
             return false;
         }
     }
     Console.WriteLine("Hash values agree -- no tampering occurred.");
     return true;
 }
        public static string GenerateHMACSHA256AuthorisationToken(string sessionToken, string sharedSecret, out string dateString)
        {
            if (String.IsNullOrWhiteSpace(sharedSecret))
            {
                throw new ArgumentNullException("sharedSecret");
            }

            if (String.IsNullOrWhiteSpace(sessionToken))
            {
                throw new ArgumentNullException("sessionToken");
            }

            // Generate UTC ISO 8601 date string.
            dateString = DateTime.UtcNow.ToString("o");
            // 1. Combine the Token and current date time in UTC using ISO 8601 format.
            byte[] messageBytes = Encoding.ASCII.GetBytes(sessionToken + ":" + dateString);
            // 2. Calculate the HMAC SHA 256 using the Consumer Secret and then Base64 encode.
            byte[] keyBytes = Encoding.ASCII.GetBytes(sharedSecret);
            string hmacsha256EncodedString;

            using (HMACSHA256 hmacsha256 = new HMACSHA256(keyBytes))
            {
                byte[] hashMessage = hmacsha256.ComputeHash(messageBytes);
                hmacsha256EncodedString = Convert.ToBase64String(hashMessage);
            }

            // 3. Combine the Token with the resulting string from above separated by a colon.
            string combinedMessage = sessionToken + ":" + hmacsha256EncodedString;
            // 4. Base64 encode this string.
            string base64EncodedString = Convert.ToBase64String(Encoding.ASCII.GetBytes(combinedMessage));

            // 5. Prefix this string with the Authentication Method and a space.
            return AuthorisationMethod.HMACSHA256.ToString() + " " + base64EncodedString;
        }
Beispiel #27
0
        public CyanAccount(string accountName, string accountSecret)
        {
            Name = accountName;

            var key = Convert.FromBase64String(accountSecret);
            signatureHasher = new HMACSHA256(key);
        }
    public static string GetAuthorizationHeader(string macKeyIdentifier, string macKey, string macAlgorithm, string method, Uri uri)
    {
      TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
      string timestamp = ((int)t.TotalSeconds).ToString();

      string nonce = new Random().Next().ToString();

      string normalizedString = string.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n\n", timestamp, nonce, method, uri.PathAndQuery, uri.Host, uri.Port);

      HashAlgorithm hashGenerator = null;

      if (macAlgorithm == "hmac-sha-256")
      {
        hashGenerator = new HMACSHA256(Encoding.ASCII.GetBytes(macKey));
      }
      else if (macAlgorithm == "hmac-sha-1")
      {
        hashGenerator = new HMACSHA1(Encoding.ASCII.GetBytes(macKey));
      }
      else
      {
        throw new InvalidOperationException("Unsupported MAC algorithm");
      }

      string hash = System.Convert.ToBase64String(hashGenerator.ComputeHash(Encoding.ASCII.GetBytes(normalizedString)));

      StringBuilder authorizationHeader = new StringBuilder();
      authorizationHeader.AppendFormat(@"id=""{0}"",ts=""{1}"",nonce=""{2}"",mac=""{3}""", macKeyIdentifier, timestamp, nonce, hash);

      return authorizationHeader.ToString();
    }
Beispiel #29
0
        private string ComputePayloadSig(string secret, string payload)
        {
            // from : https://github.com/laktak/discourse-sso/blob/master/src/Handler.cs
            var hash = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secret)).ComputeHash(Encoding.UTF8.GetBytes(payload));

            return(string.Join("", hash.Select(b => String.Format("{0:x2}", b))));
        }
        public Tuple <string, string> GetSignedToken(string nounce)
        {
            System.Security.Cryptography.HMACSHA256 hmac = new System.Security.Cryptography.HMACSHA256(UTF8Encoding.UTF8.GetBytes(MasterKey));
            string hash = BitConverter.ToString(hmac.ComputeHash(UTF8Encoding.UTF8.GetBytes(nounce))).Replace("-", "");

            return(new Tuple <string, string>(hash.Left(6), hash.Substring(6)));
        }
        public static FacebookSignedRequestResult Verify(string appSecret, string signedRequest)
        {
            var hmacsha256 = new HMACSHA256(Encoding.UTF8.GetBytes(appSecret));
            var javaScriptSerializer = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(signedRequest) || !signedRequest.Contains("."))
            {
                return new FacebookSignedRequestResult(false, string.Empty, string.Empty, null, null);
            }

            var split = signedRequest.Split('.');
            var providedPayloadHash = split[0];
            var requestPayload = split[1];

            byte[] hashBytes = hmacsha256.ComputeHash(Encoding.UTF8.GetBytes(requestPayload));
            string calculatedHash = Convert.ToBase64String(hashBytes);
            string modifiedBase64Hash = ConvertToModifiedBase64(calculatedHash);

            string payloadBase64 = ConvertFromModifiedBase64(requestPayload);
            byte[] payloadBytes = Convert.FromBase64String(payloadBase64);
            string payloadJson = Encoding.UTF8.GetString(payloadBytes);

            var request = javaScriptSerializer.Deserialize<FacebookSignedRequest>(payloadJson);

            return new FacebookSignedRequestResult(providedPayloadHash == modifiedBase64Hash, request.user_id, request.app_data, request.page, request.user);
        }
Beispiel #32
0
 // Computes a keyed hash for a source file, creates a target file with the keyed hash
 // prepended to the contents of the source file, then decrypts the file and compares
 // the source and the decrypted files.
 public static void EncodeFile(byte[] key, String sourceFile, String destFile)
 {
     // Initialize the keyed hash object.
     HMACSHA256 myhmacsha256 = new HMACSHA256(key);
     FileStream inStream = new FileStream(sourceFile, FileMode.Open);
     FileStream outStream = new FileStream(destFile, FileMode.Create);
     // Compute the hash of the input file.
     byte[] hashValue = myhmacsha256.ComputeHash(inStream);
     // Reset inStream to the beginning of the file.
     inStream.Position = 0;
     // Write the computed hash value to the output file.
     outStream.Write(hashValue, 0, hashValue.Length);
     // Copy the contents of the sourceFile to the destFile.
     int bytesRead;
     // read 1K at a time
     byte[] buffer = new byte[1024];
     do
     {
         // Read from the wrapping CryptoStream.
         bytesRead = inStream.Read(buffer, 0, 1024);
         outStream.Write(buffer, 0, bytesRead);
     } while (bytesRead > 0);
     myhmacsha256.Clear();
     // Close the streams
     inStream.Close();
     outStream.Close();
     return;
 }
Beispiel #33
0
        /// <summary>
        /// The function can be used to generate a hashed version of a user-provided password
        /// to store in a database for authentication purposes.
        /// </summary>
        /// <param name="password">The secret password to generate the key from.</param>
        /// <param name="salt">A (byte) string to use for better protection from dictionary attacks.</param>
        /// <param name="dklen">The cumulative length of the keys to produce.</param>
        /// <param name="count">Iteration count.</param>
        /// <returns>A byte string of length dklen that can be used as key material.</returns>
        /// <seealso cref="https://stackoverflow.com/questions/18648084/rfc2898-pbkdf2-with-sha256-as-digest-in-c-sharp"/>
        /// <seealso cref="https://pycryptodome.readthedocs.io/en/latest/src/protocol/kdf.html"/>
        static byte[] PBKDF2_SHA256_GetBytes(byte[] password, byte[] salt, int dklen, int count)
        {
            // NOTE: The iteration count should be as high as possible without causing
            // unreasonable delay. Note also that the password and salt are byte arrays, not strings.
            // After use, the password and salt should be cleared (with Array.Clear)

            using (var hmac = new System.Security.Cryptography.HMACSHA256(password))
            {
                int hashLength = hmac.HashSize / 8;
                if ((hmac.HashSize & 7) != 0)
                {
                    hashLength++;
                }
                int keyLength = dklen / hashLength;
                if ((long)dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
                {
                    throw new ArgumentOutOfRangeException("dklen");
                }
                if (dklen % hashLength != 0)
                {
                    keyLength++;
                }
                byte[] extendedkey = new byte[salt.Length + 4];
                Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
                using (var ms = new System.IO.MemoryStream())
                {
                    for (int i = 0; i < keyLength; i++)
                    {
                        extendedkey[salt.Length]     = (byte)(((i + 1) >> 24) & 0xFF);
                        extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                        extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                        extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                        byte[] u = hmac.ComputeHash(extendedkey);
                        Array.Clear(extendedkey, salt.Length, 4);
                        byte[] f = u;
                        for (int j = 1; j < count; j++)
                        {
                            u = hmac.ComputeHash(u);
                            for (int k = 0; k < f.Length; k++)
                            {
                                f[k] ^= u[k];
                            }
                        }
                        ms.Write(f, 0, f.Length);
                        Array.Clear(u, 0, u.Length);
                        Array.Clear(f, 0, f.Length);
                    }
                    byte[] dk = new byte[dklen];
                    ms.Position = 0;
                    ms.Read(dk, 0, dklen);
                    ms.Position = 0;
                    for (long i = 0; i < ms.Length; i++)
                    {
                        ms.WriteByte(0);
                    }
                    Array.Clear(extendedkey, 0, extendedkey.Length);
                    return(dk);
                }
            }
        }
Beispiel #34
0
 static JsonWebToken()
 {
     HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
                      {
                          {JwtHashAlgorithm.RS256, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA256(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          },
                          {JwtHashAlgorithm.HS384, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA384(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          },
                          {JwtHashAlgorithm.HS512, (key, value) =>
                                                   {
                                                       using (var sha = new HMACSHA512(key))
                                                       {
                                                           return sha.ComputeHash(value);
                                                       }
                                                   }
                          }
                      };
 }
Beispiel #35
0
        public static string AuthorizationHeader(
            string storageAccount, 
            string storageKey, 
            string method, 
            DateTime now,
            HttpRequestMessage request, 
            string ifMatch = "", 
            string contentMD5 = "", 
            string size = "", 
            string contentType = "")
        {
            string stringToSign = string.Format(
                "{0}\n\n\n{1}\n{5}\n{6}\n\n\n{2}\n\n\n\n{3}{4}", 
                method, 
                (size == string.Empty) ? string.Empty : size, 
                ifMatch, 
                GetCanonicalizedHeaders(request), 
                GetCanonicalizedResource(request.RequestUri, storageAccount), 
                contentMD5, 
                contentType);

            byte[] signatureBytes = Encoding.UTF8.GetBytes(stringToSign);
            string authorizationHeader;
            using (HMACSHA256 hmacsha256 = new HMACSHA256(Convert.FromBase64String(storageKey)))
            {
                authorizationHeader = "SharedKey " + storageAccount + ":"
                                      + Convert.ToBase64String(hmacsha256.ComputeHash(signatureBytes));
            }

            return authorizationHeader;
        }
Beispiel #36
0
        public static byte[] Protect(byte[] encryptionKey, byte[] validationKey, byte[] initializationVector, byte[] plainText)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                using (ICryptoTransform transform = provider.CreateEncryptor(encryptionKey, initializationVector))
                {
                    using (var ms = new MemoryStream())
                    {
                        ms.Write(initializationVector, 0, initializationVector.Length);
                        using (var cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write))
                        {
                            // Encrypted payload
                            cryptoStream.Write(plainText, 0, plainText.Length);
                            cryptoStream.FlushFinalBlock();

                            // Compute signature
                            using (var sha = new HMACSHA256(validationKey))
                            {
                                checked
                                {
                                    byte[] signature = sha.ComputeHash(ms.GetBuffer(), 0, (int)ms.Length);

                                    // Write the signature to the paylod
                                    ms.Write(signature, 0, signature.Length);

                                    // Final bytes
                                    return ms.ToArray();
                                }
                            }
                        }
                    }
                }
            }
        }
Beispiel #37
0
        /// <summary>
        /// Encrypt a message using AES in CBC (cipher-block chaining) mode.
        /// </summary>
        /// <param name="plaintext">The message (plaintext) to encrypt</param>
        /// <param name="key">An AES key</param>
        /// <param name="iv">The IV to use or null to use a 0 IV</param>
        /// <param name="addHmac">When set, a SHA256-based HMAC (HMAC256) of 32 bytes using the same key is added to the plaintext
        /// before it is encrypted.</param>
        /// <returns>The ciphertext derived by encrypting the orignal message using AES in CBC mode</returns>
        public static byte[] EncryptAesCbc(byte[] plaintext, byte[] key, byte[] iv = null, bool addHmac = false)
        {
            using (Aes aes =Aes.Create())
//            using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider())
            {
                aes.Key = key;
                if (iv == null)
                    iv = NullIv;
                aes.Mode = CipherMode.CBC;
                aes.IV = iv;

                // Encrypt the message with the key using CBC and InitializationVector=0
                byte[] cipherText;
                using (System.IO.MemoryStream ciphertext = new System.IO.MemoryStream())
                {
                    using (CryptoStream cs = new CryptoStream(ciphertext, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        cs.Write(plaintext, 0, plaintext.Length);
                        if (addHmac)
                        {
                            byte[] hmac = new HMACSHA256(key).ComputeHash(plaintext);
                            cs.Write(hmac, 0, hmac.Length);
                        }
                        cs.Flush();
                    }
                    cipherText = ciphertext.ToArray();
                }

                return cipherText;
            }
        }
        /// <summary>
        /// C# version of the Objective-C algorithm found in Firefox Home.
        /// </summary>
        /// <param name="key"></param>
        /// <param name="info"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static byte[] HDKFSHA256ExpandWithInfo(this byte[] key, byte[] info, int length)
        {
            int iterations = (length + SHA256_DIGEST_LENGTH - 1) / SHA256_DIGEST_LENGTH;

            byte[] tr = new byte[iterations * SHA256_DIGEST_LENGTH];

            byte[] tn = new byte[0];
            byte[] tnSha = new byte[0];
            int lengthCopied = 0;

            using (HMACSHA256 hmacSha256 = new HMACSHA256(key))
            {
                for (int i = 0; i < iterations; i++)
                {
                    tn = new byte[tnSha.Length + info.Length + 1];
                    Array.Copy(tnSha, 0, tn, 0, tnSha.Length);
                    Array.Copy(info, 0, tn, tnSha.Length, info.Length);
                    tn[tnSha.Length + info.Length] = (byte) (i + 1);
                    tnSha = hmacSha256.ComputeHash(tn);

                    Array.Copy(tnSha, 0, tr, lengthCopied, tnSha.Length);
                    lengthCopied += tnSha.Length;
                }
            }

            byte[] result = new byte[length];
            Array.Copy(tr, result, length);
            return result;
        }
        protected void TestButton_Click(object sender, EventArgs e)
        {
            // Define key and data string.
            var k  = "test key";
            var s  = "Encoding-编码-암호화-表現形式";
            var kb = System.Text.Encoding.UTF8.GetBytes(k);
            var sb = System.Text.Encoding.UTF8.GetBytes(s);

            // Test SHA256.
            WriteLog("// Create SHA256 Algorithm");
            var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider();
            var hash   = System.BitConverter.ToString(sha256.ComputeHash(sb));

            WriteLog("sha256.ComputeHash('" + s + "') = " + hash);

            //WriteLog("// Create SHA256 Algorithm");
            //var sha2 = new SHA256Managed();
            //hash = System.BitConverter.ToString(sha2.ComputeHash(sb));
            //WriteLog("sha2.ComputeHash('" + s + "') = " + hash);
            //WriteLog(sha2.Log.ToString());

            // Test HMACSHA256.
            Trace.Write("// Create HMAC-SHA256 Algorithm");
            var hmac = new System.Security.Cryptography.HMACSHA256(kb);

            hash = System.BitConverter.ToString(hmac.ComputeHash(sb));
            WriteLog("hmac.ComputeHash('" + k + "','" + s + "') = " + hash);
        }
Beispiel #40
0
 /// <summary>
 /// Computes the <see cref="HMACSHA256"/> hash of the string using the given
 /// salt and <c cref="Encoding.UTF8">UTF8 Encoding</c>
 /// </summary>
 /// <param name="plainText"></param>
 /// <param name="salt"></param>
 /// <returns></returns>
 public static byte[] ComputeHash(this string plainText, string salt)
 {
     var encoding = Encoding.UTF8;
     using (var sha = new HMACSHA256(Encoding.UTF8.GetBytes(salt))) {
         return sha.ComputeHash(encoding.GetBytes(plainText));
     }
 }
Beispiel #41
0
 /// <summary>
 ///  Generates the private key for a specific domain, based on the master key. 
 /// </summary>
 /// <returns>
 ///  The private key. 
 /// </returns>
 /// <param name='masterKey'>
 ///  The master key. 
 /// </param>
 /// <param name='domain'>
 ///  The domain. 
 /// </param>
 public byte[] GeneratePrivateKey(byte[] masterKey, string domain)
 {
     using(HMACSHA256 hmac = new HMACSHA256(masterKey))
     {
         return hmac.ComputeHash(Encoding.UTF8.GetBytes(domain));
     }
 }
Beispiel #42
0
 private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256())
     {
         passwordSalt = hmac.Key;
         passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
     }
 }
Beispiel #43
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="header"></param>
 /// <param name="payload"></param>
 /// <param name="secret"></param>
 /// <returns></returns>
 private static byte[] HS256(string header, string payload, string secret)
 {
     using (var hasher = new System.Security.Cryptography.HMACSHA256(Encoding.UTF8.GetBytes(secret)))
     {
         var bytes = Encoding.UTF8.GetBytes(string.Format("{0}.{1}", header, payload));
         return(hasher.ComputeHash(bytes));
     }
 }
        /// <summary>
        /// Computes the "Hi()"-formula which is part of the client's response
        /// to the server challenge.
        /// </summary>
        /// <param name="password">The supplied password to use.</param>
        /// <param name="salt">The salt received from the server.</param>
        /// <param name="count">The iteration count.</param>
        /// <returns>An array of bytes containing the result of the
        /// computation of the "Hi()"-formula.</returns>
        /// <remarks>Hi is, essentially, PBKDF2 with HMAC as the
        /// pseudorandom function (PRF) and with dkLen == output length of
        /// HMAC() == output length of H(). (Refer to RFC 5802, p.6)</remarks>
        private byte[] Hi(string password, string salt, int count)
        {
            byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
            // The salt is sent by the server as a base64-encoded string.
            byte[] saltBytes = Convert.FromBase64String(salt);
            HMAC   hmac      = new System.Security.Cryptography.HMACSHA256(passwordBytes);

            return(PBKDF2(32, passwordBytes, saltBytes, count, hmac));
        }
 private byte[] PBKDF2Sha256GetBytes(int dklen, byte[] password, byte[] salt, int iterationCount)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256(password))
     {
         int hashLength = hmac.HashSize / 8;
         if ((hmac.HashSize & 7) != 0)
         {
             hashLength++;
         }
         int keyLength = dklen / hashLength;
         if ((long)dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
         {
             throw new ArgumentOutOfRangeException("dklen");
         }
         if (dklen % hashLength != 0)
         {
             keyLength++;
         }
         byte[] extendedkey = new byte[salt.Length + 4];
         Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
         using (var ms = new System.IO.MemoryStream())
         {
             for (int i = 0; i < keyLength; i++)
             {
                 extendedkey[salt.Length]     = (byte)(((i + 1) >> 24) & 0xFF);
                 extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                 extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                 extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                 byte[] u = hmac.ComputeHash(extendedkey);
                 Array.Clear(extendedkey, salt.Length, 4);
                 byte[] f = u;
                 for (int j = 1; j < iterationCount; j++)
                 {
                     u = hmac.ComputeHash(u);
                     for (int k = 0; k < f.Length; k++)
                     {
                         f[k] ^= u[k];
                     }
                 }
                 ms.Write(f, 0, f.Length);
                 Array.Clear(u, 0, u.Length);
                 Array.Clear(f, 0, f.Length);
             }
             byte[] dk = new byte[dklen];
             ms.Position = 0;
             ms.Read(dk, 0, dklen);
             ms.Position = 0;
             for (long i = 0; i < ms.Length; i++)
             {
                 ms.WriteByte(0);
             }
             Array.Clear(extendedkey, 0, extendedkey.Length);
             return(dk);
         }
     }
 }
Beispiel #46
0
        string HmacSha256Digest(string message, string secret)
        {
            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] keyBytes     = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(message);
            System.Security.Cryptography.HMACSHA256 cryptographer = new System.Security.Cryptography.HMACSHA256(keyBytes);
            byte[] bytes = cryptographer.ComputeHash(messageBytes);
            return(BitConverter.ToString(bytes).Replace("-", "").ToLower());
        }
Beispiel #47
0
 public static string GetHMACSHA256Base64String(string str, string keyStr)
 {
     byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);
     byte[] key   = System.Text.Encoding.ASCII.GetBytes(keyStr);
     using (System.Security.Cryptography.HMACSHA256 hmacsha256 = new System.Security.Cryptography.HMACSHA256(key))
     {
         byte[] s = hmacsha256.ComputeHash(bytes);
         return(Convert.ToBase64String(s));
     }
 }
    private static string CreateHmac(string secret, string data)
    {
        var myEncoder   = new System.Text.UTF8Encoding();
        var secretBytes = myEncoder.GetBytes(secret);
        var dataBytes   = myEncoder.GetBytes(data);
        var myHMACSHA1  = new System.Security.Cryptography.HMACSHA256(secretBytes);
        var HashCode    = myHMACSHA1.ComputeHash(dataBytes);
        var hash        = BitConverter.ToString(HashCode).Replace("-", "");

        return(hash.ToLower());
    }
        string GenerateHash(string text, string key)
        {
            var encoding  = new ASCIIEncoding();
            var textBytes = encoding.GetBytes(text);
            var keyBytes  = encoding.GetBytes(key);

            byte[] hasBytes;
            using var hash = new System.Security.Cryptography.HMACSHA256(keyBytes);
            hasBytes       = hash.ComputeHash(textBytes);
            return(BitConverter.ToString(hasBytes).Replace("-", "").ToLower());
        }
        public static string CreateToken(string string_to_sign, string secret)
        {
            secret = secret ?? "";
            var encoding = new System.Text.ASCIIEncoding();

            byte[] keyByte      = encoding.GetBytes(secret);
            byte[] messageBytes = encoding.GetBytes(string_to_sign);
            using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyByte))
            {
                byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                return(string.Join("", Array.ConvertAll(hashmessage, b => b.ToString("x2"))));
            }
        }
 public static string HACSHA(byte[] key, byte[] data, long pos, int length)
 {
     using (var shaAlgorithm = new System.Security.Cryptography.HMACSHA256(key))
     {
         byte[] realData = new byte[length];
         for (int i = 0; i < length; i++)
         {
             realData[i] = data[pos + i];
         }
         var signatureHashBytes = shaAlgorithm.ComputeHash(realData);
         var signatureHashHex   = string.Concat(Array.ConvertAll(signatureHashBytes, b => b.ToString("X2"))).ToLower();
         return(signatureHashHex);
     }
 }
Beispiel #52
0
        /// <summary>
        /// 雜湊
        /// </summary>
        /// <param name="message">訊息</param>
        /// <param name="key">秘密金鑰</param>
        /// <returns></returns>
        public string Hash(string message, string key)
        {
            // UTF8 not emit BOM, https://docs.microsoft.com/zh-tw/dotnet/api/system.text.utf8encoding?view=netcore-3.1
            UTF8Encoding utf8 = new UTF8Encoding();

            byte[] messageBytes = utf8.GetBytes(message);
            byte[] keyBytes     = utf8.GetBytes(key);

            using (Cryptography.HMACSHA256 hmacsha256 = new Cryptography.HMACSHA256(keyBytes))
            {
                byte[] hashedBytes = hmacsha256.ComputeHash(messageBytes);
                return(BitConverter.ToString(hashedBytes).Replace("-", string.Empty).ToLower());
            }
        }
Beispiel #53
0
        private bool VerityPasswordHash(string password, string passwordHash, string salt)
        {
            byte[] saltByte = Convert.FromBase64String(salt);

            using (var hmac = new System.Security.Cryptography.HMACSHA256(saltByte))
            {
                var ComputedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(password));

                if (Convert.ToBase64String(ComputedHash) != passwordHash)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #54
0
 private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
 {
     using (var hmac = new System.Security.Cryptography.HMACSHA256(passwordSalt))
     {
         var computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
         for (int i = 0; i < computedHash.Length; i++)
         {
             if (computedHash[i] != passwordHash[i])
             {
                 return(false);
             }
         }
         return(true);
     }
 }
Beispiel #55
0
    private string sha256(string planeStr, string key)
    {
        System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
        byte[] planeBytes           = ue.GetBytes(planeStr);
        byte[] keyBytes             = ue.GetBytes(key);
        System.Security.Cryptography.HMACSHA256 sha256 = new System.Security.Cryptography.HMACSHA256(keyBytes);
        byte[] hashBytes = sha256.ComputeHash(planeBytes);
        string hashStr   = "";

        foreach (byte b in hashBytes)
        {
            hashStr += string.Format("{0,0:x2}", b);
        }
        return(hashStr);
    }
Beispiel #56
0
        public static string HMACSHA256(string input, string key)
        {
            var keyBytes = System.Text.Encoding.ASCII.GetBytes(key);

            using (var alg = new System.Security.Cryptography.HMACSHA256(keyBytes)) {
                byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
                byte[] hash       = alg.ComputeHash(inputBytes);

                var sb = new System.Text.StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("x2"));
                }
                return(sb.ToString().ToLower());
            }
        }
Beispiel #57
0
    public static bool IsValidPassword(string password, string base64)
    {
        // ----------------------------------------------------------------
        if (string.IsNullOrEmpty(password))
        {
            return(false);
        }
        if (string.IsNullOrEmpty(base64))
        {
            return(false);
        }
        // Try parse salt and hash from base64.
        byte[] baseBytes;
        try { baseBytes = System.Convert.FromBase64String(base64); }
        catch { return(false); }
        // Get size of salt and hash.
        var size = baseBytes.Length / 2;
        var salt = new byte[size];
        var hash = new byte[size];

        Array.Copy(baseBytes, 0, salt, 0, size);
        Array.Copy(baseBytes, size, hash, 0, size);
        Console.WriteLine("IsValidPassword:"******"  Salt: {0}", string.Join("", salt.Select(x => x.ToString("X2"))));
        Console.WriteLine("  Hash: {0}", string.Join("", hash.Take(size).Select(x => x.ToString("X2"))));
        // ----------------------------------------------------------------
        // Convert string to bytes.
        // Use Unicode, because ASCII doesn't work worldwide and SQL server doesn't support UTF8.
        var passwordBytes = System.Text.Encoding.Unicode.GetBytes(password);
        var algorithm     = new System.Security.Cryptography.HMACSHA256();

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

        // Compare first specified bytes.
        for (int i = 0; i < size; i++)
        {
            if (passwordHash[i] != hash[i])
            {
                // Password hash bytes do not match.
                return(false);
            }
        }
        // Password hash bytes match.
        return(true);
    }
        public static string HmacSha256(string plain)
        {
            string secretKey  = "eastmoney88";
            var    keyBytes   = Encoding.UTF8.GetBytes(secretKey);
            var    plainBytes = Encoding.UTF8.GetBytes(plain);

            using (var hmacsha256 = new System.Security.Cryptography.HMACSHA256(keyBytes))
            {
                var sb        = new StringBuilder();
                var hashValue = hmacsha256.ComputeHash(plainBytes);
                foreach (byte x in hashValue)
                {
                    sb.Append($"{x:x2}");
                }
                return(sb.ToString());
            }
        }
Beispiel #59
0
        public Ping handlePing(byte[] body, string signature, Options opts = null)
        {
            var binApikey = Encoding.UTF8.GetBytes(apikey);
            var hasher    = new System.Security.Cryptography.HMACSHA256(binApikey);
            var binDigest = hasher.ComputeHash(body);
            var digest    = Convert.ToBase64String(binDigest);

            if (!constTimeEquals(digest, signature))
            {
                throw new Exception("invalid ping signature");
            }
            using (var ms = new MemoryStream(body))
                using (var sr = new StreamReader(ms))
                    using (var jtr = new JsonTextReader(sr))
                    {
                        return(JsonSerializer.Create().Deserialize <Ping>(jtr));
                    }
        }
Beispiel #60
0
    // Part of article: https://github.com/JocysCom/ShellScripts/wiki/HMAC-for-SQL

    public static int ProcessArguments(string[] args)
    {
        // Use Unicode, because ASCII doesn't work worldwide.
        var base64  = HashPassword("Password", 128);
        var isValid = IsValidPassword("Password", base64);

        Console.WriteLine("Results:");
        Console.WriteLine("  IsValid: {0}, base64: {1}", isValid, base64);
        Console.WriteLine();
        Console.WriteLine("-------");
        var key       = StringToByteArray("0x63727970746969");
        var data      = StringToByteArray("0x68656C6C6F21");
        var algorithm = new System.Security.Cryptography.HMACSHA256();

        algorithm.Key = key;
        var hash = algorithm.ComputeHash(data);

        Console.WriteLine("  Hash: {0}", string.Join("", hash.Select(x => x.ToString("X2"))));
        return(0);
    }