예제 #1
0
파일: Program.cs 프로젝트: shi5588/shi5588
 // Computes a keyed hash for a source file, creates a target file with the keyed hash
 // prepended to the contents of the source file, then decrypts the file and compares
 // the source and the decrypted files.
 public static void EncodeFile(byte[] key, String sourceFile, String destFile)
 {
     // Initialize the keyed hash object.
     HMACSHA256 myhmacsha256 = new HMACSHA256(key);
     FileStream inStream = new FileStream(sourceFile, FileMode.Open);
     FileStream outStream = new FileStream(destFile, FileMode.Create);
     // Compute the hash of the input file.
     byte[] hashValue = myhmacsha256.ComputeHash(inStream);
     // Reset inStream to the beginning of the file.
     inStream.Position = 0;
     // Write the computed hash value to the output file.
     outStream.Write(hashValue, 0, hashValue.Length);
     // Copy the contents of the sourceFile to the destFile.
     int bytesRead;
     // read 1K at a time
     byte[] buffer = new byte[1024];
     do
     {
         // Read from the wrapping CryptoStream.
         bytesRead = inStream.Read(buffer, 0, 1024);
         outStream.Write(buffer, 0, bytesRead);
     } while (bytesRead > 0);
     myhmacsha256.Clear();
     // Close the streams
     inStream.Close();
     outStream.Close();
     return;
 }
        public static string GenerateHMACSHA256Hash(string Password, string QueueId, string UrlToHash)
        {
            ValidateInput(QueueId, "QueueId");
            ValidateInput(Password, "Password");
            ValidateInput(UrlToHash, "UrlToHash");

            // Create a random key using a random number generator. This would be the
            //  secret key shared by sender and receiver.
            byte[] secretkey = new Byte[64];
            Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(Password, Encoding.UTF8.GetBytes(QueueId));
            secretkey = deriveBytes.GetBytes(64);

            // Initialize the keyed hash object.
            HMACSHA256 myhmacsha256 = new HMACSHA256(secretkey);
            byte[] byteStringToHash = Encoding.UTF8.GetBytes(UrlToHash);
            byte[] hashValue = myhmacsha256.ComputeHash(byteStringToHash);
            myhmacsha256.Clear();

            string hashStr = Encoding.ASCII.GetString(hashValue);
            string UrlEncodeHashString = HttpUtility.UrlEncode(hashStr);
            //not all special characters like = and / are encoded on first UrlEncoding
            //UrlEncoding once more fixes the problem......
            UrlEncodeHashString = HttpUtility.UrlEncode(UrlEncodeHashString);

            return UrlEncodeHashString;
        }
예제 #3
0
        public static string Get(string code)
        {
            HMAC alg = new HMACSHA256(Key);
            try
            {
                DateTime    date = new DateTime(1978, 3, 31);
                byte[] hashBytes = alg.ComputeHash(Encoding.UTF8.GetBytes(code));
                byte[]    result = new byte[8 + hashBytes.Length];

                hashBytes.CopyTo(result, 8);
                BitConverter.GetBytes(date.Ticks).CopyTo(result, 0);
                return Swap(Convert.ToBase64String(result), "+=/", "-_,");
            }
            finally { alg.Clear(); }
        }
예제 #4
0
 // Hashing a value using HMAC-256
 private void HMACHash()
 {
     ASCIIEncoding encode = new ASCIIEncoding();
     HMACSHA256 hmac256 = new HMACSHA256(key);
     byte[] uniqueAsByte = encode.GetBytes(unique);
     byte[] hashedUnique = hmac256.ComputeHash(uniqueAsByte);
     unique = null;
     unique = ByteToString(hashedUnique);
     hmac256.Clear();
 }
예제 #5
0
        private static string HMACHashIntoHexString(string value_IN, string secret_IN)
        {
            // return reference
            string value_OUT = null;

            // declare variables
            string secret   = "";
            string to_hash  = "";
            string hex_hash = "";

            System.Text.UTF8Encoding encoding = null;

            // declare variables - making HMAC hash
            byte[] key = null;
            System.Security.Cryptography.HMACSHA256 myhmacsha256 = null;
            byte[] value_bytes = null;
            byte[] hashValue   = null;
            //string resultSTR = null;

            // do we have a value?
            if ((value_IN != null) && (value_IN != ""))
            {
                // set up hash test.
                secret  = secret_IN;
                to_hash = value_IN;

                // set encoding
                encoding = new System.Text.UTF8Encoding();

                // Hash secret using SHA256, use that as the key.
                key = SHA256HashByteArray(secret);

                // not just converting to byte array
                // key = encoding.GetBytes( secret );

                // initialize HMAC hasher.
                myhmacsha256 = new System.Security.Cryptography.HMACSHA256(key);

                // hash the value.
                value_bytes = encoding.GetBytes(to_hash);

                // compute hash on bytes
                hashValue = myhmacsha256.ComputeHash(value_bytes);

                // clear out the hasher - wouldn't need to do this if you just
                //    initialized it once with a secret, then kept it around in a
                //    variable.
                myhmacsha256.Clear();

                // convert to base-64 string.
                // resultSTR = Convert.ToBase64String( hashValue );
                // Console.WriteLine( "base 64: " + resultSTR );

                // output as base-64

                // output as hex, lower-case...
                hex_hash = BitConverter.ToString(hashValue).Replace("-", string.Empty);
                hex_hash = hex_hash.ToLower();
                //Console.WriteLine( "hex: " + hex_hash );

                value_OUT = hex_hash;
            }
            else
            {
                // nothing passed in.  Return "".
                value_OUT = "";
            }

            return(value_OUT);
        } //-- END private static method HMACHashIntoHexString --//
예제 #6
0
파일: OAuth.cs 프로젝트: vebin/WeiboSdk
        /// <summary>
        ///     站内应用使用SignedRequest获取AccessToken
        /// </summary>
        /// <param name="signedRequest">SignedRequest</param>
        /// <returns></returns>
        public AccessToken GetAccessTokenBySignedRequest(string signedRequest) {
            var parameters = signedRequest.Split('.');
            if (parameters.Length < 2) {
                throw new Exception("SignedRequest格式错误。");
            }
            var encodedSig = parameters[0];
            var payload = parameters[1];
            var sha256 = new HMACSHA256(Encoding.UTF8.GetBytes(AppSecret));
            var expectedSig = Convert.ToBase64String(sha256.ComputeHash(Encoding.UTF8.GetBytes(payload)));
            sha256.Clear();

            encodedSig = parameters[0].Length%4 == 0
                             ? parameters[0]
                             : parameters[0].PadRight(parameters[0].Length + (4 - parameters[0].Length%4), '=')
                                            .Replace("-", "+")
                                            .Replace("_", "/");
            payload = parameters[1].Length%4 == 0
                          ? parameters[1]
                          : parameters[1].PadRight(parameters[1].Length + (4 - parameters[1].Length%4), '=')
                                         .Replace("-", "+")
                                         .Replace("_", "/");


            if (encodedSig != expectedSig) {
                throw new WeiboException("SignedRequest签名验证失败。");
            }
            var result = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(payload)));

            if (result["oauth_token"] == null) {
                return null; //throw new WeiboException("没有获取到授权信息,请先进行授权。");
            }

            var token = new AccessToken();
            AccessToken = token.Token = result["oauth_token"].ToString();


            token.UID = result["user_id"].ToString();
            token.ExpiresIn = Convert.ToInt32(result["expires"].ToString());
            return token;
        }