まずは検証用のデータを PHP で作成。以下のコマンドを実行。
php -r 'echo hash_hmac("sha256", "apple", "secret_key")."\n";'結果はこちらは
ba6b88d8c49940b6424e053aef2ba049bbae3ed3b44c0cbb74bf5f1e32726b70
Unity でも apple と secret_key を引数にして ba6b88d8c49940b6424e053aef2ba049bbae3ed3b44c0cbb74bf5f1e32726b70 が返って来れば成功です。
プログラムの主な部分はこちら( C# のプログラムです)。
string sha256(string planeStr, string key) {
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] planeBytes = ue.GetBytes(planeStr);
byte[] keyBytes = ue.GetBytes(key);
System.Security.Cryptography.HMACSHA256 sha256 = new System.Security.Cryptography.HMACSHA256(keyBytes);
byte[] hashBytes = sha256.ComputeHash(planeBytes);
string hashStr = "";
foreach(byte b in hashBytes) {
hashStr += string.Format("{0,0:x2}", b);
}
return hashStr;
}
void Start () {
string res = sha256("apple", "secret_key");
Debug.Log(res);
}
実行した所、 console に表示された文字は ba6b88d8c49940b6424e053aef2ba049bbae3ed3b44c0cbb74bf5f1e32726b70 。正しく、 SHA256 でハッシュ化された値が取得できました。
関連情報
MD5 - Unify Community Wiki
http://wiki.unity3d.com/index.php?title=MD5
Unity で SHA1(メッセージダイジェスト) を生成する方法 - 強火で進め
http://d.hatena.ne.jp/nakamura001/20130115/1358265478