Fragment Description:



encoding into Base64, signing a message or not signing it.
Remember:
1- Encrypting:
you use their public key to write message and they use their private key to read it.
2- Signing:
you use your private key to write your message's signature, and they use your public key to check if it's really yours.


Base64Encoding

Go Playground

Last update, on 2015, Sat 28 Nov, 18:12:48

/* ... <== see fragment description ... */

package main

import (
    "bytes"
    "crypto/hmac"
    "crypto/sha256"
    "encoding/base64"
    "fmt"
)

var messageBase64 string

func ComputeHmac256(message string, secret string) string {
    key := []byte(secret)
    // An HMAC is a cryptographic hash that uses a key to 'sign' a message.
    // func New(h func() hash.Hash, key []byte) hash.Hash
    h := hmac.New(sha256.New, key)
    h.Write([]byte(message))
    messageBase64 = base64.StdEncoding.EncodeToString(h.Sum(nil))
    return messageBase64
}
func toBase64(data string) string {
    // buf is an io.Writer, see bytes.Buffer (Write)
    var buf bytes.Buffer
    encoder := base64.NewEncoder(base64.StdEncoding, &buf)
    encoder.Write([]byte(data))
    encoder.Close()
    return buf.String()
}
func main() {
    fmt.Println("base64 signed: ", ComputeHmac256("Message", "secret"))
    fmt.Println("base64 not signed: ", toBase64(messageBase64))
}

/* Expected Output:
base64 signed:  HZWuYpaasfqTS4OVF5sgzkU8tEdrqkfKN27GysTA/f8=
base64 not signed:  SFpXdVlwYWFzZnFUUzRPVkY1c2d6a1U4dEVkcnFrZktOMjdHeXNUQS9mOD0=
*/



Comments