rss resume / curriculum vitae linkedin linkedin gitlab github twitter mastodon instagram
Go Tip: Generating JSON Web Key Sets
Aug 06, 2018

Previously I blogged about using ActiveDirectory and JWT with Go, well this quick tip is somehow related to that post, it’s for generating JSON Web Key Sets that should help for creating a real valid JSON or for testing local-only values.

There’s a full example showing this in action, feel free to explore the repo.


This example uses the great go-jose package by Square, the final snippet code looks like this:

func generateJWTWithKeyID() *jose.JSONWebKeySet {
	rsaKey, _ := rsa.GenerateKey(rand.Reader, 2048)           // XXX Check err
	serialNumber, _ := rand.Int(rand.Reader, big.NewInt(100)) // XXX Check err

	template := x509.Certificate{
		SerialNumber: serialNumber,
		Subject: pkix.Name{
			Organization: []string{"Example Co"},
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(2 * time.Hour),
		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
	}

	derBytes, _ := x509.CreateCertificate(rand.Reader, &template, &template, &rsaKey.PublicKey, rsaKey) // XXX Check err
	certificate, _ := x509.ParseCertificate(derBytes)                                                   // XXX Check err

	return &jose.JSONWebKeySet{
		Keys: []jose.JSONWebKey{
			{
				Certificates: []*x509.Certificate{certificate},
				Key:          &rsaKey.PublicKey,
				KeyID:        "someKeyID",
				Use:          "sig",
			},
		},
	}
}

Back to posts