Last active
          August 29, 2015 14:02 
        
      - 
      
 - 
        
Save genghisjahn/c696026b56784bd41512 to your computer and use it in GitHub Desktop.  
    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
    
  
  
    
  | // http://play.golang.org/p/YxTFqTxBPv | |
| package main | |
| import ( | |
| "crypto/hmac" | |
| "crypto/rand" | |
| "crypto/sha512" | |
| "encoding/base64" | |
| "encoding/json" | |
| "fmt" | |
| "time" | |
| ) | |
| type BaseMessage struct { | |
| PublicKey string | |
| TimeStamp time.Time | |
| Nonce string | |
| Verb string | |
| Body string | |
| } | |
| type SignedMessage struct { | |
| MessageInfo BaseMessage | |
| Hash string | |
| } | |
| func (sm *SignedMessage) SetHash(privkey string) { | |
| jsonbody, _ := json.Marshal(sm.MessageInfo) | |
| key := []byte(privkey) | |
| h := hmac.New(sha512.New, key) | |
| h.Write([]byte(jsonbody)) | |
| sm.Hash = base64.StdEncoding.EncodeToString(h.Sum(nil)) | |
| } | |
| func main() { | |
| pubkey := "mbRgpR2eYAdJkhvrfwjlmMC+L/0Vbrj4KvVo5nvnScwsx25LK+tPE3AM/IMcHuDW5zzp4Kup9xKd5YXupRJHzw==" | |
| privkey := "7F22ZeY+mlHtALq3sXcjrLdcID7whhVIQ5zD4bl4raKdBTYVgAjfdbvdfB5lmQa4wVP1o4frD5tfUcKON4ueVA==" | |
| _ = pubkey | |
| _ = privkey | |
| _, nonce := GenerateKey(32) | |
| sMsg := SignedMessage{} | |
| sMsg.MessageInfo.PublicKey = pubkey | |
| sMsg.MessageInfo.TimeStamp = time.Now().Local() | |
| sMsg.MessageInfo.Verb = "get" | |
| sMsg.MessageInfo.Nonce = nonce | |
| sMsg.MessageInfo.Body = "Get item id 42" | |
| sMsg.SetHash(privkey) | |
| jsonmsg,_:=json.Marshal(sMsg) | |
| fmt.Println("Hashed: ", sMsg.Hash) | |
| fmt.Printf("SignedMessage: %v.\n", string(jsonmsg)) | |
| } | |
| func GenerateKey(keylength int) ([]byte, string) { | |
| key := make([]byte, keylength) | |
| rand.Read(key) | |
| base64str := base64.StdEncoding.EncodeToString(key) | |
| return key, base64str | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment