static string calcHmac( string data )
 {
     byte[] key = Encoding.ASCII.GetBytes(AUTH_TOKEN);
     HMACSHA256 myhmacsha256 = new HMACSHA256(key);
     byte[] byteArray = Encoding.ASCII.GetBytes(data);
     MemoryStream stream = new MemoryStream(byteArray);
     string result = myhmacsha256.ComputeHash(stream).Aggregate("", (s, e) => s + String.Format("{0:x2}",e), s => s );
     Console.WriteLine(result);
     return result;
 }
Beispiel #2
7
        static void Main()
        {
            var data = "testtesttest";
            var secretKey = "secretkey";

            // Initialize the keyed hash object using the secret key as the key
            HMACSHA256 hashObject = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));

            // Computes the signature by hashing the salt with the secret key as the key
            var signature = hashObject.ComputeHash(Encoding.UTF8.GetBytes(data));

            // Base 64 Encode
            var encodedSignature = Convert.ToBase64String(signature);

            // URLEncode
            // encodedSignature = System.Web.HttpUtility.UrlEncode(encodedSignature);

            Console.WriteLine("Voila! A signature: " + encodedSignature);

            Console.ReadKey();
        }
Beispiel #3
4
 public static string HMACSHA256Encode(string input, string key)
 {
     byte[] k = Encoding.ASCII.GetBytes (key);
     HMACSHA256 myhmacsha256 = new HMACSHA256 (k);
     byte[] byteArray = Encoding.ASCII.GetBytes (input);
     using (MemoryStream stream = new MemoryStream (byteArray)){
         return byteToHex(myhmacsha256.ComputeHash (stream));
     }
 }
Beispiel #4
4
    string container = "ogp"; //Storage container created on azure portal called "test"

    #endregion Fields

    #region Methods

    private static String SignThis(String StringToSign, string Key, string Account)
    {
        String signature = string.Empty;
        byte[] unicodeKey = Convert.FromBase64String(Key);
        using (HMACSHA256 hmacSha256 = new HMACSHA256(unicodeKey))
        {
            Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
            signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
        }

        String authorizationHeader = String.Format(
            CultureInfo.InvariantCulture,
            "{0} {1}:{2}",
            "SharedKeyLite",
            Account,
            signature);

        return authorizationHeader;
    }
 public static string getHashSha256(string text, string mail)
 {
     byte[] key = Encoding.UTF8.GetBytes(mail);
     byte[] bytes = Encoding.UTF8.GetBytes(text);
     HMACSHA256 hashstring = new HMACSHA256(key);
     byte[] hash = hashstring.ComputeHash(bytes);
     string hashString = string.Empty;
     foreach (byte x in hash)
     {
         hashString += String.Format("{0:x2}", x);
     }
     return hashString;
 }
Beispiel #6
1
    public Crypto(Guid sessionId, byte[] cipherKey, byte[] cipherNonce, byte[] macKey)
    {
        if (cipherKey.Length != 16) {
            throw new System.ArgumentException("Chipher Key must be 16 bytes");
        }

        if (cipherNonce.Length != 8) {
            throw new System.ArgumentException("Chipher Nonce must be 8 bytes");
        }

        if (macKey.Length != 32) {
            throw new System.ArgumentException("Mac Key must be 32 bytes");
        }

        _sequence = 0;
        _sessionId = TransposeGuidBytes(sessionId.ToByteArray());
        _cipherKey = cipherKey;
        _cipherNonce = cipherNonce;
        _cipherCounter = new byte[_cipherNonce.Length + sizeof(uint) + sizeof(uint)];
        _macKey = macKey;

        if (_sessionId.Length != 16) {
            throw new System.ArgumentException("Session ID must be 16 bytes");
        }

        if (_cipherCounter.Length != 16) {
            throw new System.ArgumentException("Chipher Counter must be 16 bytes");
        }

        // aes-128-ecb
        Aes aes = Aes.Create();
        aes.Mode = CipherMode.ECB;
        aes.Key = _cipherKey;
        _cryptoAlgorithm = aes.CreateEncryptor();

        _hashAlgorithm = new HMACSHA256(_macKey);
        _hashLength = _hashAlgorithm.HashSize / 8;
        _sharedSecret = new byte[_cipherKey.Length + _cipherNonce.Length + _macKey.Length];

        if (_hashLength != 32) {
            throw new System.ArgumentException("Hash must be 32 bytes");
        }

        if (_sharedSecret.Length != 56) {
            throw new System.ArgumentException("Shared Secret must be 56 bytes");
        }

        // copy _chipherKey to _sharedSecret
        Buffer.BlockCopy(_cipherKey, 0, _sharedSecret, 0, _cipherKey.Length);
        // copy _cipherNonce to _sharedSecret
        Buffer.BlockCopy(_cipherNonce, 0, _sharedSecret, _cipherKey.Length, cipherNonce.Length);
        // copy _macKey to _sharedSecret
        Buffer.BlockCopy(_macKey, 0, _sharedSecret, _cipherKey.Length + _cipherNonce.Length, _macKey.Length);
        // copy _cipherNonce to _cihperCounter
        Buffer.BlockCopy(_cipherNonce, 0, _cipherCounter, 0, _cipherNonce.Length);
    }
	static void Main(string[] args)
	{
		using (var rijndael = new RijndaelManaged())
		using (var hmacsha256 = new HMACSHA256())
		{
			rijndael.GenerateKey();
			hmacsha256.Initialize();
			Console.WriteLine(template, new SoapHexBinary(rijndael.Key), new SoapHexBinary(hmacsha256.Key));
		}

		Console.WriteLine("press any key to exit...");
		Console.ReadKey();
	}
    /// <summary> 
    /// Code  for generating of SAS token for authorization with Service Bus 
    /// </summary> 
    /// <param name="resourceUri"></param> 
    /// <param name="keyName"></param> 
    /// <param name="key"></param> 
    /// <returns></returns> 
    private static string createToken(string resourceUri, string keyName, string key)
    {
        TimeSpan sinceEpoch = DateTime.UtcNow - new DateTime(1970, 1, 1);
        var expiry = Convert.ToString((int)sinceEpoch.TotalSeconds + 3600); //EXPIRES in 1h
        string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));

        var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
        var sasToken = String.Format(CultureInfo.InvariantCulture,
        "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",
            HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);

        return sasToken;
    }
    // Use this for initialization
    void Start () {
        Rfc2898DeriveBytes PBKDF2_hash = new Rfc2898DeriveBytes("qwerty", Encoding.ASCII.GetBytes("rm4fSDh0sofK"), 20000);
        HMACSHA256 HMACSHA256_hash = new HMACSHA256();
        //System.Text.Encoding.UTF8.GetString(bytes);
        string hPassword = Convert.ToBase64String(PBKDF2_hash.GetBytes(32));
        Debug.Log("Hash = " + hPassword);
        //Debug.Log("Password hash" + Encoding.ASCII.GetString(PBKDF2.GetBytes(256)));
        //PBKDF2.Salt = 


        /*string password = "******";
        string hPassword = ComputeHash(password, new SHA256CryptoServiceProvider());
        Debug.Log("Hash from: " + password + " = " + hPassword);*/
    }
Beispiel #10
1
    public byte[] Decrypt(byte[] payload)
    {
        byte[] payloadToSign = _ByteSlice(payload, 0, payload.Length - _hashLength);
        byte[] serverHmac = _ByteSlice(payload, payload.Length - _hashLength, payload.Length);
        HMACSHA256 hashAlgorithm = new HMACSHA256(_macKey);
        byte[] clientHmac = hashAlgorithm.ComputeHash(payloadToSign);

        if (!ByteEqual(serverHmac, clientHmac)) {
            throw new System.ArgumentException("Bad Signature");
        }

        byte[] eBytes = _ByteSlice(payload, SEQ_LEN, payload.Length - _hashLength);
        byte[] dBytes = new byte[eBytes.Length];

        // seq is always 0 from server
        uint seq = 0;
        _Ctr(seq, eBytes, dBytes, 0);

        return dBytes;
    }
    /// <summary>
    /// Computes the Client Assertion portion of the JWT
    /// </summary>
    /// <param name="header">The JSON Web Token header</param>
    /// <param name="claimSet">The JSON Web Token claim set</param>
    /// <param name="clientSecret">The client's secret</param>
    /// <returns>The assertion</returns>
    public string BuildAssertion(JWTHeader header, JWTClaimSet claimSet, string clientSecret)
    {
        // Serialize the header and claimSet
        string serializedHeader = JsonConvert.SerializeObject(header);
        string serializedClaimSet = JsonConvert.SerializeObject(claimSet);

        // Base64Encode the header and claimSet
        string encodedHeader = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedHeader));
        string encodedClaimSet = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(serializedClaimSet));

        // Concatenate the header and the claims separated with a '.': [header].[claims]
        string message = string.Join(".", encodedHeader, encodedClaimSet);

        // Apply an HMAC/SHA-256 hash* to the concatenated content using the Client Secret as the key
        HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(clientSecret));
        byte[] hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));

        // Base64Encode the result of the hash
        string signature = Convert.ToBase64String(hash);

        // Combine the encoded elements as follows [header].[claims].[hash]
        string assertion = string.Join(".", encodedHeader, encodedClaimSet, signature);
        return assertion;
    }
Beispiel #12
1
    public byte[] Encrypt(byte[] payload)
    {
        _sequence++;
        byte[] seqBytes = BitConverter.GetBytes(IPAddress.NetworkToHostOrder((int)_sequence));
        byte[] cipherBytes = new byte[payload.Length];
        byte[] outpacket = new byte[cipherBytes.Length + SEQ_LEN + _hashLength];

        _Ctr(_sequence, payload, cipherBytes, 0);

        Buffer.BlockCopy(seqBytes, 0, outpacket, 0, SEQ_LEN);
        Buffer.BlockCopy(cipherBytes, 0, outpacket, SEQ_LEN, cipherBytes.Length);

        byte[] payloadToSign = _ByteSlice(outpacket, 0, outpacket.Length - _hashLength);
        HMACSHA256 hashAlgorithm = new HMACSHA256(_macKey);
        byte[] hmac = hashAlgorithm.ComputeHash(payloadToSign);

        Buffer.BlockCopy(hmac, 0, outpacket, outpacket.Length - _hashLength, _hashLength);

        byte[] epacket = new byte[_sessionId.Length + SEQ_LEN + outpacket.Length];

        Buffer.BlockCopy(_sessionId, 0, epacket, 0, _sessionId.Length);
        Buffer.BlockCopy(seqBytes, 0, epacket, _sessionId.Length, SEQ_LEN);
        Buffer.BlockCopy(outpacket, 0, epacket, _sessionId.Length + SEQ_LEN, outpacket.Length);

        return epacket;
    }
Beispiel #13
1
    public void init()
    {
        System.Net.ServicePointManager.DefaultConnectionLimit = 1000;
        secure = secret_key.Length > 0;
        subscriptions = new Hashtable();
        origin = (ssl?"https://":"http://") + origin;

        if(secure) {
            sha256 = new HMACSHA256( System.Text.Encoding.UTF8.GetBytes(secret_key) );
        }
        pubnub.init(this);
        initialized = true;
    }
    private SimpleWebToken CreateToken(ClaimCollection claims, string issuerName, string appliesTo)
    {
        appliesTo = appliesTo.ToLower();

        var sKey = ConfigurationManager.AppSettings[appliesTo];
        if (String.IsNullOrEmpty(sKey))
        {
            //check if appliesTo failed to find the key because it's missing a trailing slash,
            //or because it has a trailing slash which shouldn't be there
            //and act accordingly (and try again):
            if (!appliesTo.EndsWith("/"))
                appliesTo += "/";
            else
                appliesTo = VirtualPathUtility.RemoveTrailingSlash(appliesTo);

            sKey = ConfigurationManager.AppSettings[appliesTo];
            if (String.IsNullOrEmpty(sKey))
                throw new ConfigurationException(String.Format("Missing symmetric key for \"{0}\".", appliesTo));
        }
        var key = this.HexToByte(sKey);

        var sb = new StringBuilder();
        foreach (var c in claims)
            sb.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(c.ClaimType), HttpUtility.UrlEncode(c.Value));

        double lifeTimeInSeconds = 3600;
        sb
            .AppendFormat("TokenId={0}&", HttpUtility.UrlEncode(Guid.NewGuid().ToString()))
            .AppendFormat("Issuer={0}&", HttpUtility.UrlEncode(issuerName))
            .AppendFormat("Audience={0}&", HttpUtility.UrlEncode(appliesTo))
            .AppendFormat("ExpiresOn={0:0}", (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + lifeTimeInSeconds);

        var unsignedToken = sb.ToString();

        var hmac = new HMACSHA256(key);
        var sig = hmac.ComputeHash(Encoding.ASCII.GetBytes(unsignedToken));

        string signedToken = String.Format("{0}&HMACSHA256={1}",
            unsignedToken,
            HttpUtility.UrlEncode(Convert.ToBase64String(sig)));

        return new SimpleWebToken(signedToken);
    }
    /**
     * Computes RFC 2104-compliant HMAC signature for request parameters
     * Implements AWS Signature, as per following spec:
     *
     * If Signature Version is 2, string to sign is based on following:
     *
     *    1. The HTTP Request Method followed by an ASCII newline (%0A)
     *    2. The HTTP Host header in the form of lowercase host, followed by an ASCII newline.
     *    3. The URL encoded HTTP absolute path component of the URI
     *       (up to but not including the query string parameters);
     *       if this is empty use a forward '/'. This parameter is followed by an ASCII newline.
     *    4. The concatenation of all query string components (names and values)
     *       as UTF-8 characters which are URL encoded as per RFC 3986
     *       (hex characters MUST be uppercase), sorted using lexicographic byte ordering.
     *       Parameter names are separated from their values by the '=' character
     *       (ASCII character 61), even if the value is empty.
     *       Pairs of parameter and values are separated by the '&' character (ASCII code 38).
     *
     */
    private static String SignParameters(IDictionary<String, String> parameters, String key)
    {
        String signatureVersion = "2";

        KeyedHashAlgorithm algorithm = new HMACSHA256();

        String stringToSign = null;
        if ("2".Equals(signatureVersion))
        {
            String signatureMethod = "HmacSHA256";
            algorithm = KeyedHashAlgorithm.Create(signatureMethod.ToUpper());
            stringToSign = CalculateStringToSignV2(parameters);
        }
        else
        {
            throw new Exception("Invalid Signature Version specified");
        }

        return Sign(stringToSign, key, algorithm);
    }
    public string GetSignature(string secretAccessKey, string host = "ecs.amazonaws.jp", string path = "/onca/xml")
    {
        var queryStr = this.ToQueryString();
        var strToSign = string.Format("GET\n{0}\n{1}\n{2}", host, path, queryStr);
        var toSign = Encoding.UTF8.GetBytes(strToSign);

        var signer = new HMACSHA256(Encoding.UTF8.GetBytes(secretAccessKey));
        var sigBytes = signer.ComputeHash(toSign);
        var signature = CustomUrlEncode(Convert.ToBase64String(sigBytes));

        return signature;
    }
Beispiel #17
1
 /// <summary>
 /// Singature mapping which corresponds to php's 'hash_hmac'
 /// </summary>
 /// <param name="message"></param>
 /// <returns></returns>
 private string GetSignature(string message)
 {
     var secretKeyBytes = encoding.GetBytes(ApiSecret);
     //using the bytemap
     using (var hmacsha256 = new HMACSHA256(secretKeyBytes))
     {
         hmacsha256.ComputeHash(encoding.GetBytes(message));
         //Return the corresponding string for the signature request.
         return hmacsha256.Hash.Aggregate(string.Empty, (current, b) => current + b.ToString("X2")).ToLower();
     }
 }
Beispiel #18
1
 public static byte[] GetHmacSignatureInBytes(byte[] data, byte[] sharedSecret)
 {
     HMACSHA256 hash = new HMACSHA256();
     hash.Key = sharedSecret;
     byte[] hashedValue = hash.ComputeHash(data);
     return hashedValue;
 }
Beispiel #19
0
        public static byte[] Generate(byte[] password, byte[] salt, int iterationCount, int byteCount)
        {
            if (iterationCount <= 0)
            {
                throw new ArgumentOutOfRangeException("iterationCount", "Iteration count should be positive");
            }

            if (byteCount < 0)
            {
                throw new ArgumentOutOfRangeException("byteCount", "Byte count should be nonnegative");
            }

            using (var hmac = new HMACSHA256())
            {
                hmac.Key = password;

                // Prepare hash input (salt + block index)
                var hashInputSize = salt.Length + 4;
                var hashInput     = new byte[hashInputSize];
                salt.CopyTo(hashInput, 0);
                hashInput[hashInputSize - 4] = 0;
                hashInput[hashInputSize - 3] = 0;
                hashInput[hashInputSize - 2] = 0;
                hashInput[hashInputSize - 1] = 0;

                var bytes      = new byte[byteCount];
                var hashSize   = hmac.HashSize / 8;
                var blockCount = (byteCount + hashSize - 1) / hashSize;

                for (var i = 0; i < blockCount; ++i)
                {
                    // Increase 32-bit big-endian block index at the end of the hash input buffer
                    if (++hashInput[hashInputSize - 1] == 0)
                    {
                        if (++hashInput[hashInputSize - 2] == 0)
                        {
                            if (++hashInput[hashInputSize - 3] == 0)
                            {
                                ++hashInput[hashInputSize - 4];
                            }
                        }
                    }

                    var hashed = hmac.ComputeHash(hashInput);
                    var block  = hashed;
                    for (var j = 1; j < iterationCount; ++j)
                    {
                        hashed = hmac.ComputeHash(hashed);
                        for (var k = 0; k < hashed.Length; ++k)
                        {
                            block[k] ^= hashed[k];
                        }
                    }

                    var offset = i * hashSize;
                    var size   = Math.Min(hashSize, byteCount - offset);
                    Array.Copy(block, 0, bytes, offset, size);
                }

                return(bytes);
            }
        }
Beispiel #20
0
        private static byte[] HashHMAC(byte[] key, byte[] message)
        {
            var hash = new HMACSHA256(key);

            return(hash.ComputeHash(message));
        }
Beispiel #21
0
        private byte[] HashHMAC(byte[] decodedToken, byte[] secretKey)
        {
            var hash = new HMACSHA256(secretKey);

            return(hash.ComputeHash(decodedToken));
        }
        private static byte[] Sign(byte[] key, byte[] data)
        {
            HMACSHA256 sha256 = new HMACSHA256(data);

            return(sha256.ComputeHash(key));
        }
        public byte[] GenerateHmacHash(string input, string key)
        {
            var hmacsha256 = new HMACSHA256(utf8Converter.ConvertToBytes(key));

            return(hmacsha256.ComputeHash(utf8Converter.ConvertToBytes(input)));
        }
 static byte[] applyHMACwithSHA256(byte[] byteInput, byte[] key)
 {
     HMACSHA256 hmacSHA256 = new HMACSHA256(key);
     byte[] result = hmacSHA256.ComputeHash(byteInput);
     return result;
 }
Beispiel #25
0
 public static byte[] HashStringToBytes(string str_to_hash)
 {
     HMACSHA256 hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["UserSalt"]));
     return hs256.ComputeHash(StringToBytes(str_to_hash));
 }
Beispiel #26
0
        public void DeleteMultipleBlobs(List <string> blobs)
        {
            if (blobs.Count == 0)
            {
                return;
            }

            if (_hasSasToken)
            {
                // Multi-Delete isn't supported when using a SAS token
                // https://issues.hibernatingrhinos.com/issue/RavenDB-14936
                // https://github.com/Azure/azure-sdk-for-net/issues/11762
                DeleteBlobsWithSasToken(blobs);
                return;
            }

            const string xMsDate                  = "x-ms-date";
            const string xMsClientRequestId       = "x-ms-client-request-id";
            const string xMsReturnClientRequestId = "x-ms-return-client-request-id";

            var now = SystemTime.UtcNow.ToString("R");
            var url = GetUrl(_serverUrlForAccountName, "comp=batch");

            var requestMessage = new HttpRequestMessage(HttpMethods.Post, url)
            {
                Headers =
                {
                    { xMsDate, now }, { "x-ms-version", AzureStorageVersion }
                }
            };

            var batchContent = new MultipartContent("mixed", $"batch_{Guid.NewGuid()}");

            requestMessage.Content = batchContent;

            var blobsWithIds = new Dictionary <string, string>();

            for (var i = 0; i < blobs.Count; i++)
            {
                using var ms     = new MemoryStream();
                using var writer = new StreamWriter(ms);
                var clientRequestId = Guid.NewGuid().ToString();
                blobsWithIds[clientRequestId] = blobs[i];

                writer.WriteLine($"{HttpMethods.Delete} /{_containerName}/{blobs[i]} HTTP/1.1");
                writer.WriteLine($"{xMsDate}: {now}");
                writer.WriteLine($"{xMsClientRequestId}: {clientRequestId}");
                writer.WriteLine($"{xMsReturnClientRequestId}: true");

                using (var hash = new HMACSHA256(_accountKey))
                {
                    var uri     = new Uri($"{_serverUrlForContainer}/{blobs[i]}", UriKind.Absolute);
                    var hashStr =
                        $"{HttpMethods.Delete}\n\n\n\n\n\n\n\n\n\n\n\n{xMsClientRequestId}:{clientRequestId}\n{xMsDate}:{now}\n{xMsReturnClientRequestId}:true\n/{_accountName}{uri.AbsolutePath}";
                    writer.WriteLine($"Authorization: SharedKey {_accountName}:{Convert.ToBase64String(hash.ComputeHash(Encoding.UTF8.GetBytes(hashStr)))}");
                }

                writer.WriteLine("Content-Length: 0");
                writer.Flush();

                batchContent.Add(new ByteArrayContent(ms.ToArray())
                {
                    Headers =
                    {
                        { "Content-Type",              "application/http" },
                        { "Content-Transfer-Encoding", "binary"           },
                        { "Content-ID",                $"{i}"             }
                    }
                });
            }

            var client = GetClient();

            if (batchContent.Headers.ContentLength.HasValue == false)
            {
                // we need the ContentLength to CalculateAuthorizationHeaderValue
                // the ContentLength is calculated on the fly, it gets added to Headers only when we try to access it.
                throw new ArgumentException($"{nameof(MultipartContent)} should have content length");
            }

            SetAuthorizationHeader(client, HttpMethods.Post, url, requestMessage.Headers, batchContent.Headers);

            var response = client.SendAsync(requestMessage).Result;

            if (response.IsSuccessStatusCode == false)
            {
                throw StorageException.FromResponseMessage(response);
            }

            using var stream = response.Content.ReadAsStreamAsync().Result;
            using var reader = new StreamReader(stream);

            const string statusCode       = "StatusCode";
            const string status           = "Status";
            var          responseBoundary = $"--{response.Content.Headers.ContentType.Parameters.First().Value}";
            var          result           = new Dictionary <string, Dictionary <string, string> >();

            while (reader.Peek() >= 0)
            {
                var line = reader.ReadLine();

                // read batch response
                if (line != responseBoundary && line != $"{responseBoundary}--")
                {
                    throw new InvalidDataException("Got invalid response from server.");
                }

                while (string.IsNullOrEmpty(line) == false)
                {
                    line = reader.ReadLine();
                }

                line = reader.ReadLine();

                // read sub-response block
                if (string.IsNullOrEmpty(line))
                {
                    break;
                }

                string[] res = line.Split(" ");
                var      responseDictionary = new Dictionary <string, string>
                {
                    { statusCode, res[1] },
                    { status, res[1] == "202" ? res[res.Length - 1] : string.Join(" ", res, 2, res.Length - 2) }
                };

                line = reader.ReadLine();

                while (string.IsNullOrEmpty(line) == false)
                {
                    var r = line.Split(": ");
                    responseDictionary[r.First()] = r.Last();
                    line = reader.ReadLine();
                }
                result[blobsWithIds[responseDictionary["x-ms-client-request-id"]]] = responseDictionary;

                if (responseDictionary.TryGetValue("x-ms-error-code", out _))
                {
                    // read the error message body
                    line = reader.ReadLine();
                    if (line.StartsWith("<?xml"))
                    {
                        while (line.EndsWith("</Error>") == false)
                        {
                            line = reader.ReadLine();
                        }
                    }
                    else
                    {
                        while (string.IsNullOrEmpty(line) == false)
                        {
                            line = reader.ReadLine();
                        }
                    }
                }
            }

            var errors = result.Keys.Where(key => result[key][status] != "Accepted").ToDictionary(key => key, key => result[key][status]);
            var canLog = _logger != null && _logger.IsInfoEnabled;

            if (errors.Count == 0)
            {
                if (canLog)
                {
                    _logger.Info($"Successfully deleted {result.Count} blob{Pluralize(result.Count)} from container: {_containerName}.");
                }

                return;
            }

            var reasons = errors.Values.Distinct().ToArray();
            var failedToDeleteReasons = reasons.Aggregate(string.Empty, (current, r) =>
                                                          current + $"Reason: {r} Blobs ({errors.Count(x => x.Value == r)}): {string.Join(", ", errors.Where(x => x.Value == r).Select(y => y.Key))}. ");

            var message = $"Failed to delete {errors.Count} blob{Pluralize(errors.Count)} from container: {_containerName}. Successfully deleted {result.Count - errors.Count} blob{Pluralize(result.Count - errors.Count)}. {failedToDeleteReasons}";

            if (canLog)
            {
                _logger.Info(message);
            }

            string Pluralize(int num)
            {
                return(num == 0 || num > 1 ? "s" : string.Empty);
            }

            throw new InvalidOperationException(message);
        }
Beispiel #27
0
        /// <summary>
        /// Generates a hash for the given plain text value and returns a
        /// base64-encoded result. Before the hash is computed, a random salt
        /// is generated and appended to the plain text. This salt is stored at
        /// the end of the hash value, so it can be used later for hash
        /// verification.
        /// </summary>
        /// <param name="byteData">
        /// Plaintext value to be hashed.
        /// </param>
        /// <param name="hashAlgorithm">
        /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
        /// "SHA256", "SHA384", "SHA512", "HMACMD5", "HMACSHA1", "HMACSHA256",
        ///  "HMACSHA512" (if any other value is specified  MD5 will be used).
        ///
        /// HMAC algorithms uses Hash-based Message Authentication Code.
        /// The HMAC process mixes a secret key with the message data, hashes
        /// the result with the hash function, mixes that hash value with
        /// the secret key again, and then applies the hash function
        /// a second time. HMAC hashes are fixed lenght and generally
        /// much longer than non-HMAC hashes of the same type.
        ///
        /// https://msdn.microsoft.com/en-us/library/system.security.cryptography.hmacsha256(v=vs.110).aspx
        ///
        /// This value is case-insensitive.
        /// </param>
        /// <param name="saltBytes">
        /// Optional but recommended salt bytes to apply to the hash. If not passed the
        /// raw encoding is used. If salt is nullthe raw algorithm is used (useful for
        /// file hashes etc.) HMAC versions REQUIRE that salt is passed.
        /// </param>
        /// <param name="useBinHex">if true returns the data as BinHex byte pair string. Otherwise Base64 is returned.</param>
        /// <returns>
        /// Hash value formatted as a base64-encoded or BinHex stringstring.
        /// </returns>
        public static string ComputeHash(byte[] byteData,
                                         string hashAlgorithm,
                                         byte[] saltBytes,
                                         bool useBinHex = false)
        {
            if (byteData == null)
            {
                return(null);
            }

            // Convert plain text into a byte array.
            byte[] plainTextWithSaltBytes;

            if (saltBytes != null && !hashAlgorithm.StartsWith("HMAC"))
            {
                // Allocate array, which will hold plain text and salt.
                plainTextWithSaltBytes =
                    new byte[byteData.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < byteData.Length; i++)
                {
                    plainTextWithSaltBytes[i] = byteData[i];
                }

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                {
                    plainTextWithSaltBytes[byteData.Length + i] = saltBytes[i];
                }
            }
            else
            {
                plainTextWithSaltBytes = byteData;
            }

            HashAlgorithm hash;

            // Make sure hashing algorithm name is specified.
            if (hashAlgorithm == null)
            {
                hashAlgorithm = "";
            }

            // Initialize appropriate hashing algorithm class.
            switch (hashAlgorithm.ToUpper())
            {
            case "SHA1":
                hash = new SHA1Managed();
                break;

            case "SHA256":
                hash = new SHA256Managed();
                break;

            case "SHA384":
                hash = new SHA384Managed();
                break;

            case "SHA512":
                hash = new SHA512Managed();
                break;

            case "HMACMD5":
                hash = new HMACMD5(saltBytes);
                break;

            case "HMACSHA1":
                hash = new HMACSHA1(saltBytes);
                break;

            case "HMACSHA256":
                hash = new HMACSHA256(saltBytes);
                break;

            case "HMACSHA512":
                hash = new HMACSHA512(saltBytes);
                break;

            default:
                // default to MD5
                hash = new MD5CryptoServiceProvider();
                break;
            }

            byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);


            hash.Dispose();

            if (useBinHex)
            {
                return(BinaryToBinHex(hashBytes));
            }

            return(Convert.ToBase64String(hashBytes));
        }
Beispiel #28
0
        /* This method returns value for paramter Signature which is then passed to Signature header
         * paramter 'Signature' is calucated based on below key values and then signed with SECRET KEY -
         * host: Sandbox (apitest.cybersource.com) or Production (api.cybersource.com) hostname
         * date: "HTTP-date" format as defined by RFC7231.
         * (request-target): Should be in format of httpMethod: path
         *    Example: "post /pts/v2/payments"
         * Digest: Only needed for POST calls.
         *    digestString = BASE64( HMAC-SHA256 ( Payload ));
         *    Digest: “SHA-256=“ + digestString;
         * v-c-merchant-id: set value to Cybersource Merchant ID
         *    This ID can be found on EBC portal*/

        static StringBuilder GenerateSignature(String request, String digest, String keyid, String gmtDateTime, String method, string resource)
        {
            StringBuilder signatureHeaderValue = new StringBuilder();
            String        algorithm            = "HmacSHA256";
            String        postHeaders          = "host date (request-target) digest v-c-merchant-id";
            String        getHeaders           = "host date (request-target) v-c-merchant-id";
            String        url = "https://" + requestHost + resource;
            String        getRequestTarget  = method + " " + resource;
            String        postRequestTarget = method + " " + resource;

            try
            {
                // Generate the Signature

                StringBuilder signatureString = new StringBuilder();
                signatureString.Append('\n');
                signatureString.Append("host");
                signatureString.Append(": ");
                signatureString.Append(requestHost);
                signatureString.Append('\n');
                signatureString.Append("date");
                signatureString.Append(": ");
                signatureString.Append(gmtDateTime);
                signatureString.Append('\n');
                signatureString.Append("(request-target)");
                signatureString.Append(": ");
                if (method.Equals("post"))
                {
                    signatureString.Append(postRequestTarget);
                    signatureString.Append('\n');
                    signatureString.Append("digest");
                    signatureString.Append(": ");
                    signatureString.Append(digest);
                }
                else
                {
                    signatureString.Append(getRequestTarget);
                }
                signatureString.Append('\n');
                signatureString.Append("v-c-merchant-id");
                signatureString.Append(": ");
                signatureString.Append(merchantID);
                signatureString.Remove(0, 1);

                byte[] signatureByteString = System.Text.Encoding.UTF8.GetBytes(signatureString.ToString());

                byte[] decodedKey = Convert.FromBase64String(merchantsecretKey);

                HMACSHA256 aKeyId = new HMACSHA256(decodedKey);

                byte[] hashmessage            = aKeyId.ComputeHash(signatureByteString);
                String base64EncodedSignature = Convert.ToBase64String(hashmessage);

                signatureHeaderValue.Append("keyid=\"" + merchantKeyId + "\"");
                signatureHeaderValue.Append(", algorithm=\"" + algorithm + "\"");
                if (method.Equals("post"))
                {
                    signatureHeaderValue.Append(", headers=\"" + postHeaders + "\"");
                }
                else if (method.Equals("get"))
                {
                    signatureHeaderValue.Append(", headers=\"" + getHeaders + "\"");
                }
                signatureHeaderValue.Append(", signature=\"" + base64EncodedSignature + "\"");


                // Writing Generated Token to file.
                File.WriteAllText("..\\signatureHeaderValue.txt", signatureHeaderValue.ToString());
            }
            catch (Exception ex)
            {
                Console.WriteLine("Oops : " + ex.ToString());
            }

            return(signatureHeaderValue);
        }
        private static string GenerateKeyAuthorizationCore(
            string verb,
            string resourceId,
            string resourceType,
            INameValueCollection headers,
            string key,
            out MemoryStream payload,
            bool bUseUtcNowForMissingXDate = false)
        {
            string authorizationToken;

            // resourceId can be null for feed-read of /dbs
            if (string.IsNullOrEmpty(verb))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(verb));
            }

            if (resourceType == null)
            {
                throw new ArgumentNullException(nameof(resourceType)); // can be empty
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException(RMResources.StringArgumentNullOrEmpty, nameof(key));
            }

            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            byte[] keyBytes = Convert.FromBase64String(key);
            using (HMACSHA256 hmacSha256 = new HMACSHA256(keyBytes))
            {
                // Order of the values included in the message payload is a protocol that clients/BE need to follow exactly.
                // More headers can be added in the future.
                // If any of the value is optional, it should still have the placeholder value of ""
                // OperationType -> ResourceType -> ResourceId/OwnerId -> XDate -> Date
                string verbInput         = verb ?? string.Empty;
                string resourceIdInput   = resourceId ?? string.Empty;
                string resourceTypeInput = resourceType ?? string.Empty;

                string authResourceId       = AuthorizationHelper.GetAuthorizationResourceIdOrFullName(resourceTypeInput, resourceIdInput);
                int    memoryStreamCapacity = AuthorizationHelper.ComputeMemoryCapacity(verbInput, authResourceId, resourceTypeInput);
                payload = new MemoryStream(memoryStreamCapacity);
                AuthorizationHelper.SerializeMessagePayload(
                    payload,
                    verbInput,
                    authResourceId,
                    resourceTypeInput,
                    headers,
                    bUseUtcNowForMissingXDate);
                payload.Position = 0;

                byte[] hashPayLoad = hmacSha256.ComputeHash(payload);
                authorizationToken = Convert.ToBase64String(hashPayLoad);
                payload.Position   = 0;
            }

            return(authorizationToken);
        }
Beispiel #30
0
        public string CreateSignature(string nonce, string username, string key, string secret)
        {
            byte[] bites = new HMACSHA256(Encoding.UTF8.GetBytes(secret)).ComputeHash(Encoding.UTF8.GetBytes(nonce + username + key));

            return(BitConverter.ToString(bites).ToUpper().Replace("-", string.Empty));;
        }
Beispiel #31
0
    /// <summary>
    /// Returns the SHA256 HMAC of the given <paramref name="prefix"/>, the given <paramref name="request"/>'s
    /// body, and the given <paramref name="suffix"/> (in that order).
    /// </summary>
    /// <param name="request">The current <see cref="HttpRequest"/>.</param>
    /// <param name="secret">The key data used to initialize the <see cref="HMACSHA256"/>.</param>
    /// <param name="prefix">
    /// If non-<see langword="null"/> and non-empty, additional <c>byte</c>s to include in the hashed content
    /// before the <paramref name="request"/>'s body.
    /// </param>
    /// <param name="suffix">
    /// If non-<see langword="null"/> and non-empty, additional <c>byte</c>s to include in the hashed content
    /// after the <paramref name="request"/>'s body.
    /// </param>
    /// <returns>
    /// A <see cref="Task"/> that on completion provides a <see cref="byte"/> array containing the SHA256 HMAC of
    /// the <paramref name="prefix"/>, the <paramref name="request"/>'s body, and the <paramref name="suffix"/>
    /// (in that order).
    /// </returns>
    protected virtual async Task <byte[]> ComputeRequestBodySha256HashAsync(
        HttpRequest request,
        byte[] secret,
        byte[] prefix,
        byte[] suffix)
    {
        if (request == null)
        {
            throw new ArgumentNullException(nameof(request));
        }
        if (secret == null)
        {
            throw new ArgumentNullException(nameof(secret));
        }
        if (secret.Length == 0)
        {
            throw new ArgumentException(Resources.General_ArgumentCannotBeNullOrEmpty, nameof(secret));
        }

        await WebHookHttpRequestUtilities.PrepareRequestBody(request);

        using (var hasher = new HMACSHA256(secret))
        {
            try
            {
                if (prefix != null && prefix.Length > 0)
                {
                    hasher.TransformBlock(
                        inputBuffer: prefix,
                        inputOffset: 0,
                        inputCount: prefix.Length,
                        outputBuffer: null,
                        outputOffset: 0);
                }

                // Split body into 4K chunks.
                var buffer      = new byte[4096];
                var inputStream = request.Body;
                int bytesRead;
                while ((bytesRead = await inputStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    hasher.TransformBlock(
                        buffer,
                        inputOffset: 0,
                        inputCount: bytesRead,
                        outputBuffer: null,
                        outputOffset: 0);
                }

                if (suffix != null && suffix.Length > 0)
                {
                    hasher.TransformBlock(
                        suffix,
                        inputOffset: 0,
                        inputCount: suffix.Length,
                        outputBuffer: null,
                        outputOffset: 0);
                }

                hasher.TransformFinalBlock(Array.Empty <byte>(), inputOffset: 0, inputCount: 0);

                return(hasher.Hash);
            }
            finally
            {
                // Reset Position because JsonInputFormatter et cetera always start from current position.
                request.Body.Seek(0L, SeekOrigin.Begin);
            }
        }
    }
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            if (req.OperationName != null && IgnoreForOperationTypes.Contains(req.OperationName))
            {
                return;
            }

            var bearerToken = req.GetBearerToken()
                              ?? req.GetCookieValue(Keywords.TokenCookie);

            if (bearerToken != null)
            {
                var parts = bearerToken.Split('.');
                if (parts.Length == 3)
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    var header         = parts[0];
                    var payload        = parts[1];
                    var signatureBytes = parts[2].FromBase64UrlSafe();

                    var headerJson   = header.FromBase64UrlSafe().FromUtf8Bytes();
                    var payloadBytes = payload.FromBase64UrlSafe();

                    var headerData = headerJson.FromJson <Dictionary <string, string> >();

                    var bytesToSign = string.Concat(header, ".", payload).ToUtf8Bytes();

                    var algorithm = headerData["alg"];

                    //Potential Security Risk for relying on user-specified algorithm: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
                    if (RequireHashAlgorithm && algorithm != HashAlgorithm)
                    {
                        throw new NotSupportedException("Invalid algoritm '{0}', expected '{1}'".Fmt(algorithm, HashAlgorithm));
                    }

                    if (!VerifyPayload(algorithm, bytesToSign, signatureBytes))
                    {
                        return;
                    }

                    var payloadJson = payloadBytes.FromUtf8Bytes();
                    var jwtPayload  = JsonObject.Parse(payloadJson);

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
                else if (parts.Length == 5) //Encrypted JWE Token
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    if (PrivateKey == null || PublicKey == null)
                    {
                        throw new NotSupportedException("PrivateKey is required to DecryptPayload");
                    }

                    var jweHeaderBase64Url  = parts[0];
                    var jweEncKeyBase64Url  = parts[1];
                    var ivBase64Url         = parts[2];
                    var cipherTextBase64Url = parts[3];
                    var tagBase64Url        = parts[4];

                    var sentTag    = tagBase64Url.FromBase64UrlSafe();
                    var aadBytes   = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes();
                    var iv         = ivBase64Url.FromBase64UrlSafe();
                    var cipherText = cipherTextBase64Url.FromBase64UrlSafe();

                    var jweEncKey        = jweEncKeyBase64Url.FromBase64UrlSafe();
                    var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength);

                    var authKey  = new byte[128 / 8];
                    var cryptKey = new byte[128 / 8];
                    Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
                    Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

                    using (var hmac = new HMACSHA256(authKey))
                        using (var encryptedStream = new MemoryStream())
                        {
                            using (var writer = new BinaryWriter(encryptedStream))
                            {
                                writer.Write(aadBytes);
                                writer.Write(iv);
                                writer.Write(cipherText);
                                writer.Flush();

                                var calcTag = hmac.ComputeHash(encryptedStream.ToArray());

                                if (!calcTag.EquivalentTo(sentTag))
                                {
                                    return;
                                }
                            }
                        }

                    JsonObject jwtPayload;
                    using (var aes = new AesManaged
                    {
                        KeySize = 128,
                        BlockSize = 128,
                        Mode = CipherMode.CBC,
                        Padding = PaddingMode.PKCS7
                    })
                        using (var decryptor = aes.CreateDecryptor(cryptKey, iv))
                            using (var ms = MemoryStreamFactory.GetStream(cipherText))
                                using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                                {
                                    var jwtPayloadBytes = cryptStream.ReadFully();
                                    jwtPayload = JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes());
                                }

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
            }
        }
Beispiel #33
0
        public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
        {
            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
            }

            using (var hmac = new HMACSHA256(authKey))
            {
                var sentTag = new byte[hmac.HashSize / 8];
                //Calculate Tag
                var calcTag  = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
                var ivLength = (BlockBitSize / 8);

                //if message length is to small just return null
                if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
                {
                    return(null);
                }

                //Grab Sent Tag
                Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);

                //Compare Tag with constant time comparison
                var compare = 0;
                for (var i = 0; i < sentTag.Length; i++)
                {
                    compare |= sentTag[i] ^ calcTag[i];
                }

                //if message doesn't authenticate return null
                if (compare != 0)
                {
                    return(null);
                }

                using (var aes = new AesManaged
                {
                    KeySize = KeyBitSize,
                    BlockSize = BlockBitSize,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                })
                {
                    //Grab IV from message
                    var iv = new byte[ivLength];
                    Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                    using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
                        using (var plainTextStream = new MemoryStream())
                        {
                            using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                                using (var binaryWriter = new BinaryWriter(decrypterStream))
                                {
                                    //Decrypt Cipher Text from Message
                                    binaryWriter.Write(
                                        encryptedMessage,
                                        nonSecretPayloadLength + iv.Length,
                                        encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length
                                        );
                                }
                            //Return Plain Text
                            return(plainTextStream.ToArray());
                        }
                }
            }
        }
Beispiel #34
0
        /// <summary>
        /// Generate HMAC256 hash.
        /// </summary>
        /// <param name="key">Byte array key.</param>
        /// <param name="value">String value to hash.</param>
        /// <returns>Byte array hash.</returns>
        public static byte[] HMAC256(byte[] key, string value)
        {
            HMACSHA256 hmac = new HMACSHA256(key);

            return(hmac.ComputeHash(ToBytes(value)));
        }
Beispiel #35
0
        private static byte[] HmacSha256(byte[] key, string data)
        {
            var hashAlgorithm = new HMACSHA256(key);

            return(hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(data)));
        }
        public byte[] GenerateHmacHash(byte[] input, byte[] key)
        {
            var hmacsha256 = new HMACSHA256(key);

            return(hmacsha256.ComputeHash(input));
        }
Beispiel #37
0
        public static byte[] ComputeHMAC(byte[] data, byte[] key)
        {
            HMACSHA256 SessionHmac = new HMACSHA256(key);

            return(SessionHmac.ComputeHash(data));
        }
Beispiel #38
0
 /// <summary>
 /// Calculates a SHA-256 hash signature.
 /// </summary>
 /// <param name="input">The message for which a signature will be generated</param>
 /// <param name="key">The secret key to use to sign the message</param>
 /// <returns>The HMAC signature.</returns>
 public static byte[] HMACSHA256(byte[] input, byte[] key)
 {
     using HMACSHA256 hmac = new HMACSHA256(key);
     return(hmac.ComputeHash(input));
 }
Beispiel #39
0
        private void _listener_ReceivedPeerInfo(IPEndPoint peerEP, byte[] challenge, BinaryID recvHMAC, bool isReply)
        {
            if (PeerDiscovered != null)
            {
                BinaryID foundNetworkID = null;

                lock (_trackedNetworkIDs)
                {
                    foreach (BinaryID networkID in _trackedNetworkIDs)
                    {
                        using (HMACSHA256 hmacSHA256 = new HMACSHA256(networkID.ID))
                        {
                            BinaryID computedHmac = new BinaryID(hmacSHA256.ComputeHash(challenge));

                            if (computedHmac.Equals(recvHMAC))
                            {
                                foundNetworkID = networkID;
                                break;
                            }
                        }
                    }
                }

                if (foundNetworkID != null)
                {
                    PeerInfo peerInfo = new PeerInfo(peerEP, foundNetworkID);

                    bool peerInCache;

                    if (_peerInfoCache.Contains(peerInfo))
                    {
                        PeerInfo existingPeerInfo = _peerInfoCache[_peerInfoCache.IndexOf(peerInfo)];

                        if (existingPeerInfo.IsExpired())
                        {
                            peerInCache = false;
                            _peerInfoCache.Remove(existingPeerInfo);
                        }
                        else
                        {
                            peerInCache = true;
                        }
                    }
                    else
                    {
                        peerInCache = false;
                    }

                    if (!peerInCache)
                    {
                        _peerInfoCache.Add(peerInfo);

                        PeerDiscovered(this, peerEP, foundNetworkID);
                    }

                    if (!isReply)
                    {
                        ThreadPool.QueueUserWorkItem(AnnounceAsync, new object[] { foundNetworkID, new IPAddress[] { peerEP.Address }, 1, true });
                    }
                }
            }
        }
Beispiel #40
0
        public static byte[] SignHMACSHA256(String key, byte[] data)
        {
            HMACSHA256 hashMaker = new HMACSHA256(Encoding.ASCII.GetBytes(key));

            return(hashMaker.ComputeHash(data));
        }
        /// <summary>
        ///     Creates a signature value given a signature base and the consumer secret and a known token secret.
        /// </summary>
        /// <param name="signatureMethod">The hashing method</param>
        /// <param name="signatureTreatment">The treatment to use on a signature value</param>
        /// <param name="signatureBase">The signature base</param>
        /// <param name="consumerSecret">The consumer secret</param>
        /// <param name="tokenSecret">The token secret</param>
        /// <returns></returns>
        public static string GetSignature(OAuthSignatureMethod signatureMethod,
                                          OAuthSignatureTreatment signatureTreatment,
                                          string signatureBase, string consumerSecret, string tokenSecret)
        {
            if (tokenSecret.IsNullOrBlank())
            {
                tokenSecret = string.Empty;
            }

            var unencodedConsumerSecret = consumerSecret;

            consumerSecret = Uri.EscapeDataString(consumerSecret);
            tokenSecret    = Uri.EscapeDataString(tokenSecret);

            string signature;

            switch (signatureMethod)
            {
            case OAuthSignatureMethod.HmacSha1:
            {
                var crypto = new HMACSHA1();
                var key    = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                crypto.Key = encoding.GetBytes(key);
                signature  = signatureBase.HashWith(crypto);
                break;
            }

            case OAuthSignatureMethod.HmacSha256:
            {
                var crypto = new HMACSHA256();
                var key    = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                crypto.Key = encoding.GetBytes(key);
                signature  = signatureBase.HashWith(crypto);
                break;
            }

            case OAuthSignatureMethod.RsaSha1:
            {
                using (var provider = new RSACryptoServiceProvider {
                        PersistKeyInCsp = false
                    })
                {
                    provider.FromXmlString2(unencodedConsumerSecret);

                    SHA1Managed hasher = new SHA1Managed();
                    byte[]      hash   = hasher.ComputeHash(encoding.GetBytes(signatureBase));

                    signature = Convert.ToBase64String(provider.SignHash(hash, CryptoConfig.MapNameToOID("SHA1")));
                }
                break;
            }

            case OAuthSignatureMethod.PlainText:
            {
                signature = "{0}&{1}".FormatWith(consumerSecret, tokenSecret);

                break;
            }

            default:
                throw new NotImplementedException("Only HMAC-SHA1, HMAC-SHA256, and RSA-SHA1 are currently supported.");
            }

            var result = signatureTreatment == OAuthSignatureTreatment.Escaped
                ? UrlEncodeRelaxed(signature)
                : signature;

            return(result);
        }
 private static byte[] HMACDigest([NotNull] string key, [NotNull] string content)
 {
     using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key))) {
         return(hmac.ComputeHash(Encoding.UTF8.GetBytes(content)));
     }
 }
Beispiel #43
0
        public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
        {
            if (cryptKey == null || cryptKey.Length != KeyBitSize / (double)8)
            {
                throw new ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / (double)8)
            {
                throw new ArgumentException(string.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (secretMessage == null || secretMessage.Length < 1)
            {
                throw new ArgumentException("Secret Message Required!", "secretMessage");
            }

            nonSecretPayload = nonSecretPayload ?? new byte[] { };
            byte[] cipherText;
            byte[] iv;

            using (var aes = new AesManaged()
            {
                KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7
            })
            {
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                {
                    using (var cipherStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                        {
                            using (var binaryWriter = new BinaryWriter(cryptoStream))
                            {
                                binaryWriter.Write(secretMessage);
                            }
                        }

                        cipherText = cipherStream.ToArray();
                    }
                }
            }

            using (var hmac = new HMACSHA256(authKey))
            {
                using (var encryptedStream = new MemoryStream())
                {
                    using (var binaryWriter = new BinaryWriter(encryptedStream))
                    {
                        binaryWriter.Write(nonSecretPayload);
                        binaryWriter.Write(iv);
                        binaryWriter.Write(cipherText);
                        binaryWriter.Flush();
                        var tag = hmac.ComputeHash(encryptedStream.ToArray());
                        binaryWriter.Write(tag);
                    }

                    return(encryptedStream.ToArray());
                }
            }
        }
 public byte[] computeMAC(byte[] text, byte[] key)
 {
     helper = new HMACSHA256(key);
     return(helper.ComputeHash(text));
 }
Beispiel #45
0
        public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
        {
            if (cryptKey == null || cryptKey.Length != KeyBitSize / (double)8)
            {
                throw new ArgumentException(string.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / (double)8)
            {
                throw new ArgumentException(string.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
            }

            using (var hmac = new HMACSHA256(authKey))
            {
                var sentTag  = new byte[hmac.HashSize / 8 - 1 + 1];
                var calcTag  = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
                var ivLength = (BlockBitSize / 8);
                if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
                {
                    return(null);
                }

                Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);
                var compare = 0;
                var loopTo  = sentTag.Length - 1;
                for (var i = 0; i <= loopTo; i++)
                {
                    compare = compare | sentTag[i] ^ calcTag[i];
                }

                if (compare != 0)
                {
                    return(null);
                }

                using (var aes = new AesManaged()
                {
                    KeySize = KeyBitSize, BlockSize = BlockBitSize, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7
                })
                {
                    var iv = new byte[ivLength - 1 + 1];
                    Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                    using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
                    {
                        using (var plainTextStream = new MemoryStream())
                        {
                            using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                            {
                                using (var binaryWriter = new BinaryWriter(decrypterStream))
                                {
                                    binaryWriter.Write(encryptedMessage, nonSecretPayloadLength + iv.Length, encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length);
                                }
                            }

                            return(plainTextStream.ToArray());
                        }
                    }
                }
            }
        }
 public string ComputeSignature(string message)
 {
     byte[] key            = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(gateway.ClientSecret));
     byte[] signatureBytes = new HMACSHA256(key).ComputeHash(Encoding.UTF8.GetBytes(message));
     return(BitConverter.ToString(signatureBytes).Replace("-", "").ToLower());
 }
        public static string HashHmacSHA256(string body, string secretKey)
        {
            var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));

            return(Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(body))));
        }
Beispiel #48
0
        public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
        {
            //User Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (secretMessage == null || secretMessage.Length < 1)
            {
                throw new ArgumentException("Secret Message Required!", "secretMessage");
            }

            //non-secret payload optional
            nonSecretPayload = nonSecretPayload ?? new byte[] { };

            byte[] cipherText;
            byte[] iv;

            using (var aes = new AesManaged
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                //Use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                    using (var cipherStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                            using (var binaryWriter = new BinaryWriter(cryptoStream))
                            {
                                //Encrypt Data
                                binaryWriter.Write(secretMessage);
                            }

                        cipherText = cipherStream.ToArray();
                    }
            }

            //Assemble encrypted message and add authentication
            using (var hmac = new HMACSHA256(authKey))
                using (var encryptedStream = new MemoryStream())
                {
                    using (var binaryWriter = new BinaryWriter(encryptedStream))
                    {
                        //Prepend non-secret payload if any
                        binaryWriter.Write(nonSecretPayload);
                        //Prepend IV
                        binaryWriter.Write(iv);
                        //Write Ciphertext
                        binaryWriter.Write(cipherText);
                        binaryWriter.Flush();

                        //Authenticate all data
                        var tag = hmac.ComputeHash(encryptedStream.ToArray());
                        //Postpend tag
                        binaryWriter.Write(tag);
                    }
                    return(encryptedStream.ToArray());
                }
        }
        /// <summary>
        /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message.
        /// </summary>
        /// <param name="encryptedMessage">The encrypted message.</param>
        /// <param name="cryptKey">The crypt key.</param>
        /// <param name="authKey">The auth key.</param>
        /// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
        /// <returns>Decrypted Message</returns>
        public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
        {
            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException($"CryptKey needs to be {KeyBitSize.ToString()} bit!", nameof(cryptKey));
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException($"AuthKey needs to be {KeyBitSize.ToString()} bit!", nameof(authKey));
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", nameof(encryptedMessage));
            }

            using (HMACSHA256 hmac = new HMACSHA256(authKey))
            {
                byte[] sentTag = new byte[hmac.HashSize / 8];
                //Calculate Tag
                byte[] calcTag  = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
                int    ivLength = (BlockBitSize / 8);

                //if message length is to small just return null
                if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
                {
                    return(null);
                }

                //Grab Sent Tag
                Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);

                //Compare Tag with constant time comparison
                int compare = 0;
                for (int i = 0; i < sentTag.Length; i++)
                {
                    compare |= sentTag[i] ^ calcTag[i];
                }

                //if message doesn't authenticate return null
                if (compare != 0)
                {
                    return(null);
                }

                using (AesManaged aes = new AesManaged
                {
                    KeySize = KeyBitSize,
                    BlockSize = BlockBitSize,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                })
                {
                    //Grab IV from message
                    byte[] iv = new byte[ivLength];
                    Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                    ICryptoTransform decrypter       = aes.CreateDecryptor(cryptKey, iv);
                    MemoryStream     plainTextStream = new MemoryStream();
                    {
                        CryptoStream decrypterStream = null;
                        try
                        {
                            decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write);
                            using (BinaryWriter binaryWriter = new BinaryWriter(decrypterStream))
                            {
                                decrypterStream = null;
                                //Decrypt Cipher Text from Message
                                binaryWriter.Write(encryptedMessage, nonSecretPayloadLength + iv.Length, encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length);
                                binaryWriter.Flush();
                            }
                            //Return Plain Text
                            return(plainTextStream.ToArray());
                        }
                        catch { }
                        finally
                        {
                            if (decrypterStream != null)
                            {
                                decrypterStream.Dispose();
                            }
                        }
                    }
                }
            }

            return(new byte[0]);
        }
Beispiel #50
-3
 public static string HashString(string str_to_hash)
 {
     HMACSHA256 hs256 = new HMACSHA256(Encoding.ASCII.GetBytes(ConfigurationManager.AppSettings["UserSalt"]));
     return BytesToHexString(hs256.ComputeHash(StringToBytes(str_to_hash))).Replace("-", "");
 }