サンプル C
この C クラスは、3 つの入力パラメーターからダイジェストトークンを作成する方法を示しています。
- strEncryptionMethod – ハッシュ計算方法 (SHA1、SHA256、または MD5) をリスト
- message – ダイジェストトークンに変換する値をリスト
- sharedKey – 秘密キーをリスト
注:
ダイジェストトークンの生成には、SHA256 などのより強力で安全なハッシュアルゴリズムを使用します。
この例では、以下を前提としています。
- Web サーバーは C をサポート
- 他のコードがこのクラスを呼び出し、予想されるパラメーターを渡す
サンプルコード
private stringdigestData(string strEncryptionMethod , string message , string sharedKey ) {
UnicodeEncoding myUnicodeEncoding = new UnicodeEncoding ( ) ;
byte [ ] messageBytes = System. Text. Encoding. ASCII. GetBytes (message ) ;
byte [ ] sharedKeyBytes = System. Text. Encoding. ASCII. GetBytes (sharedKey ) ;
byte [ ] hashedMessage ;
string b64SHA1Message ;
if (this. DEBUG ) {
TextBoxMessage. Text = message ;
TextBoxSecret. Text = sharedKey ; }
switch ( (strEncryptionMethod ) )
{ case "SHA1" :
HMACSHA1 hmacsha1 = new HMACSHA1 ( ) ;
hmacsha1. Key = sharedKeyBytes ;
hashedMessage = hmacsha1. ComputeHash (messageBytes ) ;
b64SHA1Message = Convert. ToBase64String (hashedMessage ) ; if (this. DEBUG ) TextBoxDigest. Text = Convert. ToString (hashedMessage ) ; break ;
case "MD5" :
HMACMD5 hmacmd5 = new HMACMD5 (sharedKeyBytes ) ;
hashedMessage = hmacmd5. ComputeHash (messageBytes ) ;
b64SHA1Message = Convert. ToBase64String (hashedMessage ) ; if (this. DEBUG ) TextBoxDigest. Text = Convert. ToString (hashedMessage ) ; break ;
default :
b64SHA1Message = "Unknown Encryption Method" ; break ;
}
TextBoxBase64. Text = b64SHA1Message ; return b64SHA1Message ;
}