Skip to content

Instantly share code, notes, and snippets.

@eiri
Last active August 3, 2020 03:32
Show Gist options
  • Save eiri/aeb74fd945bbc4975350cec6f482388f to your computer and use it in GitHub Desktop.
Save eiri/aeb74fd945bbc4975350cec6f482388f to your computer and use it in GitHub Desktop.
Script to generate CouchDB authentication cookie with expiration period of one year
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"flag"
"fmt"
"os"
"strings"
"time"
)
func main() {
var user = flag.String("user", "", "username")
var secret = flag.String("secret", "", "global secret")
var salt = flag.String("salt", "", "user's salt")
flag.Parse()
for argName, arg := range map[string]*string{"user": user, "secret": secret, "salt": salt} {
if *arg == "" {
fmt.Printf("%s is required paramter!\n", argName)
os.Exit(1)
}
}
expiration := time.Now().Add(8760 * time.Hour).Unix()
msg := []byte(fmt.Sprintf("%s:%X", *user, expiration))
key := []byte(*secret + *salt)
mac := hmac.New(sha1.New, key)
mac.Write(msg)
control := mac.Sum(nil)
cookieRaw := bytes.Join([][]byte{msg, control}, []byte(":"))
cookie := base64.StdEncoding.EncodeToString(cookieRaw)
// Don't ask. CouchDB is very... unique in how it does base64 encoding
cookie = strings.TrimRight(cookie, "=")
cookie = strings.ReplaceAll(cookie, "/", "_")
cookie = strings.ReplaceAll(cookie, "+", "-")
fmt.Printf("#HttpOnly_127.0.0.1\tFALSE\t/\tFALSE\t%d\tAuthSession\t%s\n", expiration, cookie)
}
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"flag"
"fmt"
"os"
"strconv"
"strings"
"time"
)
func main() {
var user = flag.String("cookie", "", "cookie")
var secret = flag.String("secret", "", "global secret")
var salt = flag.String("salt", "", "user's salt")
flag.Parse()
cookieRaw, _ := base64.StdEncoding.DecodeString(*cookie)
attr := bytes.Split(cookieRaw, []byte(":"))
fmt.Printf("name: %q\n", attr[0])
expiration, _ := strconv.ParseInt(string(attr[1]), 16, 64)
fmt.Printf("expiration: %d\n", expiration)
key := []byte(*secret + *salt)
msg := bytes.Join([][]byte{attr[0], attr[1]}, []byte(":"))
mac := hmac.New(sha1.New, key)
mac.Write(msg)
control := mac.Sum(nil)
fmt.Printf("returned hmac : %#v\n", attr[2])
fmt.Printf("calculated hmac: %#v\n", control)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment