- 
      
- 
        Save roppa/b2ab8d2d41bbf507a8195f1b0007aa14 to your computer and use it in GitHub Desktop. 
    Golang SHA256 hash example
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package crypto | |
| import ( | |
| "crypto/sha256" | |
| ) | |
| // NewSHA256 ... | |
| func NewSHA256(data []byte) []byte { | |
| hash := sha256.Sum256(data) | |
| return hash[:] | |
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package crypto | |
| import ( | |
| "encoding/hex" | |
| "fmt" | |
| "testing" | |
| ) | |
| func TestNewSHA256(t *testing.T) { | |
| for i, tt := range []struct { | |
| in []byte | |
| out string | |
| }{ | |
| {[]byte(""), "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, | |
| {[]byte("abc"), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"}, | |
| {[]byte("hello"), "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"}, | |
| } { | |
| t.Run(fmt.Sprintf("%v", i), func(t *testing.T) { | |
| result := NewSHA256(tt.in) | |
| if hex.EncodeToString(result) != tt.out { | |
| t.Errorf("want %v; got %v", tt.out, hex.EncodeToString(result)) | |
| } | |
| }) | |
| } | |
| } | |
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | package main | |
| import ( | |
| "crypto/sha256" | |
| "fmt" | |
| ) | |
| func main() { | |
| data := []byte("hello") | |
| hash := sha256.Sum256(data) | |
| fmt.Printf("%x", hash[:]) // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment