LoginSignup
7
0

More than 3 years have passed since last update.

golangで文字列からキー付きでsha256ハッシュ化する方法

Posted at

キー付きでハッシュ化

キー無しでハッシュ化する方法は以前記事(golangで文字列からsha256でハッシュ化する方法)を執筆したのですが、今回はキー付きでhash化する方法です。

// キー無しでSHA256
func getBinaryBySHA256(s string) []byte {
    r := sha256.Sum256([]byte(s))
    return r[:]
}

// キー有りでSHA256
func getBinaryBySHA256WithKey(msg, key string) ([]byte, error) {
    mac := hmac.New(sha256.New, getBinaryBySHA256(key))
    _, err := mac.Write([]byte(msg))
    return mac.Sum(nil), err
}

サンプルプログラム

hash化は不可逆変換ですが、同じ文字列に対して、同じキーを使ってhash化すれば同じ値になります
暗号化とは違うのでお気をつけください

package main

import (
    "crypto/hmac"
    "crypto/sha256"
    "encoding/hex"
    "fmt"
)

func main() {
    key := "Hello, World"
    msg := "some message"

    b, _ := getBinaryBySHA256WithKey(msg, key)
    fmt.Println(b) // [0 216 92 122 115 159 23 115 167 90 110 26 246 24 65 143 147 100 227 21 198 33 167 226 128 220 121 229 179 78 59 33]
    fmt.Println(hex.EncodeToString(b)) // 00d85c7a739f1773a75a6e1af618418f9364e315c621a7e280dc79e5b34e3b21
}

func getBinaryBySHA256(s string) []byte {
    r := sha256.Sum256([]byte(s))
    return r[:]
}

func getBinaryBySHA256WithKey(msg, key string) ([]byte, error) {
    // hmac.New(string, []byte)なので、[]byte部分にgetBinaryBySHA256を使う必要はないですが、今回はサンプルとして使用しておきます
    mac := hmac.New(sha256.New, getBinaryBySHA256(key))
    _, err := mac.Write([]byte(msg))
    return mac.Sum(nil), err
}

7
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0