HMAC-SHA 1アルゴリズムの使用方法

5794 ワード

1、HMACSHA1   
HMACSHA1
SHA1 , HMAC( )。 HMAC
, , , 。 160

ビット、指定したビット数に変換できます.
2、QQ OAuth 1.0        

///

/// HMACSHA1 ToBase64String

///


///

///

/// ( )

public static string ToBase64hmac(string strText, string strKey)

{

HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(strKey));

byte[] byteText = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(strText));

return System.Convert.ToBase64String(byteText);

}
, :

public static string HMACSHA1Text(string EncryptText, string EncryptKey)
{
//HMACSHA1
string message;
string key;
message = EncryptText;
key = EncryptKey;

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] keyByte = encoding.GetBytes(key);
HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
byte[] messageBytes = encoding.GetBytes(message);
byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);

return ByteToString(hashmessage);
}

, 。COPY


using System.Security.Cryptography;

3、 HMACSHA1

public static string HMACSHA1Text(string EncryptText, string EncryptKey)

{
//HMACSHA1
HMACSHA1 hmacsha1 = new HMACSHA1();
hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);

byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
return Convert.ToBase64String(hashBytes);
}
      
public static string HmacSha1Sign(string text, string key)
        {
            Encoding encode = Encoding.GetEncoding(input_charset);
            byte[] byteData = encode.GetBytes(text);
            byte[] byteKey = encode.GetBytes(key);
            HMACSHA1 hmac = new HMACSHA1(byteKey);
            CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);
            cs.Write(byteData, 0, byteData.Length);
            cs.Close();
            return Convert.ToBase64String(hmac.Hash);
        }