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))

}

Wednesday, September 6, 2017

Using M2Crypto to connect with certificate authentication

ctx = SSL.Context()
ctx.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, depth=9)
x509_store = ctx.get_cert_store()
x509_store.add_x509(CACertObject)
m2.ssl_ctx_use_x509(ctx.ctx, CertObject)
m2.ssl_ctx_use_pkey_privkey(ctx.ctx, PrivateKeyObject)
m2.ssl_ctx_check_privkey(ctx.ctx)
_ssl = SSL.Connection(ctx)
_ssl.connect((self._host, self._port))
sock = _ssl.socket