Monday, September 11, 2017

generate nonce value in golang

package main

import (
"fmt"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"math/big"
)

const nonceLen = 40

func main() {
nonce := make([]byte, 12)
for i := 0; i < 4; i++ {
nonce[i] = 0
}
if _, err := rand.Read(nonce[4:]); err != nil {
panic("Failure in NewCipher: " + err.Error())
}

// Encode counter to plaintext
pt := make([]byte, 16)
ctr := big.NewInt(11)
pad := 8 - len(ctr.Bytes())
fmt.Printf("pad = %d\n", pad)
copy(pt[pad:], ctr.Bytes())
fmt.Printf("pt = %d\n", pt)

// Encrypt AES256
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
panic("Failure in NewCipher: " + err.Error())
}

c, err := aes.NewCipher(key)
if err != nil {
panic("Failure in NewCipher: " + err.Error())
}
gcm, err := cipher.NewGCM(c)
if err != nil {
panic("Failure in NewGCM: " + err.Error())
}
ret := make([]byte, nonceLen)
ct := gcm.Seal(nil, nonce, pt, nil)
copy(ret, nonce[4:])
copy(ret[8:], ct)
fmt.Println(base64.RawURLEncoding.EncodeToString(ret))

}