コード例 #1
0
        // public methods
        /// <summary>
        /// Static method that computes a combined key from issue and requester entropy using PSHA1 according to WS-Trust
        /// </summary>
        /// <param name="requestorEntropy">Entropy provided by the requester</param>
        /// <param name="issuerEntropy">Entropy provided by the issuer</param>
        /// <param name="keySize">Size of required key, in bits</param>
        /// <returns>Array of bytes that contain key material</returns>
        public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySize)
        {
            KeyedHashAlgorithm kha = new HMACSHA1(requestorEntropy, true);

            byte[] key = new byte[keySize / 8];                 // Final key
            byte[] a   = issuerEntropy;                         // A(0)
            byte[] b   = new byte[kha.HashSize / 8 + a.Length]; // Buffer for A(i) + seed

            for (int i = 0; i < key.Length;)
            {
                // Calculate A(i+1).
                kha.Initialize();
                a = kha.ComputeHash(a);

                // Calculate A(i) + seed
                a.CopyTo(b, 0);
                issuerEntropy.CopyTo(b, a.Length);
                kha.Initialize();
                byte[] result = kha.ComputeHash(b);

                for (int j = 0; j < result.Length; j++)
                {
                    if (i < key.Length)
                    {
                        key[i++] = result[j];
                    }
                    else
                    {
                        break;
                    }
                }
            }

            return(key);
        }
コード例 #2
0
        public static byte[] ComputeCombinedKey(byte[] requestorEntropy, byte[] issuerEntropy, int keySize)
        {
            if (keySize < 64 || keySize > 4096)
            {
                throw new ArgumentOutOfRangeException("keySize");
            }
            KeyedHashAlgorithm keyedHashAlgorithm = new HMACSHA1(requestorEntropy, true);

            byte[] array  = new byte[keySize / 8];
            byte[] array2 = issuerEntropy;
            byte[] array3 = new byte[keyedHashAlgorithm.HashSize / 8 + array2.Length];
            int    i      = 0;

            while (i < array.Length)
            {
                keyedHashAlgorithm.Initialize();
                array2 = keyedHashAlgorithm.ComputeHash(array2);
                array2.CopyTo(array3, 0);
                issuerEntropy.CopyTo(array3, array2.Length);
                keyedHashAlgorithm.Initialize();
                byte[] array4 = keyedHashAlgorithm.ComputeHash(array3);
                int    num    = 0;
                while (num < array4.Length && i < array.Length)
                {
                    array[i++] = array4[num];
                    num++;
                }
            }
            return(array);
        }
コード例 #3
0
ファイル: SignatureHelper.cs プロジェクト: Mx1014/workSource
        /// <summary>
        /// 计算一个字典的签名。
        ///
        /// </summary>
        /// <param name="paramsMap">字典</param>
        /// <param name="secretKey">密钥,base64编码过的64字节的Key</param>
        /// <returns>base64字符串</returns>
        public static String ComputeSignature(Dictionary <String, String> paramsMap, String secretKey)
        {
            byte[]   key        = System.Convert.FromBase64String(secretKey);
            HMACSHA1 myhmacsha1 = new HMACSHA1(key);

            myhmacsha1.Initialize();
            List <String> keyList = new List <string>();

            keyList.AddRange(paramsMap.Keys);
            keyList.Sort();

            StringBuilder sb = new StringBuilder();

            byte[] b = null;
            foreach (var keyItem in keyList)
            {
                //b = Encoding.UTF8.GetBytes(keyItem);
                sb.Append(keyItem);
                if (!String.IsNullOrEmpty(paramsMap[keyItem]))
                {
                    sb.Append(paramsMap[keyItem]);
                }
            }
            //String r = myhmacsha1.ComputeHash(ms).Aggregate("", (s, e) => s + String.Format("{0:x2}", e), s => s);
            Console.WriteLine(sb.ToString());
            //char[] cs = r.ToCharArray();
            b = myhmacsha1.ComputeHash(Encoding.UTF8.GetBytes(sb.ToString()));
            return(System.Convert.ToBase64String(b));
        }
コード例 #4
0
ファイル: CryptoUtils.cs プロジェクト: gema-arta/UWPX-Client
        public static byte[] HmacSha1(byte[] data, byte[] key)
        {
            HMACSHA1 hmac = new HMACSHA1(key);

            hmac.Initialize();
            return(hmac.ComputeHash(data));
        }
コード例 #5
0
ファイル: CoursioApi.cs プロジェクト: punarinta/coursio-api
        public void Auth()
        {
            // setup connection to endpoint
            request = WebRequest.Create(baseUrl + "auth");

            // compute HMAC
            var      enc  = Encoding.ASCII;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(privateKey));

            hmac.Initialize();

            var timestamp = DateTime.Now.ToString(@"MM\/dd\/yyyy hh\:mm");

            byte[] buffer = enc.GetBytes(publicKey + timestamp + salt);
            var    hash   = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();

            request.Headers ["X-Coursio-apikey"] = publicKey;
            request.Headers ["X-Coursio-time"]   = timestamp;
            request.Headers ["X-Coursio-random"] = salt;
            request.Headers ["X-Coursio-hmac"]   = hash;
            request.Method = "POST";

            byte[] byteArray = Encoding.UTF8.GetBytes("{\"method\":\"loginHmac\"}");

            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Write data to the Stream
            Stream dataStream = request.GetRequestStream();

            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            // Get the response.
            WebResponse response = request.GetResponse();

            // Get the stream content and read it
            Stream       dataStream2 = response.GetResponseStream();
            StreamReader reader      = new StreamReader(dataStream2);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Clean up
            reader.Close();
            dataStream2.Close();
            response.Close();

            Regex regex = new Regex(@"""sessionId"":""(.*?)""");
            Match match = regex.Match(responseFromServer);

            if (match.Success)
            {
                sessionId = match.Groups[1].Value;
            }
            else
            {
                throw new System.Exception("Login failed");
            }
        }
コード例 #6
0
        /// <summary>
        /// Generates a PIN of desired length when given a challenge (counter)
        /// </summary>
        /// <param name="challenge">Counter to calculate hash</param>
        /// <returns>Desired length PIN</returns>
        private String generateResponseCode(long challenge, byte[] randomBytes)
        {
            //create hmacsha1 instance and init
            HMACSHA1 myHmac = new HMACSHA1(randomBytes);

            myHmac.Initialize();

            //convert interval to bytes
            byte[] value = BitConverter.GetBytes(challenge);
            Array.Reverse(value); //reverses the challenge array due to differences in c# vs java
            myHmac.ComputeHash(value);

            //Get hash
            byte[] hash   = myHmac.Hash;
            int    offset = hash[hash.Length - 1] & 0xF;

            byte[] selectedFourBytes = new byte[4];
            //selected bytes are actually reversed due to c# again, thus the weird stuff here
            selectedFourBytes[0] = hash[offset];
            selectedFourBytes[1] = hash[offset + 1];
            selectedFourBytes[2] = hash[offset + 2];
            selectedFourBytes[3] = hash[offset + 3];
            Array.Reverse(selectedFourBytes);
            int finalInt      = BitConverter.ToInt32(selectedFourBytes, 0);
            int truncatedHash = finalInt & 0x7FFFFFFF;     //remove the most significant bit for interoperability as per HMAC standards
            int pinValue      = truncatedHash % pinModulo; //generate 10^d digits where d is the number of digits

            return(padOutput(pinValue));
        }
コード例 #7
0
        private static string Base64EncodeHash(string url)
        {
            byte[]   result;
            HMACSHA1 shaM = new HMACSHA1();

            shaM.Key = new byte[2];

            byte[] ms = new byte[url.Length];

            for (int i = 0; i < url.Length; i++)
            {
                byte b = Convert.ToByte(url[i]);
                ms[i] = (b);
            }

            shaM.Initialize();

            result = shaM.ComputeHash(ms, 0, ms.Length);



            string hash = System.Convert.ToBase64String(result);

            return(System.Web.HttpUtility.UrlEncode(hash));
        }
コード例 #8
0
            public TwitterCryptor(string consumerSecret, string oauthTokenSecret = null)
            {
                string signingKey = RFC3986.Encode(consumerSecret) + '&' + RFC3986.Encode(oauthTokenSecret);

                m_Crypto = new HMACSHA1(Encoding.ASCII.GetBytes(signingKey));
                m_Crypto.Initialize();
            }
コード例 #9
0
        public static string GetS3SignedPlayer(string url)
        {
            url = url ?? "https://s3-sa-east-1.amazonaws.com/mgunauthpermission/imageUniRio.png";


            var accessKey = Constants.ACCESSKEY;
            var secretKey = Constants.SECRETKEY;
            var r         = ((int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds + 3600) / 60.0;
            var expires   = Math.Round(r) * 60;

            var enc    = Encoding.ASCII;
            var encUtf = Encoding.UTF8;

            HMACSHA1 hmac = new HMACSHA1(encUtf.GetBytes(secretKey));

            hmac.Initialize();
            var VERB     = "GET";
            var resource = (new Uri(url)).AbsolutePath;
            var host     = (new Uri(url)).AbsoluteUri.Replace(resource, "");

            var signatureString = String.Concat(VERB, "\n", "\n", "\n", expires, "\n", resource);

            byte[] buffer    = encUtf.GetBytes(signatureString);
            var    signature = ToUrlSafeBase64String(hmac.ComputeHash(buffer));

            return(String.Concat(host, resource, "?AWSAccessKeyId=", accessKey, "&Expires=", expires, "&Signature=", HttpUtility.UrlEncode(signature)));
        }
コード例 #10
0
        private static string ToHMAC_SHA1(string password, string key, EncodingType encodingType)
        {
            using var hmacSha = new HMACSHA1(Encoding.UTF8.GetBytes(key));

            hmacSha.Initialize();
            return(Encode(hmacSha.ComputeHash(Encoding.UTF8.GetBytes(password)), encodingType));
        }
コード例 #11
0
        public static string CalculateCode(string _key, long _tick = -1)
        {
            if (_tick == -1)
            {
                TimeSpan _timeSpan           = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                long     _currentTimeSeconds = (long)Math.Floor(_timeSpan.TotalSeconds);
                _tick = _currentTimeSeconds / Authenticator.INTERVAL_LENGTH;
            }

            byte[] _keyByteArray = Base32.Decode(_key);

            HMACSHA1 _myHmac = new HMACSHA1(_keyByteArray);

            _myHmac.Initialize();

            byte[] _value = BitConverter.GetBytes(_tick);
            Array.Reverse(_value);
            _myHmac.ComputeHash(_value);
            byte[] _hash   = _myHmac.Hash;
            int    _offset = _hash[_hash.Length - 1] & 0xF;

            byte[] _fourBytes = new byte[4];
            _fourBytes[0] = _hash[_offset];
            _fourBytes[1] = _hash[_offset + 1];
            _fourBytes[2] = _hash[_offset + 2];
            _fourBytes[3] = _hash[_offset + 3];
            Array.Reverse(_fourBytes);
            int _finalInt      = BitConverter.ToInt32(_fourBytes, 0);
            int _truncatedHash = _finalInt & 0x7FFFFFFF;
            int _pinValue      = _truncatedHash % (int)Math.Pow(10, Authenticator.PIN_LENGTH);

            return(_pinValue.ToString().PadLeft(Authenticator.PIN_LENGTH, '0'));
        }
コード例 #12
0
ファイル: Signature.cs プロジェクト: mm1860/OneLotus
        private static byte[] hash_hmac_byte(string signatureString, string secretKey)
        {
            var enc = Encoding.UTF8; HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));

            hmac.Initialize();
            byte[] buffer = enc.GetBytes(signatureString);
            return(hmac.ComputeHash(buffer));
        }
コード例 #13
0
        /// <summary>
        /// Generates signature for douban api
        /// </summary>
        /// <param name="api">Douban api path, e.g. /api/v2/search/movie</param>
        /// <param name="ts">Timestamp.</param>
        /// <returns>Douban signature</returns>
        public static string GetSigParam(string api, string ts)
        {
            using var hmacsha1 = new HMACSHA1(Encoding.UTF8.GetBytes(SecretKey));
            hmacsha1.Initialize();
            byte[] data = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes($"GET&{UrlEncodeInUpperCase(api)}&{ts}"));

            return(Convert.ToBase64String(data));
        }
コード例 #14
0
        private string createSign(HttpWebRequest request, string path)
        {
            HMACSHA1 hmacsha1 = new HMACSHA1();

            hmacsha1.Initialize();
            hmacsha1.Key = Encoding.Default.GetBytes(this.secret_key);
            byte[] final = hmacsha1.ComputeHash(Encoding.Default.GetBytes(createSignString(request, path)));
            return(Convert.ToBase64String(final));
        }
コード例 #15
0
        /// <summary>
        /// 生成基于哈希的消息验证代码
        /// </summary>
        /// <param name="signatureString"></param>
        /// <param name="secretKey"></param>
        /// <returns></returns>
        private byte[] CreateHmacSha(string signString, string secretKey)
        {
            var      encoding = Encoding.UTF8;
            HMACSHA1 hmacsha  = new HMACSHA1(encoding.GetBytes(secretKey));

            hmacsha.Initialize();
            byte[] buffer = encoding.GetBytes(signString);
            return(hmacsha.ComputeHash(buffer));
        }
コード例 #16
0
 /// <summary>
 /// Signs the input with the key provided
 /// </summary>
 /// <param name="input">Data to be signed</param>
 /// <param name="key">Key used for signing</param>
 /// <returns>Base64 encoded signed data</returns>
 public static string SignHMAC(byte[] input, byte[] key)
 {
     using (HMACSHA1 hmac = new HMACSHA1(key))
     {
         hmac.Initialize();
         var signature = hmac.ComputeHash(input);
         return(Convert.ToBase64String(signature));
     }
 }
コード例 #17
0
        private static string hash_hmac(string signatureString, string secretKey)
        {
            var      enc  = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));

            hmac.Initialize();
            byte[] buffer = enc.GetBytes(signatureString);
            return(BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower());
        }
コード例 #18
0
        static string hmac1(char[] secretKey, char[] signatureString)
        {
            var      enc  = Encoding.ASCII;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));

            hmac.Initialize();
            byte[] buffer = enc.GetBytes(signatureString);
            return(BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower());
        }
コード例 #19
0
ファイル: HmacHelper.cs プロジェクト: YAMAHAH/core-library
        public static string HmacSha1ToBase64(string signatureString, string secretKey)
        {
            var      enc  = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));

            hmac.Initialize();
            byte[] buffer = enc.GetBytes(signatureString);
            return(Convert.ToBase64String(hmac.ComputeHash(buffer)).Trim());
        }
コード例 #20
0
ファイル: ePayHelpers.cs プロジェクト: Stefoajc/RealEstate
 /// <summary>
 /// UTF8 !
 /// </summary>
 /// <param name="tobeSigned"></param>
 /// <returns></returns>
 public static string HMAC_SHA1_Encoding(string tobeSigned)
 {
     using (HMACSHA1 hmac = new HMACSHA1(System.Text.Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["ePayClientSecret"])))
     {
         hmac.Initialize();
         byte[] encodedBytes = System.Text.Encoding.UTF8.GetBytes(tobeSigned);
         return(BitConverter.ToString(hmac.ComputeHash(encodedBytes)).Replace("-", "").ToLower());
     }
 }
コード例 #21
0
        public static byte[] CalculateHMACSHA1(string data, string key)
        {
            var      enc  = System.Text.Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(key));

            hmac.Initialize();

            byte[] buffer = enc.GetBytes(data);
            return(hmac.ComputeHash(buffer));
        }
コード例 #22
0
        private string hash_hmac(string signatureString, string secretKey)
        {
            var      enc  = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secretKey));

            hmac.Initialize();

            byte[] buffer = enc.GetBytes(signatureString);
            return(Convert.ToBase64String(hmac.ComputeHash(buffer)));
        }
コード例 #23
0
        private static byte[] HMACSHA1(string signatureString, string secretKey)
        {
            var sh1 = new HMACSHA1(UTF8Bytes(secretKey));

            sh1.Initialize();

            var buffer = UTF8Bytes(signatureString);

            return(sh1.ComputeHash(buffer));
        }
コード例 #24
0
ファイル: Util.cs プロジェクト: xuyongjie/GeoWeatherQuery
        public static string HashHMAC(string PublicKey, string PrivateKey)
        {
            var      enc  = Encoding.UTF8;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(PrivateKey));

            hmac.Initialize();
            byte[] buffer = enc.GetBytes(PublicKey);

            return(Convert.ToBase64String(hmac.ComputeHash(buffer)));
        }
コード例 #25
0
        // ReSharper disable once InconsistentNaming
        public string HashHMACSHA1WithoutBase64(string message, string secret)
        {
            var      enc  = Encoding.ASCII;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secret));

            hmac.Initialize();

            byte[] buffer = enc.GetBytes(message);
            return(BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower());
        }
コード例 #26
0
        private string HmacSha1(string encoded, string secret)
        {
            var      enc  = Encoding.ASCII;
            HMACSHA1 hmac = new HMACSHA1(enc.GetBytes(secret));

            hmac.Initialize();

            byte[] buffer = enc.GetBytes(encoded);
            return(BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower());
        }
コード例 #27
0
ファイル: ePayBgButton.cs プロジェクト: tuaasn/Cart42
        private string calculateHmac(string encoded)
        {
            var hmac = new HMACSHA1(Encoding.ASCII.GetBytes(settings.Secret));

            hmac.Initialize();
            byte[] buffer   = Encoding.ASCII.GetBytes(encoded);
            string checksum = BitConverter.ToString(hmac.ComputeHash(buffer)).Replace("-", "").ToLower();

            return(checksum);
        }
コード例 #28
0
        /// <summary>
        /// Generates the encrypted password to append to the end of a request URI.
        /// </summary>
        /// <param name="url">request URI without "&amp;pass="******"string"/> of the encrypted password.</returns>
        protected string GenerateQueryStringPassword(string url)
        {
            var uri      = new Uri(url);
            var hmacshA1 = new HMACSHA1(Encoding.ASCII.GetBytes(Key.ToLowerInvariant()));

            hmacshA1.Initialize();
            var str = Convert.ToBase64String(hmacshA1.ComputeHash(Encoding.ASCII.GetBytes(uri.PathAndQuery)));

            return(Uri.EscapeDataString(string.Format("HMAC{{{0}}}", str.ToLowerInvariant())));
        }
コード例 #29
0
        private string ComputeHash(string privateKey, string message)
        {
            var key = Encoding.UTF8.GetBytes(privateKey);

            using (var hmac = new HMACSHA1(key))
            {
                hmac.Initialize();
                var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
                return(Convert.ToBase64String(hash));
            }
        }
コード例 #30
0
        private static string GetBase64Digest(string signatureString, string secretKey)
        {
            var enc  = Encoding.UTF8;
            var hmac = new HMACSHA1(enc.GetBytes(secretKey));

            hmac.Initialize();

            var buffer = enc.GetBytes(signatureString);

            return(Convert.ToBase64String(hmac.ComputeHash(buffer)));
        }
コード例 #31
0
    private static string Base64EncodeHash(Stream ms)
    {
        ms.Seek(0, SeekOrigin.Begin);
        byte[] result;
        HMACSHA1 shaM = new HMACSHA1();
        shaM.Key = new byte[1];

        shaM.Initialize();

        result = shaM.ComputeHash(ms);

        string hash = System.Convert.ToBase64String(result);
        return hash;
    }