FIPS 140-3 mode

suggest change

FIPS 140-3 is a US government standard for cryptographic modules. Some regulated environments (US federal agencies and their contractors, and some finance and healthcare deployments) require software to use cryptography only from a validated module, in an approved mode of operation.

Since Go 1.24 the standard library's cryptography is built on an internal package tree called the Go Cryptographic Module (crypto/internal/fips140/...). Packages like crypto/sha256, crypto/ecdsa and crypto/tls call into it. The toolchain gives you two controls:

control when what it does
GOFIPS140 environment variable build time selects which copy of the module source is compiled in (current or a frozen snapshot) and turns FIPS mode on by default
GODEBUG=fips140=off|on|only run time (fixed at startup) turns FIPS 140-3 mode on, and optionally blocks non-approved algorithms

And two packages for code:

A note on terminology: this article describes what the Go toolchain does. Whether a specific module version is validated, and whether your product satisfies the requirements you're subject to, is decided by NIST's Cryptographic Module Validation Program and your own compliance process, not by a flag. The official reference is go.dev/doc/security/fips140.

Checking the mode at run time

crypto/fips140 has three functions to inspect the current state:

package main

import (
	"crypto/fips140"
	"fmt"
	"runtime/debug"
)

func main() {
	fmt.Println("enabled: ", fips140.Enabled())
	fmt.Println("enforced:", fips140.Enforced())
	fmt.Println("version: ", fips140.Version())

	if bi, ok := debug.ReadBuildInfo(); ok {
		for _, s := range bi.Settings {
			if s.Key == "GOFIPS140" || s.Key == "DefaultGODEBUG" {
				fmt.Printf("build setting %s=%s\n", s.Key, s.Value)
			}
		}
	}
}

Run it with different GODEBUG values:

$ go run .
enabled:  false
enforced: false
version:  latest

$ GODEBUG=fips140=on go run .
enabled:  true
enforced: false
version:  latest

$ GODEBUG=fips140=only go run .
enabled:  true
enforced: true
version:  latest

The setting is read once at program start. Changing the GODEBUG environment variable with os.Setenv later has no effect.

A service that must run in FIPS mode can check fips140.Enabled() at startup and refuse to start otherwise, so a misconfigured deployment fails loudly instead of quietly running without it.

fips140=on vs. fips140=only

With GODEBUG=fips140=on the module operates in FIPS 140-3 mode:

But on doesn't stop your code from calling non-approved algorithms like MD5 directly. That's what only adds: non-approved functions return an error or panic.

This program tries a range of operations:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/des"
	"crypto/ecdh"
	"crypto/ed25519"
	"crypto/hkdf"
	"crypto/md5"
	"crypto/pbkdf2"
	"crypto/rand"
	"crypto/rc4"
	"crypto/rsa"
	"crypto/sha1"
	"crypto/sha256"
	"fmt"
)

func try(name string, f func() error) {
	defer func() {
		if r := recover(); r != nil {
			fmt.Printf("%-28s panic: %v\n", name, r)
		}
	}()
	if err := f(); err != nil {
		fmt.Printf("%-28s error: %v\n", name, err)
		return
	}
	fmt.Printf("%-28s ok\n", name)
}

func main() {
	try("sha256.Sum256", func() error { sha256.Sum256([]byte("x")); return nil })
	try("md5.Sum", func() error { md5.Sum([]byte("x")); return nil })
	try("sha1.Sum", func() error { sha1.Sum([]byte("x")); return nil })
	try("rc4.NewCipher", func() error { _, err := rc4.NewCipher(make([]byte, 16)); return err })
	try("des.NewTripleDESCipher", func() error { _, err := des.NewTripleDESCipher(make([]byte, 24)); return err })
	try("ecdh.X25519 GenerateKey", func() error { _, err := ecdh.X25519().GenerateKey(rand.Reader); return err })
	try("ecdh.P256 GenerateKey", func() error { _, err := ecdh.P256().GenerateKey(rand.Reader); return err })
	try("ed25519.GenerateKey", func() error { _, _, err := ed25519.GenerateKey(nil); return err })
	try("rsa.GenerateKey 1024", func() error { _, err := rsa.GenerateKey(rand.Reader, 1024); return err })
	try("rsa.GenerateKey 2048", func() error { _, err := rsa.GenerateKey(rand.Reader, 2048); return err })
	try("cipher.NewGCM", func() error {
		b, _ := aes.NewCipher(make([]byte, 32))
		_, err := cipher.NewGCM(b)
		return err
	})
	try("cipher.NewGCMWithRandomNonce", func() error {
		b, _ := aes.NewCipher(make([]byte, 32))
		_, err := cipher.NewGCMWithRandomNonce(b)
		return err
	})
	try("pbkdf2 8-byte salt", func() error {
		_, err := pbkdf2.Key(sha256.New, "pw", make([]byte, 8), 1000, 32)
		return err
	})
	try("pbkdf2 16-byte salt", func() error {
		_, err := pbkdf2.Key(sha256.New, "pw", make([]byte, 16), 1000, 32)
		return err
	})
	try("hkdf sha256", func() error {
		_, err := hkdf.Key(sha256.New, []byte("secret-input-key"), nil, "info", 32)
		return err
	})
	try("hkdf md5", func() error {
		_, err := hkdf.Key(md5.New, []byte("secret-input-key"), nil, "info", 32)
		return err
	})
}

Without GODEBUG (or with fips140=on) every line prints ok. With fips140=only:

$ GODEBUG=fips140=only go run .
sha256.Sum256                ok
md5.Sum                      panic: crypto/md5: use of MD5 is not allowed in FIPS 140-only mode
sha1.Sum                     panic: crypto/sha1: use of SHA-1 is not allowed in FIPS 140-only mode
rc4.NewCipher                error: crypto/rc4: use of RC4 is not allowed in FIPS 140-only mode
des.NewTripleDESCipher       error: crypto/des: use of TripleDES is not allowed in FIPS 140-only mode
ecdh.X25519 GenerateKey      error: crypto/ecdh: use of X25519 is not allowed in FIPS 140-only mode
ecdh.P256 GenerateKey        ok
ed25519.GenerateKey          ok
rsa.GenerateKey 1024         error: crypto/rsa: use of keys smaller than 2048 bits is not allowed in FIPS 140-only mode
rsa.GenerateKey 2048         ok
cipher.NewGCM                error: crypto/cipher: use of GCM with arbitrary IVs is not allowed in FIPS 140-only mode, use NewGCMWithRandomNonce
cipher.NewGCMWithRandomNonce ok
pbkdf2 8-byte salt           error: crypto/pbkdf2: use of salts shorter than 128 bits is not allowed in FIPS 140-only mode
pbkdf2 16-byte salt          ok
hkdf sha256                  ok
hkdf md5                     error: crypto/hkdf: use of hash functions other than SHA-2 or SHA-3 is not allowed in FIPS 140-only mode

Things to notice:

Packages outside the standard library, like golang.org/x/crypto/chacha20poly1305 or golang.org/x/crypto/bcrypt, don't go through the Go Cryptographic Module at all, and only mode can't see them. If you need FIPS-approved cryptography, use the standard library packages. For password hashing that means PBKDF2, see Password hashing.

AES-GCM in only mode

The common AES-GCM pattern (shown in Encryption and decryption with AES GCM) uses cipher.NewGCM and generates a random nonce yourself. In only mode cipher.NewGCM returns an error, because the module can't verify how the caller chooses nonces.

Use cipher.NewGCMWithRandomNonce (Go 1.24) instead. It generates the nonce inside the module and prepends it to the ciphertext:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"crypto/rand"
	"fmt"
)

func main() {
	key := make([]byte, 32)
	rand.Read(key)

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}
	aead, err := cipher.NewGCMWithRandomNonce(block)
	if err != nil {
		panic(err)
	}
	fmt.Println("nonce size:", aead.NonceSize(), "overhead:", aead.Overhead())

	plaintext := []byte("attack at dawn")
	// nonce must be nil: Seal generates a random one and prepends it
	ciphertext := aead.Seal(nil, nil, plaintext, nil)
	fmt.Println("ciphertext len:", len(ciphertext))

	decrypted, err := aead.Open(nil, nil, ciphertext, nil)
	if err != nil {
		panic(err)
	}
	fmt.Println("decrypted:", string(decrypted))
}
$ GODEBUG=fips140=only go run .
nonce size: 0 overhead: 28
ciphertext len: 42
decrypted: attack at dawn

NonceSize() is 0 because you don't pass a nonce. Overhead() is 28: a 12-byte nonce plus the 16-byte authentication tag. The ciphertext format is the same as the "nonce followed by sealed data" layout most code builds by hand, so data encrypted the old way can be decrypted with Open from this AEAD.

TLS in FIPS mode

crypto/tls restricts what it negotiates as soon as FIPS mode is on (on is enough, you don't need only). This program connects to a local test server with different client configurations:

package main

import (
	"crypto/tls"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/http/httptest"
)

func get(srv *httptest.Server, cfg *tls.Config) {
	tr := srv.Client().Transport.(*http.Transport).Clone()
	cfg.RootCAs = tr.TLSClientConfig.RootCAs // trust the test certificate
	tr.TLSClientConfig = cfg
	resp, err := (&http.Client{Transport: tr}).Get(srv.URL)
	if err != nil {
		fmt.Println("  error:", err)
		return
	}
	resp.Body.Close()
	cs := resp.TLS
	fmt.Println("  ok:", tls.VersionName(cs.Version), tls.CipherSuiteName(cs.CipherSuite), cs.CurveID)
}

func main() {
	srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
	srv.Config.ErrorLog = log.New(io.Discard, "", 0)
	srv.StartTLS()
	defer srv.Close()

	fmt.Println("default config:")
	get(srv, &tls.Config{})

	fmt.Println("X25519 only:")
	get(srv, &tls.Config{CurvePreferences: []tls.CurveID{tls.X25519}})

	fmt.Println("TLS 1.2 with ChaCha20-Poly1305:")
	get(srv, &tls.Config{
		MaxVersion:   tls.VersionTLS12,
		CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256},
	})

	fmt.Println("TLS 1.2 with AES-GCM:")
	get(srv, &tls.Config{
		MaxVersion:   tls.VersionTLS12,
		CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
	})
}
$ go run .
default config:
  ok: TLS 1.3 TLS_AES_128_GCM_SHA256 X25519MLKEM768
X25519 only:
  ok: TLS 1.3 TLS_AES_128_GCM_SHA256 X25519
TLS 1.2 with ChaCha20-Poly1305:
  ok: TLS 1.2 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 X25519
TLS 1.2 with AES-GCM:
  ok: TLS 1.2 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 X25519

$ GODEBUG=fips140=on go run .
default config:
  ok: TLS 1.3 TLS_AES_128_GCM_SHA256 X25519MLKEM768
X25519 only:
  error: Get "https://127.0.0.1:62201": tls: no supported key exchange methods (CurveIDs)
TLS 1.2 with ChaCha20-Poly1305:
  error: Get "https://127.0.0.1:62201": remote error: tls: handshake failure
TLS 1.2 with AES-GCM:
  ok: TLS 1.2 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 CurveP256

With the default configuration nothing changes: TLS 1.3 with the hybrid post-quantum key exchange X25519MLKEM768 is still negotiated. Plain X25519 and ChaCha20-Poly1305 are dropped, and the TLS 1.2 connection switches from X25519 to P-256. In practice this means that in FIPS mode your service may fail to connect to peers that only support non-approved options, so test against the real servers you talk to.

In FIPS mode TLS 1.2 connections also require the Extended Master Secret extension. Go 1.27 added GODEBUG=fips140ems=0 to turn that requirement off for peers that don't support it (also backported to Go 1.26.6 and 1.25.13; it's planned to be removed in Go 1.31).

Escaping enforcement for non-security uses

Sometimes you use a non-approved algorithm for something that isn't security: an MD5 ETag required by an external API, SHA-1 to compute a Git object ID, a checksum in a legacy file format. In only mode those calls panic.

fips140.WithoutEnforcement (Go 1.26) runs a function with enforcement switched off:

package main

import (
	"crypto/fips140"
	"crypto/md5"
	"crypto/sha256"
	"fmt"
	"io"
	"strings"
)

// etag computes an MD5 content hash used only as a cache key,
// not for security.
func etag(r io.Reader) (string, error) {
	var sum string
	var err error
	fips140.WithoutEnforcement(func() {
		h := md5.New()
		if _, err = io.Copy(h, r); err == nil {
			sum = fmt.Sprintf("%x", h.Sum(nil))
		}
	})
	return sum, err
}

func main() {
	tag, err := etag(strings.NewReader("hello"))
	fmt.Println("etag:", tag, err)
	fmt.Println("enforced after:", fips140.Enforced())

	fmt.Printf("sha256: %x\n", sha256.Sum256([]byte("hello")))
}
$ GODEBUG=fips140=only go run .
etag: 5d41402abc4b2a76b9719d911017c592 <nil>
enforced after: true
sha256: 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Rules:

Setting the mode for a program

Passing GODEBUG in the environment works for trying things out, but for a production binary you usually want the default baked in. There are three ways, from narrowest to widest.

A //go:debug directive in the main package, before the package clause:

//go:debug fips140=only

package main

import (
	"crypto/fips140"
	"fmt"
)

func main() {
	fmt.Println("enabled:", fips140.Enabled(), "enforced:", fips140.Enforced())
}
$ go run .
enabled: true enforced: true

$ GODEBUG=fips140=off go run .
enabled: false enforced: false

A godebug line in go.mod of the main module does the same for every program in the module:

module example.com/service

go 1.27

godebug fips140=only

Both set only the default. A GODEBUG environment variable at run time still overrides it, as the second run above shows. If the mode is a hard requirement, check fips140.Enabled() at startup.

The third way, GOFIPS140, also selects the module source and is described next.

Building with GOFIPS140

GOFIPS140 is read by go build, go run and go test. It accepts:

value meaning
off default: use the module source from the current toolchain, FIPS mode off by default
latest same source as off, but FIPS mode on by default
v1.Y.Z build against a frozen snapshot of the module with that version
certified, inprocess aliases for a specific snapshot version

A frozen snapshot is a copy of the module source as it was submitted for validation. The snapshots ship with the toolchain in $(go env GOROOT)/lib/fips140, and the aliases are defined by text files in the same directory. In Go 1.27 that directory has v1.0.0 and v1.26.0 snapshots, certified resolves to v1.0.0 and inprocess to v1.26.0. Your toolchain may differ: check the directory rather than relying on this list. The rest of the standard library (and the rest of your program) still comes from the current toolchain; only the module code inside crypto/internal/fips140 is swapped.

Running the status program from the first section with different values:

$ GOFIPS140=latest go run .
enabled:  true
enforced: false
version:  latest
build setting DefaultGODEBUG=fips140=on
build setting GOFIPS140=latest

$ GOFIPS140=v1.0.0 go run .
enabled:  true
enforced: false
version:  v1.0.0
build setting DefaultGODEBUG=fips140=on
build setting GOFIPS140=v1.0.0-c2097c7c

$ GOFIPS140=inprocess go run .
enabled:  true
enforced: false
version:  v1.26.0
build setting DefaultGODEBUG=fips140=on
build setting GOFIPS140=v1.26.0

Any value other than off sets the default GODEBUG to fips140=on. For only, add //go:debug fips140=only or a godebug line on top of it.

fips140.Version() returns the version as referenced in the module's security policy (v1.0.0). The exact snapshot, including a suffix that tells copies with the same version apart, is recorded in the build info as the GOFIPS140 setting. You can see it, and the build tag the toolchain adds, with go version -m:

$ GOFIPS140=v1.0.0 go build -o service.exe .
$ go version -m service.exe | grep -E "fips|GODEBUG"
	build	-tags=fips140v1.0
	build	DefaultGODEBUG=fips140=on
	build	GOFIPS140=v1.0.0-c2097c7c

An unknown value is rejected:

$ GOFIPS140=bogus go build .
go.exe: invalid GOFIPS140: must be off, latest, inprocess, certified, or v1.Y.Z

GOFIPS140 works with cross-compilation (GOOS=linux GOFIPS140=v1.0.0 go build). Set it per command or in your build script rather than with go env -w, so it doesn't silently apply to unrelated projects. See go env and go build.

A frozen snapshot is older code than the toolchain's current module. It can be missing newer algorithms and features: for example cryptotest.SetGlobalRandom, covered below, isn't supported with v1.0.0.

Deterministic crypto tests with testing/cryptotest

Since Go 1.26, functions that take a rand io.Reader parameter, such as ecdsa.GenerateKey, ecdsa.SignASN1, rsa.GenerateKey and ecdh.Curve.GenerateKey, ignore it and always use a secure source of randomness. This prevents a buggy or weak reader from compromising keys (and is required for FIPS mode, where the DRBG must be the source). GODEBUG=cryptocustomrand=1 restores the old behavior temporarily.

The downside: the old trick of passing a fixed reader to get the same key in every test run no longer works.

testing/cryptotest.SetGlobalRandom(t, seed) replaces it. For the duration of the test, crypto/rand and all implicit randomness in crypto/... packages come from a deterministic stream derived from seed.

Code under test:

package sign

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
)

// NewKey generates a P-256 signing key.
func NewKey() (*ecdsa.PrivateKey, error) {
	return ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
}

// Sign returns an ASN.1 ECDSA signature of msg.
func Sign(key *ecdsa.PrivateKey, msg []byte) ([]byte, error) {
	h := sha256.Sum256(msg)
	return ecdsa.SignASN1(rand.Reader, key, h[:])
}

Tests:

package sign

import (
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/sha256"
	"fmt"
	mrand "math/rand/v2"
	"testing"
	"testing/cryptotest"
)

func TestRandParamIgnored(t *testing.T) {
	// Two readers producing the same bytes...
	r1 := mrand.NewChaCha8([32]byte{1})
	r2 := mrand.NewChaCha8([32]byte{1})
	k1, _ := ecdsa.GenerateKey(elliptic.P256(), r1)
	k2, _ := ecdsa.GenerateKey(elliptic.P256(), r2)
	// ...still give different keys: the reader is ignored.
	fmt.Println("same key from same reader:", k1.Equal(k2))
}

func TestDeterministic(t *testing.T) {
	cryptotest.SetGlobalRandom(t, 42)
	k1, err := NewKey()
	if err != nil {
		t.Fatal(err)
	}
	sig1, _ := Sign(k1, []byte("hello"))

	cryptotest.SetGlobalRandom(t, 42) // reset the stream
	k2, _ := NewKey()
	sig2, _ := Sign(k2, []byte("hello"))

	fmt.Println("same key:      ", k1.Equal(k2))
	fmt.Println("same signature:", bytes.Equal(sig1, sig2))

	b := make([]byte, 8)
	rand.Read(b)
	fmt.Printf("rand.Read: %x\n", b)
	h := sha256.Sum256([]byte("hello"))
	fmt.Println("verifies:      ", ecdsa.VerifyASN1(&k1.PublicKey, h[:], sig1))
}
$ go test -v
=== RUN   TestRandParamIgnored
same key from same reader: false
--- PASS: TestRandParamIgnored (0.00s)
=== RUN   TestDeterministic
same key:       true
same signature: true
rand.Read: f690fc649a578c0a
verifies:       true
--- PASS: TestDeterministic (0.00s)
PASS
ok  	fipsdemo/sign	0.927s

rand.Read prints the same bytes on every run. Calling SetGlobalRandom again with the same seed resets the stream, which is why the second key and signature match the first.

Limitations:

$ GOFIPS140=v1.0.0 go test -v -run Deterministic
=== RUN   TestDeterministic
--- FAIL: TestDeterministic (0.00s)
panic: cryptotest.SetGlobalRandom is not supported when building against Go Cryptographic Module v1.0.0 [recovered, repanicked]

If you build release binaries against a frozen module but run tests with the default toolchain module, that isn't a problem. If CI also runs tests with GOFIPS140 set, skip the deterministic tests there by checking fips140.Version():

func TestDeterministicKey(t *testing.T) {
	if fips140.Version() == "v1.0.0" {
		t.Skip("SetGlobalRandom not supported with module v1.0.0")
	}
	cryptotest.SetGlobalRandom(t, 1)
	// ...
}

Checklist

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents