Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: completed hsm setup

=d819d70bc72a
diff --git a/backend-go/go.mod b/backend-go/go.mod
index 8530288079..81c1e2351e 100644
--- a/backend-go/go.mod
+++ b/backend-go/go.mod
@@ -25,6 +25,7 @@ require (
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect
github.com/DefangLabs/secret-detector v0.0.0-20250403165618-22662109213e // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
+ github.com/ThalesGroup/crypto11 v1.6.0 // indirect
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d // indirect
github.com/akhilmhdh/piccolo v0.0.1 // indirect
github.com/buger/goterm v1.0.4 // indirect
@@ -98,6 +99,7 @@ require (
github.com/mattn/go-runewidth v0.0.16 // indirect
github.com/mattn/go-shellwords v1.0.12 // indirect
github.com/mattn/go-sqlite3 v1.14.28 // indirect
+ github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
@@ -136,6 +138,7 @@ require (
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect
github.com/spf13/cobra v1.10.2 // indirect
github.com/spf13/pflag v1.0.10 // indirect
+ github.com/thales-e-security/pool v0.0.2 // indirect
github.com/tilt-dev/fsnotify v1.4.8-0.20220602155310-fff9c274a375 // indirect
github.com/tklauser/go-sysconf v0.3.16 // indirect
github.com/tklauser/numcpus v0.11.0 // indirect
diff --git a/backend-go/go.sum b/backend-go/go.sum
index 945161472a..c01db72e1b 100644
--- a/backend-go/go.sum
+++ b/backend-go/go.sum
@@ -16,6 +16,8 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERo
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
github.com/Microsoft/hcsshim v0.14.0-rc.1 h1:qAPXKwGOkVn8LlqgBN8GS0bxZ83hOJpcjxzmlQKxKsQ=
github.com/Microsoft/hcsshim v0.14.0-rc.1/go.mod h1:hTKFGbnDtQb1wHiOWv4v0eN+7boSWAHyK/tNAaYZL0c=
+github.com/ThalesGroup/crypto11 v1.6.0 h1:Og9EMn44fBS4GNnGnH1aqHnF2wL6F7IU/RhpJajWX/4=
+github.com/ThalesGroup/crypto11 v1.6.0/go.mod h1:H6LRjN5R5SHxTrLqGNteisLDI0/IC6+SGx1pHtbwizE=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
github.com/akhilmhdh/piccolo v0.0.1 h1:J8RcyL4Ab/ZTeRNbJTBiDt8AQ34cXoJDaaSFloz2+z0=
@@ -346,6 +348,8 @@ github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebG
github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A=
github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
+github.com/miekg/pkcs11 v1.1.1 h1:Ugu9pdy6vAYku5DEpVWVFPYnzV+bxB+iRdbuFSu7TvU=
+github.com/miekg/pkcs11 v1.1.1/go.mod h1:XsNlhZGX73bx86s2hdc/FuaLm2CPZJemRLMA+WTFxgs=
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
@@ -487,6 +491,8 @@ github.com/testcontainers/testcontainers-go v0.41.0 h1:mfpsD0D36YgkxGj2LrIyxuwQ9
github.com/testcontainers/testcontainers-go v0.41.0/go.mod h1:pdFrEIfaPl24zmBjerWTTYaY0M6UHsqA1YSvsoU40MI=
github.com/testcontainers/testcontainers-go/modules/compose v0.41.0 h1:6ttsQ6IilJYMoTFI2gu9l7KmKlnlY9XGkP0wtgh4rF4=
github.com/testcontainers/testcontainers-go/modules/compose v0.41.0/go.mod h1:6PfaNLXsylvZE5CID8QMZ4fWjLHORvqm1xcGBncdzAY=
+github.com/thales-e-security/pool v0.0.2 h1:RAPs4q2EbWsTit6tpzuvTFlgFRJ3S8Evf5gtvVDbmPg=
+github.com/thales-e-security/pool v0.0.2/go.mod h1:qtpMm2+thHtqhLzTwgDBj/OuNnMpupY8mv0Phz0gjhU=
github.com/theupdateframework/go-tuf v0.7.0 h1:CqbQFrWo1ae3/I0UCblSbczevCCbS31Qvs5LdxRWqRI=
github.com/theupdateframework/go-tuf/v2 v2.3.0 h1:gt3X8xT8qu/HT4w+n1jgv+p7koi5ad8XEkLXXZqG9AA=
github.com/theupdateframework/go-tuf/v2 v2.3.0/go.mod h1:xW8yNvgXRncmovMLvBxKwrKpsOwJZu/8x+aB0KtFcdw=
diff --git a/backend-go/internal/crypto/hash/hash.go b/backend-go/internal/crypto/hash/hash.go
index d6e3dc80e3..1740426069 100644
--- a/backend-go/internal/crypto/hash/hash.go
+++ b/backend-go/internal/crypto/hash/hash.go
@@ -14,6 +14,16 @@ import (
"hash"
)
+// Algorithm identifies a hash function.
+type Algorithm string
+
+const (
+ AlgoSHA1 Algorithm = "sha1"
+ AlgoSHA256 Algorithm = "sha256"
+ AlgoSHA384 Algorithm = "sha384"
+ AlgoSHA512 Algorithm = "sha512"
+)
+
// SHA256 returns the raw SHA-256 digest (32 bytes).
func SHA256(data []byte) []byte {
h := sha256.Sum256(data)
@@ -72,34 +82,32 @@ func computeHMAC(newHash func() hash.Hash, key, data []byte) []byte {
return mac.Sum(nil)
}
-// NewHasher returns a hash.Hash for the given algorithm name.
-// Supported: "sha256", "sha384", "sha512", "sha1".
-func NewHasher(algorithm string) (hash.Hash, error) {
+// NewHasher returns a hash.Hash for the given algorithm.
+func NewHasher(algorithm Algorithm) (hash.Hash, error) {
switch algorithm {
- case "sha256":
+ case AlgoSHA256:
return sha256.New(), nil
- case "sha384":
+ case AlgoSHA384:
return sha512.New384(), nil
- case "sha512":
+ case AlgoSHA512:
return sha512.New(), nil
- case "sha1":
+ case AlgoSHA1:
return sha1.New(), nil //nolint:gosec
default:
return nil, fmt.Errorf("unsupported hash algorithm: %s", algorithm)
}
}
-// NewHMAC returns an HMAC hash.Hash for the given algorithm name and key.
-// Supported: "sha256", "sha384", "sha512", "sha1".
-func NewHMAC(algorithm string, key []byte) (hash.Hash, error) {
+// NewHMAC returns an HMAC hash.Hash for the given algorithm and key.
+func NewHMAC(algorithm Algorithm, key []byte) (hash.Hash, error) {
switch algorithm {
- case "sha256":
+ case AlgoSHA256:
return hmac.New(sha256.New, key), nil
- case "sha384":
+ case AlgoSHA384:
return hmac.New(sha512.New384, key), nil
- case "sha512":
+ case AlgoSHA512:
return hmac.New(sha512.New, key), nil
- case "sha1":
+ case AlgoSHA1:
return hmac.New(sha1.New, key), nil //nolint:gosec
default:
return nil, fmt.Errorf("unsupported HMAC algorithm: %s", algorithm)
diff --git a/backend-go/internal/crypto/hash/hash_test.go b/backend-go/internal/crypto/hash/hash_test.go
index 760eb011c0..604b62094b 100644
--- a/backend-go/internal/crypto/hash/hash_test.go
+++ b/backend-go/internal/crypto/hash/hash_test.go
@@ -54,7 +54,7 @@ func TestTimingSafeEqual(t *testing.T) {
}
func TestNewHasher(t *testing.T) {
- for _, algo := range []string{"sha256", "sha384", "sha512", "sha1"} {
+ for _, algo := range []hash.Algorithm{hash.AlgoSHA256, hash.AlgoSHA384, hash.AlgoSHA512, hash.AlgoSHA1} {
h, err := hash.NewHasher(algo)
if err != nil {
t.Fatalf("NewHasher(%q): %v", algo, err)
@@ -73,7 +73,7 @@ func TestNewHasher(t *testing.T) {
func TestNewHMAC(t *testing.T) {
key := []byte("key")
- for _, algo := range []string{"sha256", "sha384", "sha512", "sha1"} {
+ for _, algo := range []hash.Algorithm{hash.AlgoSHA256, hash.AlgoSHA384, hash.AlgoSHA512, hash.AlgoSHA1} {
h, err := hash.NewHMAC(algo, key)
if err != nil {
t.Fatalf("NewHMAC(%q): %v", algo, err)
diff --git a/backend-go/internal/hsm/hsm.go b/backend-go/internal/hsm/hsm.go
new file mode 100644
index 0000000000..c961273fcc
--- /dev/null
+++ b/backend-go/internal/hsm/hsm.go
@@ -0,0 +1,341 @@
+// Package hsm provides a PKCS#11 HSM integration for encrypting/decrypting
+// the KMS root key. It wraps crypto11 for session management and key operations.
+//
+// Blob format (must match the Node.js backend):
+//
+// IV (16 bytes) || AES-CBC ciphertext (PKCS#7 padded) || HMAC-SHA256 (32 bytes)
+package hsm
+
+import (
+ "crypto/hmac"
+ "crypto/rand"
+ "errors"
+ "fmt"
+ "io"
+ "sync"
+
+ "github.com/ThalesGroup/crypto11"
+ "github.com/miekg/pkcs11"
+)
+
+const (
+ ivLength = 16
+ hmacSize = 32
+ aesKeyBits = 256
+ hmacKeyBits = 256
+)
+
+// Config holds the HSM connection parameters.
+type Config struct {
+ LibPath string
+ Slot int
+ Pin string
+ KeyLabel string
+}
+
+// Service provides HSM-backed encryption, decryption, and random byte generation.
+type Service struct {
+ ctx *crypto11.Context
+ config Config
+
+ mu sync.Mutex
+ testPassed bool
+}
+
+// NewService loads the PKCS#11 library and opens a session pool to the token.
+func NewService(cfg Config) (*Service, error) {
+ slot := cfg.Slot
+ ctx, err := crypto11.Configure(&crypto11.Config{
+ Path: cfg.LibPath,
+ SlotNumber: &slot,
+ Pin: cfg.Pin,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("HSM: configuring PKCS#11: %w", err)
+ }
+
+ return &Service{
+ ctx: ctx,
+ config: cfg,
+ }, nil
+}
+
+// Close releases all HSM resources.
+func (s *Service) Close() error {
+ if s.ctx != nil {
+ return s.ctx.Close()
+ }
+ return nil
+}
+
+// StartService ensures the required AES and HMAC keys exist on the token,
+// then runs a self-test to validate the HSM is working correctly.
+func (s *Service) StartService() error {
+ if err := s.ensureKeys(); err != nil {
+ return fmt.Errorf("HSM: ensuring keys: %w", err)
+ }
+
+ if err := s.selfTest(); err != nil {
+ return fmt.Errorf("HSM: self-test failed: %w", err)
+ }
+
+ s.mu.Lock()
+ s.testPassed = true
+ s.mu.Unlock()
+
+ return nil
+}
+
+// IsActive returns true if the HSM self-test has passed.
+func (s *Service) IsActive() bool {
+ s.mu.Lock()
+ passed := s.testPassed
+ s.mu.Unlock()
+
+ if passed {
+ return true
+ }
+
+ if err := s.selfTest(); err != nil {
+ return false
+ }
+
+ s.mu.Lock()
+ s.testPassed = true
+ s.mu.Unlock()
+
+ return true
+}
+
+// Encrypt encrypts data with the HSM AES key and appends an HMAC-SHA256.
+// Returns: IV (16) || ciphertext || HMAC (32).
+func (s *Service) Encrypt(data []byte) ([]byte, error) {
+ aesKey, err := s.findAESKey()
+ if err != nil {
+ return nil, fmt.Errorf("HSM: encryption failed, AES key not found: %w", err)
+ }
+
+ blockSize := aesKey.Cipher.BlockSize
+
+ // Generate random IV.
+ iv := make([]byte, blockSize)
+ if _, err := rand.Read(iv); err != nil {
+ return nil, fmt.Errorf("HSM: generating IV: %w", err)
+ }
+
+ // PKCS#7 pad the plaintext.
+ padded := addPKCS7Padding(data, blockSize)
+
+ // Encrypt with AES-CBC on the HSM.
+ encrypter, err := aesKey.NewCBCEncrypterCloser(iv)
+ if err != nil {
+ return nil, fmt.Errorf("HSM: creating CBC encrypter: %w", err)
+ }
+
+ ciphertext := make([]byte, len(padded))
+ encrypter.CryptBlocks(ciphertext, padded)
+ encrypter.Close()
+
+ // Compute HMAC-SHA256 over IV || ciphertext on the HSM.
+ mac, err := s.calculateHMAC(iv, ciphertext)
+ if err != nil {
+ return nil, fmt.Errorf("HSM: computing HMAC: %w", err)
+ }
+
+ // Assemble: IV || ciphertext || HMAC.
+ result := make([]byte, 0, len(iv)+len(ciphertext)+len(mac))
+ result = append(result, iv...)
+ result = append(result, ciphertext...)
+ result = append(result, mac...)
+
+ return result, nil
+}
+
+// Decrypt verifies the HMAC and decrypts a blob produced by Encrypt.
+// Expects: IV (16) || ciphertext || HMAC (32).
+func (s *Service) Decrypt(blob []byte) ([]byte, error) {
+ if len(blob) < ivLength+hmacSize+1 {
+ return nil, fmt.Errorf("HSM: encrypted blob too short")
+ }
+
+ iv := blob[:ivLength]
+ ciphertext := blob[ivLength : len(blob)-hmacSize]
+ receivedMAC := blob[len(blob)-hmacSize:]
+
+ // Verify HMAC first.
+ expectedMAC, err := s.calculateHMAC(iv, ciphertext)
+ if err != nil {
+ return nil, fmt.Errorf("HSM: decryption failed")
+ }
+
+ if !hmac.Equal(receivedMAC, expectedMAC) {
+ return nil, fmt.Errorf("HSM: decryption failed")
+ }
+
+ // Find AES key and decrypt.
+ aesKey, err := s.findAESKey()
+ if err != nil {
+ return nil, fmt.Errorf("HSM: decryption failed, AES key not found: %w", err)
+ }
+
+ decrypter, err := aesKey.NewCBCDecrypterCloser(iv)
+ if err != nil {
+ return nil, fmt.Errorf("HSM: decryption failed")
+ }
+
+ paddedPlaintext := make([]byte, len(ciphertext))
+ decrypter.CryptBlocks(paddedPlaintext, ciphertext)
+ decrypter.Close()
+
+ // Remove PKCS#7 padding.
+ plaintext, err := removePKCS7Padding(paddedPlaintext, aesKey.Cipher.BlockSize)
+ if err != nil {
+ return nil, fmt.Errorf("HSM: decryption failed")
+ }
+
+ return plaintext, nil
+}
+
+// RandomBytes generates cryptographically secure random bytes from the HSM.
+func (s *Service) RandomBytes(n int) ([]byte, error) {
+ rng, err := s.ctx.NewRandomReader()
+ if err != nil {
+ return nil, fmt.Errorf("HSM: creating random reader: %w", err)
+ }
+
+ buf := make([]byte, n)
+ if _, err := io.ReadFull(rng, buf); err != nil {
+ return nil, fmt.Errorf("HSM: reading random bytes: %w", err)
+ }
+
+ return buf, nil
+}
+
+// ensureKeys creates the AES and HMAC keys on the token if they don't already exist.
+func (s *Service) ensureKeys() error {
+ // AES key.
+ aesKey, err := s.ctx.FindKey(nil, []byte(s.config.KeyLabel))
+ if err != nil {
+ return fmt.Errorf("finding AES key: %w", err)
+ }
+ if aesKey == nil {
+ _, err = s.ctx.GenerateSecretKeyWithLabel(
+ []byte(s.config.KeyLabel),
+ []byte(s.config.KeyLabel),
+ aesKeyBits,
+ crypto11.CipherAES,
+ )
+ if err != nil {
+ return fmt.Errorf("generating AES key: %w", err)
+ }
+ }
+
+ // HMAC key.
+ hmacLabel := s.config.KeyLabel + "_HMAC"
+ hmacKey, err := s.ctx.FindKey(nil, []byte(hmacLabel))
+ if err != nil {
+ return fmt.Errorf("finding HMAC key: %w", err)
+ }
+ if hmacKey == nil {
+ _, err = s.ctx.GenerateSecretKeyWithLabel(
+ []byte(hmacLabel),
+ []byte(hmacLabel),
+ hmacKeyBits,
+ crypto11.CipherGeneric,
+ )
+ if err != nil {
+ return fmt.Errorf("generating HMAC key: %w", err)
+ }
+ }
+
+ return nil
+}
+
+// selfTest encrypts and decrypts random data to validate the HSM.
+func (s *Service) selfTest() error {
+ testData := []byte("HSM self-test: this data must survive a round-trip")
+
+ encrypted, err := s.Encrypt(testData)
+ if err != nil {
+ return fmt.Errorf("test encryption: %w", err)
+ }
+
+ decrypted, err := s.Decrypt(encrypted)
+ if err != nil {
+ return fmt.Errorf("test decryption: %w", err)
+ }
+
+ if string(testData) != string(decrypted) {
+ return errors.New("decrypted data does not match original")
+ }
+
+ return nil
+}
+
+// findAESKey locates the AES key on the token by label.
+func (s *Service) findAESKey() (*crypto11.SecretKey, error) {
+ key, err := s.ctx.FindKey(nil, []byte(s.config.KeyLabel))
+ if err != nil {
+ return nil, err
+ }
+ if key == nil {
+ return nil, fmt.Errorf("AES key with label %q not found", s.config.KeyLabel)
+ }
+ return key, nil
+}
+
+// calculateHMAC computes HMAC-SHA256 over IV || ciphertext using the HSM HMAC key.
+func (s *Service) calculateHMAC(iv, ciphertext []byte) ([]byte, error) {
+ label := s.config.KeyLabel + "_HMAC"
+ hmacKey, err := s.ctx.FindKey(nil, []byte(label))
+ if err != nil {
+ return nil, fmt.Errorf("finding HMAC key: %w", err)
+ }
+ if hmacKey == nil {
+ return nil, fmt.Errorf("HMAC key with label %q not found", label)
+ }
+
+ h, err := hmacKey.NewHMAC(pkcs11.CKM_SHA256_HMAC, 0)
+ if err != nil {
+ return nil, fmt.Errorf("creating HMAC: %w", err)
+ }
+
+ h.Write(iv)
+ h.Write(ciphertext)
+
+ return h.Sum(nil), nil
+}
+
+// addPKCS7Padding adds PKCS#7 padding to data.
+func addPKCS7Padding(data []byte, blockSize int) []byte {
+ padding := blockSize - (len(data) % blockSize)
+ padded := make([]byte, len(data)+padding)
+ copy(padded, data)
+ for i := len(data); i < len(padded); i++ {
+ padded[i] = byte(padding)
+ }
+ return padded
+}
+
+// removePKCS7Padding removes and validates PKCS#7 padding.
+func removePKCS7Padding(data []byte, blockSize int) ([]byte, error) {
+ if len(data) == 0 {
+ return nil, errors.New("cannot remove padding from empty data")
+ }
+ if len(data)%blockSize != 0 {
+ return nil, errors.New("data length is not a multiple of block size")
+ }
+
+ paddingLen := int(data[len(data)-1])
+ if paddingLen == 0 || paddingLen > blockSize || paddingLen > len(data) {
+ return nil, fmt.Errorf("invalid padding length: %d", paddingLen)
+ }
+
+ for i := len(data) - paddingLen; i < len(data); i++ {
+ if data[i] != byte(paddingLen) {
+ return nil, fmt.Errorf("invalid padding byte at position %d", i)
+ }
+ }
+
+ return data[:len(data)-paddingLen], nil
+}
diff --git a/backend-go/internal/hsm/hsm_test.go b/backend-go/internal/hsm/hsm_test.go
new file mode 100644
index 0000000000..bd9f85aefa
--- /dev/null
+++ b/backend-go/internal/hsm/hsm_test.go
@@ -0,0 +1,177 @@
+package hsm_test
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "github.com/infisical/api/internal/hsm"
+)
+
+// setupHSM initializes a SoftHSM2 token and returns a ready HSM service.
+// Skips the test if SOFTHSM2_LIB is not set.
+func setupHSM(t *testing.T) *hsm.Service {
+ t.Helper()
+
+ libPath := os.Getenv("SOFTHSM2_LIB")
+ if libPath == "" {
+ t.Skip("Skipping HSM tests: SOFTHSM2_LIB environment variable not set. Set it to the path of libsofthsm2.so to enable HSM tests.")
+ }
+
+ if _, err := exec.LookPath("softhsm2-util"); err != nil {
+ t.Skip("Skipping HSM tests: softhsm2-util not found in PATH")
+ }
+
+ tokenDir := t.TempDir()
+ confPath := filepath.Join(tokenDir, "softhsm2.conf")
+ require.NoError(t, os.WriteFile(confPath, []byte(
+ "directories.tokendir = "+tokenDir+"\nobjectstore.backend = file\n",
+ ), 0644))
+ t.Setenv("SOFTHSM2_CONF", confPath)
+
+ cmd := exec.Command("softhsm2-util",
+ "--init-token", "--free",
+ "--label", "test-token",
+ "--pin", "1234", "--so-pin", "5678",
+ )
+ cmd.Env = append(os.Environ(), "SOFTHSM2_CONF="+confPath)
+ out, err := cmd.CombinedOutput()
+ require.NoError(t, err, "softhsm2-util: "+string(out))
+
+ svc, err := hsm.NewService(hsm.Config{
+ LibPath: libPath,
+ Slot: 0,
+ Pin: "1234",
+ KeyLabel: "test-infisical",
+ })
+ require.NoError(t, err)
+ t.Cleanup(func() { svc.Close() })
+
+ require.NoError(t, svc.StartService())
+
+ return svc
+}
+
+func TestStartServiceAndIsActive(t *testing.T) {
+ svc := setupHSM(t)
+ assert.True(t, svc.IsActive())
+}
+
+func TestEncryptDecryptRoundTrip(t *testing.T) {
+ svc := setupHSM(t)
+
+ plaintext := []byte("hello from the HSM")
+
+ blob, err := svc.Encrypt(plaintext)
+ require.NoError(t, err)
+
+ // Verify blob structure: IV(16) + at least one padded block(16) + HMAC(32).
+ assert.GreaterOrEqual(t, len(blob), 16+16+32)
+
+ got, err := svc.Decrypt(blob)
+ require.NoError(t, err)
+ assert.Equal(t, plaintext, got)
+}
+
+func TestEncryptDecryptEmptyData(t *testing.T) {
+ svc := setupHSM(t)
+
+ blob, err := svc.Encrypt([]byte{})
+ require.NoError(t, err)
+
+ got, err := svc.Decrypt(blob)
+ require.NoError(t, err)
+ assert.Equal(t, []byte{}, got)
+}
+
+func TestEncryptDecryptLargeData(t *testing.T) {
+ svc := setupHSM(t)
+
+ plaintext := make([]byte, 500)
+ for i := range plaintext {
+ plaintext[i] = byte(i % 256)
+ }
+
+ blob, err := svc.Encrypt(plaintext)
+ require.NoError(t, err)
+
+ got, err := svc.Decrypt(blob)
+ require.NoError(t, err)
+ assert.Equal(t, plaintext, got)
+}
+
+func TestDecryptTamperedHMAC(t *testing.T) {
+ svc := setupHSM(t)
+
+ blob, err := svc.Encrypt([]byte("tamper test"))
+ require.NoError(t, err)
+
+ // Flip a byte in the HMAC region (last 32 bytes).
+ blob[len(blob)-1] ^= 0xFF
+
+ _, err = svc.Decrypt(blob)
+ assert.Error(t, err)
+}
+
+func TestDecryptTamperedCiphertext(t *testing.T) {
+ svc := setupHSM(t)
+
+ blob, err := svc.Encrypt([]byte("tamper ciphertext"))
+ require.NoError(t, err)
+
+ // Flip a byte in the ciphertext region (after IV, before HMAC).
+ blob[20] ^= 0xFF
+
+ _, err = svc.Decrypt(blob)
+ assert.Error(t, err)
+}
+
+func TestDecryptTamperedIV(t *testing.T) {
+ svc := setupHSM(t)
+
+ blob, err := svc.Encrypt([]byte("tamper iv"))
+ require.NoError(t, err)
+
+ // Flip a byte in the IV region.
+ blob[0] ^= 0xFF
+
+ _, err = svc.Decrypt(blob)
+ assert.Error(t, err)
+}
+
+func TestDecryptTooShort(t *testing.T) {
+ svc := setupHSM(t)
+
+ _, err := svc.Decrypt([]byte("short"))
+ assert.Error(t, err)
+}
+
+func TestRandomBytes(t *testing.T) {
+ svc := setupHSM(t)
+
+ a, err := svc.RandomBytes(32)
+ require.NoError(t, err)
+ assert.Len(t, a, 32)
+
+ b, err := svc.RandomBytes(32)
+ require.NoError(t, err)
+ assert.Len(t, b, 32)
+
+ assert.NotEqual(t, a, b)
+}
+
+func TestEncryptProducesDifferentBlobs(t *testing.T) {
+ svc := setupHSM(t)
+
+ blob1, err := svc.Encrypt([]byte("same"))
+ require.NoError(t, err)
+
+ blob2, err := svc.Encrypt([]byte("same"))
+ require.NoError(t, err)
+
+ assert.NotEqual(t, blob1, blob2, "two encryptions of same data should differ due to random IV")
+}