Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: added crypto module
=709b5b70681e
diff --git a/backend-go/internal/crypto/cipher/cipher.go b/backend-go/internal/crypto/cipher/cipher.gonew file mode 100644index 0000000000..ee50963d31--- /dev/null+++ b/backend-go/internal/crypto/cipher/cipher.go@@ -0,0 +1,64 @@+package cipher++import (+ "crypto/aes"+ gocipher "crypto/cipher"+ "crypto/rand"+ "fmt"+ "io"+)++const (+ ivLength = 12+ tagLength = 16+)++// SymmetricEncrypt encrypts plaintext with a 128-bit or 256-bit AES key using AES-GCM.+// Returns a single blob: IV (12) || ciphertext || GCM auth tag (16).+func SymmetricEncrypt(plaintext, key []byte) ([]byte, error) {+ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, fmt.Errorf("creating AES cipher: %w", err)+ }++ gcm, err := gocipher.NewGCM(block)+ if err != nil {+ return nil, fmt.Errorf("creating GCM: %w", err)+ }++ iv := make([]byte, ivLength)+ if _, err := io.ReadFull(rand.Reader, iv); err != nil {+ return nil, fmt.Errorf("generating IV: %w", err)+ }++ // Seal appends ciphertext + GCM tag after the IV prefix.+ return gcm.Seal(iv, iv, plaintext, nil), nil+}++// SymmetricDecrypt decrypts a blob produced by Encrypt.+// Expects: IV (12) || ciphertext || GCM auth tag (16).+func SymmetricDecrypt(blob, key []byte) ([]byte, error) {+ if len(blob) < ivLength+tagLength {+ return nil, fmt.Errorf("ciphertext too short: need at least %d bytes, got %d", ivLength+tagLength, len(blob))+ }++ block, err := aes.NewCipher(key)+ if err != nil {+ return nil, fmt.Errorf("creating AES cipher: %w", err)+ }++ gcm, err := gocipher.NewGCM(block)+ if err != nil {+ return nil, fmt.Errorf("creating GCM: %w", err)+ }++ iv := blob[:ivLength]+ ciphertext := blob[ivLength:]++ plaintext, err := gcm.Open(nil, iv, ciphertext, nil)+ if err != nil {+ return nil, fmt.Errorf("decrypting: %w", err)+ }++ return plaintext, nil+}diff --git a/backend-go/internal/crypto/cipher/cipher_test.go b/backend-go/internal/crypto/cipher/cipher_test.gonew file mode 100644index 0000000000..00315a5200--- /dev/null+++ b/backend-go/internal/crypto/cipher/cipher_test.go@@ -0,0 +1,94 @@+package cipher_test++import (+ "bytes"+ "crypto/rand"+ "testing"++ "github.com/infisical/api/internal/crypto/cipher"+)++func TestEncryptDecryptRoundTrip(t *testing.T) {+ key := make([]byte, 32) // AES-256+ if _, err := rand.Read(key); err != nil {+ t.Fatal(err)+ }++ plaintext := []byte("hello infisical")++ blob, err := cipher.SymmetricEncrypt(plaintext, key)+ if err != nil {+ t.Fatalf("Encrypt: %v", err)+ }++ // Blob must be longer than plaintext (12 IV + 16 tag overhead).+ if len(blob) != 12+len(plaintext)+16 {+ t.Fatalf("unexpected blob length: got %d, want %d", len(blob), 12+len(plaintext)+16)+ }++ got, err := cipher.SymmetricDecrypt(blob, key)+ if err != nil {+ t.Fatalf("Decrypt: %v", err)+ }++ if !bytes.Equal(got, plaintext) {+ t.Fatalf("round-trip mismatch: got %q, want %q", got, plaintext)+ }+}++func TestDecryptWrongKey(t *testing.T) {+ key1 := make([]byte, 32)+ key2 := make([]byte, 32)+ rand.Read(key1)+ rand.Read(key2)++ blob, err := cipher.SymmetricEncrypt([]byte("secret"), key1)+ if err != nil {+ t.Fatal(err)+ }++ _, err = cipher.SymmetricDecrypt(blob, key2)+ if err == nil {+ t.Fatal("expected decryption to fail with wrong key")+ }+}++func TestDecryptTooShort(t *testing.T) {+ _, err := cipher.SymmetricDecrypt([]byte("short"), make([]byte, 32))+ if err == nil {+ t.Fatal("expected error for short ciphertext")+ }+}++func TestEncryptProducesDifferentBlobs(t *testing.T) {+ key := make([]byte, 32)+ rand.Read(key)++ blob1, _ := cipher.SymmetricEncrypt([]byte("same"), key)+ blob2, _ := cipher.SymmetricEncrypt([]byte("same"), key)++ if bytes.Equal(blob1, blob2) {+ t.Fatal("two encryptions of the same plaintext should differ (random IV)")+ }+}++func TestAES128Key(t *testing.T) {+ key := make([]byte, 16) // AES-128+ rand.Read(key)++ plaintext := []byte("128-bit key test")++ blob, err := cipher.SymmetricEncrypt(plaintext, key)+ if err != nil {+ t.Fatalf("Encrypt with 128-bit key: %v", err)+ }++ got, err := cipher.SymmetricDecrypt(blob, key)+ if err != nil {+ t.Fatalf("Decrypt with 128-bit key: %v", err)+ }++ if !bytes.Equal(got, plaintext) {+ t.Fatalf("round-trip mismatch: got %q, want %q", got, plaintext)+ }+}diff --git a/backend-go/internal/crypto/hash/hash.go b/backend-go/internal/crypto/hash/hash.gonew file mode 100644index 0000000000..d6e3dc80e3--- /dev/null+++ b/backend-go/internal/crypto/hash/hash.go@@ -0,0 +1,107 @@+// Package hash provides cryptographic hash and HMAC functions used across+// the Infisical backend: SHA-256, SHA-1, HMAC-SHA-256, HMAC-SHA-1, and+// constant-time comparison.+package hash++import (+ "crypto/hmac"+ "crypto/sha1" //nolint:gosec // SHA-1 needed for certificate fingerprints and legacy compatibility+ "crypto/sha256"+ "crypto/sha512"+ "crypto/subtle"+ "encoding/hex"+ "fmt"+ "hash"+)++// SHA256 returns the raw SHA-256 digest (32 bytes).+func SHA256(data []byte) []byte {+ h := sha256.Sum256(data)+ return h[:]+}++// SHA256Hex returns the hex-encoded SHA-256 digest.+func SHA256Hex(data []byte) string {+ return hex.EncodeToString(SHA256(data))+}++// SHA1 returns the raw SHA-1 digest (20 bytes).+// Use only where required for compatibility (e.g. certificate fingerprints).+func SHA1(data []byte) []byte {+ h := sha1.Sum(data) //nolint:gosec+ return h[:]+}++// SHA1Hex returns the hex-encoded SHA-1 digest.+func SHA1Hex(data []byte) string {+ return hex.EncodeToString(SHA1(data))+}++// SHA384 returns the raw SHA-384 digest (48 bytes).+func SHA384(data []byte) []byte {+ h := sha512.Sum384(data)+ return h[:]+}++// SHA512 returns the raw SHA-512 digest (64 bytes).+func SHA512Bytes(data []byte) []byte {+ h := sha512.Sum512(data)+ return h[:]+}++// HMACSHA256 computes HMAC-SHA-256.+func HMACSHA256(key, data []byte) []byte {+ return computeHMAC(sha256.New, key, data)+}++// HMACSHA1 computes HMAC-SHA-1.+// Use only where required for protocol compatibility.+func HMACSHA1(key, data []byte) []byte {+ return computeHMAC(sha1.New, key, data) //nolint:gosec+}++// TimingSafeEqual performs constant-time comparison of two byte slices.+// Returns true only if a and b have the same length and identical contents.+func TimingSafeEqual(a, b []byte) bool {+ return subtle.ConstantTimeCompare(a, b) == 1+}++func computeHMAC(newHash func() hash.Hash, key, data []byte) []byte {+ mac := hmac.New(newHash, key)+ mac.Write(data)+ 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) {+ switch algorithm {+ case "sha256":+ return sha256.New(), nil+ case "sha384":+ return sha512.New384(), nil+ case "sha512":+ return sha512.New(), nil+ case "sha1":+ 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) {+ switch algorithm {+ case "sha256":+ return hmac.New(sha256.New, key), nil+ case "sha384":+ return hmac.New(sha512.New384, key), nil+ case "sha512":+ return hmac.New(sha512.New, key), nil+ case "sha1":+ 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.gonew file mode 100644index 0000000000..760eb011c0--- /dev/null+++ b/backend-go/internal/crypto/hash/hash_test.go@@ -0,0 +1,86 @@+package hash_test++import (+ "encoding/hex"+ "testing"++ "github.com/infisical/api/internal/crypto/hash"+)++func TestSHA256Hex(t *testing.T) {+ // echo -n "hello" | sha256sum+ want := "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"+ got := hash.SHA256Hex([]byte("hello"))+ if got != want {+ t.Fatalf("SHA256Hex(\"hello\") = %s, want %s", got, want)+ }+}++func TestSHA1Hex(t *testing.T) {+ // echo -n "hello" | sha1sum+ want := "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"+ got := hash.SHA1Hex([]byte("hello"))+ if got != want {+ t.Fatalf("SHA1Hex(\"hello\") = %s, want %s", got, want)+ }+}++func TestHMACSHA256(t *testing.T) {+ key := []byte("secret")+ data := []byte("hello")+ got := hex.EncodeToString(hash.HMACSHA256(key, data))+ // python3 -c "import hmac,hashlib; print(hmac.new(b'secret',b'hello',hashlib.sha256).hexdigest())"+ want := "88aab3ede8d3adf94d26ab90d3bafd4a2083070c3bcce9c014ee04a443847c0b"+ if got != want {+ t.Fatalf("HMACSHA256 = %s, want %s", got, want)+ }+}++func TestTimingSafeEqual(t *testing.T) {+ a := []byte("same")+ b := []byte("same")+ c := []byte("diff")+ d := []byte("longer")++ if !hash.TimingSafeEqual(a, b) {+ t.Fatal("expected equal slices to match")+ }+ if hash.TimingSafeEqual(a, c) {+ t.Fatal("expected different slices to not match")+ }+ if hash.TimingSafeEqual(a, d) {+ t.Fatal("expected different-length slices to not match")+ }+}++func TestNewHasher(t *testing.T) {+ for _, algo := range []string{"sha256", "sha384", "sha512", "sha1"} {+ h, err := hash.NewHasher(algo)+ if err != nil {+ t.Fatalf("NewHasher(%q): %v", algo, err)+ }+ h.Write([]byte("test"))+ if len(h.Sum(nil)) == 0 {+ t.Fatalf("NewHasher(%q) produced empty digest", algo)+ }+ }++ _, err := hash.NewHasher("md5")+ if err == nil {+ t.Fatal("expected error for unsupported algorithm")+ }+}++func TestNewHMAC(t *testing.T) {+ key := []byte("key")+ for _, algo := range []string{"sha256", "sha384", "sha512", "sha1"} {+ h, err := hash.NewHMAC(algo, key)+ if err != nil {+ t.Fatalf("NewHMAC(%q): %v", algo, err)+ }+ h.Write([]byte("test"))+ if len(h.Sum(nil)) == 0 {+ t.Fatalf("NewHMAC(%q) produced empty digest", algo)+ }+ }+}diff --git a/backend-go/internal/crypto/sign/sign.go b/backend-go/internal/crypto/sign/sign.gonew file mode 100644index 0000000000..27c6fee31e--- /dev/null+++ b/backend-go/internal/crypto/sign/sign.go@@ -0,0 +1,269 @@+// Package sign provides asymmetric key generation, signing, and verification+// for the KMS service. It supports RSA-4096 and ECC P-256 keys with multiple+// signing algorithms (RSA-PSS, RSA PKCS#1 v1.5, ECDSA).+//+// All key formats match the Node.js backend:+// - Private keys: PEM-encoded PKCS#8+// - Public keys: DER-encoded SPKI+package sign++import (+ "crypto"+ "crypto/ecdsa"+ "crypto/elliptic"+ "crypto/rand"+ "crypto/rsa"+ "crypto/sha256"+ "crypto/sha512"+ "crypto/x509"+ "encoding/pem"+ "fmt"+ "hash"+ "strings"+)++// Algorithm identifies a key type.+type Algorithm string++const (+ RSA4096 Algorithm = "RSA_4096"+ ECCP256 Algorithm = "ECC_NIST_P256"+)++// SigningAlgorithm identifies a signing scheme.+type SigningAlgorithm string++const (+ RSASSA_PSS_SHA256 SigningAlgorithm = "RSASSA_PSS_SHA_256"+ RSASSA_PSS_SHA384 SigningAlgorithm = "RSASSA_PSS_SHA_384"+ RSASSA_PSS_SHA512 SigningAlgorithm = "RSASSA_PSS_SHA_512"+ RSASSA_PKCS1_V1_5_SHA256 SigningAlgorithm = "RSASSA_PKCS1_V1_5_SHA_256"+ RSASSA_PKCS1_V1_5_SHA384 SigningAlgorithm = "RSASSA_PKCS1_V1_5_SHA_384"+ RSASSA_PKCS1_V1_5_SHA512 SigningAlgorithm = "RSASSA_PKCS1_V1_5_SHA_512"+ ECDSA_SHA256 SigningAlgorithm = "ECDSA_SHA_256"+ ECDSA_SHA384 SigningAlgorithm = "ECDSA_SHA_384"+ ECDSA_SHA512 SigningAlgorithm = "ECDSA_SHA_512"+)++// signingParams maps a SigningAlgorithm to its crypto.Hash and optional PSS salt length.+type signingParams struct {+ hash crypto.Hash+ newHash func() hash.Hash+ digestLen int+ isPSS bool+ saltLength int+}++var paramsMap = map[SigningAlgorithm]signingParams{+ RSASSA_PSS_SHA256: {hash: crypto.SHA256, newHash: sha256.New, digestLen: sha256.Size, isPSS: true, saltLength: sha256.Size},+ RSASSA_PSS_SHA384: {hash: crypto.SHA384, newHash: sha512.New384, digestLen: sha512.Size384, isPSS: true, saltLength: sha512.Size384},+ RSASSA_PSS_SHA512: {hash: crypto.SHA512, newHash: sha512.New, digestLen: sha512.Size, isPSS: true, saltLength: sha512.Size},+ RSASSA_PKCS1_V1_5_SHA256: {hash: crypto.SHA256, newHash: sha256.New, digestLen: sha256.Size},+ RSASSA_PKCS1_V1_5_SHA384: {hash: crypto.SHA384, newHash: sha512.New384, digestLen: sha512.Size384},+ RSASSA_PKCS1_V1_5_SHA512: {hash: crypto.SHA512, newHash: sha512.New, digestLen: sha512.Size},+ ECDSA_SHA256: {hash: crypto.SHA256, newHash: sha256.New, digestLen: sha256.Size},+ ECDSA_SHA384: {hash: crypto.SHA384, newHash: sha512.New384, digestLen: sha512.Size384},+ ECDSA_SHA512: {hash: crypto.SHA512, newHash: sha512.New, digestLen: sha512.Size},+}++// GeneratePrivateKey generates a new private key for the given algorithm.+// Returns the private key as PEM-encoded PKCS#8.+func GeneratePrivateKey(algo Algorithm) ([]byte, error) {+ var privKey crypto.PrivateKey+ var err error++ switch algo {+ case RSA4096:+ privKey, err = rsa.GenerateKey(rand.Reader, 4096)+ case ECCP256:+ privKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)+ default:+ return nil, fmt.Errorf("unsupported key algorithm: %s", algo)+ }+ if err != nil {+ return nil, fmt.Errorf("generating %s key: %w", algo, err)+ }++ return marshalPrivateKeyPEM(privKey)+}++// PublicKeyFromPrivate extracts the public key from a PEM-encoded PKCS#8 private key.+// Returns the public key as DER-encoded SPKI (matching the Node.js format).+func PublicKeyFromPrivate(privateKeyPEM []byte) ([]byte, error) {+ privKey, err := parsePrivateKeyPEM(privateKeyPEM)+ if err != nil {+ return nil, err+ }++ var pubKey crypto.PublicKey+ switch k := privKey.(type) {+ case *rsa.PrivateKey:+ pubKey = &k.PublicKey+ case *ecdsa.PrivateKey:+ pubKey = &k.PublicKey+ default:+ return nil, fmt.Errorf("unsupported private key type: %T", privKey)+ }++ der, err := x509.MarshalPKIXPublicKey(pubKey)+ if err != nil {+ return nil, fmt.Errorf("marshaling public key to DER: %w", err)+ }++ return der, nil+}++// Sign signs data with a PEM-encoded PKCS#8 private key.+//+// If isDigest is true, data is treated as a pre-computed hash digest and signed+// directly (without hashing again). RSA-PSS does not support pre-digested input.+//+// ECDSA signatures are DER-encoded (ASN.1), matching the Node.js output.+func Sign(data, privateKeyPEM []byte, algo SigningAlgorithm, isDigest bool) ([]byte, error) {+ if err := validateAlgorithmWithKey(algo, privateKeyPEM); err != nil {+ return nil, err+ }++ params, ok := paramsMap[algo]+ if !ok {+ return nil, fmt.Errorf("unsupported signing algorithm: %s", algo)+ }++ privKey, err := parsePrivateKeyPEM(privateKeyPEM)+ if err != nil {+ return nil, err+ }++ var digest []byte+ if isDigest {+ if params.isPSS {+ return nil, fmt.Errorf("RSA-PSS does not support pre-digested input")+ }+ digest = data+ } else {+ h := params.newHash()+ h.Write(data)+ digest = h.Sum(nil)+ }++ switch k := privKey.(type) {+ case *rsa.PrivateKey:+ if params.isPSS {+ return rsa.SignPSS(rand.Reader, k, params.hash, digest, &rsa.PSSOptions{+ SaltLength: params.saltLength,+ })+ }+ return rsa.SignPKCS1v15(rand.Reader, k, params.hash, digest)++ case *ecdsa.PrivateKey:+ // ecdsa.SignASN1 produces DER-encoded signatures matching Node.js dsaEncoding: "der".+ return ecdsa.SignASN1(rand.Reader, k, digest)++ default:+ return nil, fmt.Errorf("unsupported private key type for signing: %T", privKey)+ }+}++// Verify verifies a signature against data using a DER-encoded SPKI public key.+//+// If isDigest is true, data is treated as a pre-computed hash digest.+// RSA-PSS does not support pre-digested input.+func Verify(data, signature, publicKeyDER []byte, algo SigningAlgorithm, isDigest bool) (bool, error) {+ params, ok := paramsMap[algo]+ if !ok {+ return false, fmt.Errorf("unsupported signing algorithm: %s", algo)+ }++ if isDigest && params.isPSS {+ return false, fmt.Errorf("RSA-PSS does not support pre-digested input")+ }++ pubKeyRaw, err := x509.ParsePKIXPublicKey(publicKeyDER)+ if err != nil {+ return false, fmt.Errorf("parsing public key DER: %w", err)+ }++ var digest []byte+ if isDigest {+ digest = data+ } else {+ h := params.newHash()+ h.Write(data)+ digest = h.Sum(nil)+ }++ switch pubKey := pubKeyRaw.(type) {+ case *rsa.PublicKey:+ if params.isPSS {+ err = rsa.VerifyPSS(pubKey, params.hash, digest, signature, &rsa.PSSOptions{+ SaltLength: params.saltLength,+ })+ } else {+ err = rsa.VerifyPKCS1v15(pubKey, params.hash, digest, signature)+ }+ if err != nil {+ return false, nil+ }+ return true, nil++ case *ecdsa.PublicKey:+ return ecdsa.VerifyASN1(pubKey, digest, signature), nil++ default:+ return false, fmt.Errorf("unsupported public key type for verification: %T", pubKeyRaw)+ }+}++// parsePrivateKeyPEM decodes a PEM block and parses a PKCS#8 private key.+func parsePrivateKeyPEM(pemData []byte) (crypto.PrivateKey, error) {+ block, _ := pem.Decode(pemData)+ if block == nil {+ return nil, fmt.Errorf("no PEM block found in private key")+ }++ key, err := x509.ParsePKCS8PrivateKey(block.Bytes)+ if err != nil {+ return nil, fmt.Errorf("parsing PKCS#8 private key: %w", err)+ }++ return key, nil+}++// marshalPrivateKeyPEM marshals a private key to PEM-encoded PKCS#8.+func marshalPrivateKeyPEM(key crypto.PrivateKey) ([]byte, error) {+ der, err := x509.MarshalPKCS8PrivateKey(key)+ if err != nil {+ return nil, fmt.Errorf("marshaling private key to PKCS#8: %w", err)+ }++ return pem.EncodeToMemory(&pem.Block{+ Type: "PRIVATE KEY",+ Bytes: der,+ }), nil+}++// validateAlgorithmWithKey checks that the signing algorithm is compatible+// with the key type encoded in the PEM.+func validateAlgorithmWithKey(algo SigningAlgorithm, privateKeyPEM []byte) error {+ privKey, err := parsePrivateKeyPEM(privateKeyPEM)+ if err != nil {+ return err+ }++ algoStr := string(algo)+ isRSAAlgo := strings.HasPrefix(algoStr, "RSASSA")+ isECDSAAlgo := strings.HasPrefix(algoStr, "ECDSA")++ switch privKey.(type) {+ case *rsa.PrivateKey:+ if !isRSAAlgo {+ return fmt.Errorf("RSA key cannot be used with %s", algo)+ }+ case *ecdsa.PrivateKey:+ if !isECDSAAlgo {+ return fmt.Errorf("ECC key cannot be used with %s", algo)+ }+ }++ return nil+}diff --git a/backend-go/internal/crypto/sign/sign_test.go b/backend-go/internal/crypto/sign/sign_test.gonew file mode 100644index 0000000000..cf831807bd--- /dev/null+++ b/backend-go/internal/crypto/sign/sign_test.go@@ -0,0 +1,187 @@+package sign_test++import (+ "testing"++ "github.com/infisical/api/internal/crypto/sign"+)++func TestRSAGenerateAndPublicKey(t *testing.T) {+ privPEM, err := sign.GeneratePrivateKey(sign.RSA4096)+ if err != nil {+ t.Fatalf("GeneratePrivateKey(RSA4096): %v", err)+ }++ pubDER, err := sign.PublicKeyFromPrivate(privPEM)+ if err != nil {+ t.Fatalf("PublicKeyFromPrivate: %v", err)+ }++ if len(pubDER) == 0 {+ t.Fatal("public key DER is empty")+ }+}++func TestECCGenerateAndPublicKey(t *testing.T) {+ privPEM, err := sign.GeneratePrivateKey(sign.ECCP256)+ if err != nil {+ t.Fatalf("GeneratePrivateKey(ECCP256): %v", err)+ }++ pubDER, err := sign.PublicKeyFromPrivate(privPEM)+ if err != nil {+ t.Fatalf("PublicKeyFromPrivate: %v", err)+ }++ if len(pubDER) == 0 {+ t.Fatal("public key DER is empty")+ }+}++func TestRSAPKCS1SignVerify(t *testing.T) {+ privPEM, _ := sign.GeneratePrivateKey(sign.RSA4096)+ pubDER, _ := sign.PublicKeyFromPrivate(privPEM)+ data := []byte("hello KMS")++ for _, algo := range []sign.SigningAlgorithm{+ sign.RSASSA_PKCS1_V1_5_SHA256,+ sign.RSASSA_PKCS1_V1_5_SHA384,+ sign.RSASSA_PKCS1_V1_5_SHA512,+ } {+ sig, err := sign.Sign(data, privPEM, algo, false)+ if err != nil {+ t.Fatalf("Sign(%s): %v", algo, err)+ }++ ok, err := sign.Verify(data, sig, pubDER, algo, false)+ if err != nil {+ t.Fatalf("Verify(%s): %v", algo, err)+ }+ if !ok {+ t.Fatalf("Verify(%s) returned false", algo)+ }++ // Wrong data should fail.+ ok, err = sign.Verify([]byte("wrong"), sig, pubDER, algo, false)+ if err != nil {+ t.Fatalf("Verify(%s) with wrong data: %v", algo, err)+ }+ if ok {+ t.Fatalf("Verify(%s) should have returned false for wrong data", algo)+ }+ }+}++func TestRSAPSSSignVerify(t *testing.T) {+ privPEM, _ := sign.GeneratePrivateKey(sign.RSA4096)+ pubDER, _ := sign.PublicKeyFromPrivate(privPEM)+ data := []byte("PSS test")++ for _, algo := range []sign.SigningAlgorithm{+ sign.RSASSA_PSS_SHA256,+ sign.RSASSA_PSS_SHA384,+ sign.RSASSA_PSS_SHA512,+ } {+ sig, err := sign.Sign(data, privPEM, algo, false)+ if err != nil {+ t.Fatalf("Sign(%s): %v", algo, err)+ }++ ok, err := sign.Verify(data, sig, pubDER, algo, false)+ if err != nil {+ t.Fatalf("Verify(%s): %v", algo, err)+ }+ if !ok {+ t.Fatalf("Verify(%s) returned false", algo)+ }+ }+}++func TestRSAPSSRejectsDigest(t *testing.T) {+ privPEM, _ := sign.GeneratePrivateKey(sign.RSA4096)++ _, err := sign.Sign([]byte("data"), privPEM, sign.RSASSA_PSS_SHA256, true)+ if err == nil {+ t.Fatal("expected RSA-PSS to reject isDigest=true")+ }+}++func TestECDSASignVerify(t *testing.T) {+ privPEM, _ := sign.GeneratePrivateKey(sign.ECCP256)+ pubDER, _ := sign.PublicKeyFromPrivate(privPEM)+ data := []byte("ECDSA test")++ for _, algo := range []sign.SigningAlgorithm{+ sign.ECDSA_SHA256,+ sign.ECDSA_SHA384,+ sign.ECDSA_SHA512,+ } {+ sig, err := sign.Sign(data, privPEM, algo, false)+ if err != nil {+ t.Fatalf("Sign(%s): %v", algo, err)+ }++ ok, err := sign.Verify(data, sig, pubDER, algo, false)+ if err != nil {+ t.Fatalf("Verify(%s): %v", algo, err)+ }+ if !ok {+ t.Fatalf("Verify(%s) returned false", algo)+ }+ }+}++func TestAlgorithmKeyMismatch(t *testing.T) {+ rsaKey, _ := sign.GeneratePrivateKey(sign.RSA4096)+ ecKey, _ := sign.GeneratePrivateKey(sign.ECCP256)++ // RSA key with ECDSA algorithm.+ _, err := sign.Sign([]byte("data"), rsaKey, sign.ECDSA_SHA256, false)+ if err == nil {+ t.Fatal("expected error for RSA key with ECDSA algorithm")+ }++ // ECC key with RSA algorithm.+ _, err = sign.Sign([]byte("data"), ecKey, sign.RSASSA_PKCS1_V1_5_SHA256, false)+ if err == nil {+ t.Fatal("expected error for ECC key with RSA algorithm")+ }+}++func TestDigestSignVerify(t *testing.T) {+ privPEM, _ := sign.GeneratePrivateKey(sign.RSA4096)+ pubDER, _ := sign.PublicKeyFromPrivate(privPEM)++ // Pre-compute a SHA-256 digest (32 bytes).+ digest := make([]byte, 32)+ copy(digest, "this is a 32 byte fake digest!..")++ sig, err := sign.Sign(digest, privPEM, sign.RSASSA_PKCS1_V1_5_SHA256, true)+ if err != nil {+ t.Fatalf("Sign with digest: %v", err)+ }++ ok, err := sign.Verify(digest, sig, pubDER, sign.RSASSA_PKCS1_V1_5_SHA256, true)+ if err != nil {+ t.Fatalf("Verify with digest: %v", err)+ }+ if !ok {+ t.Fatal("Verify with digest returned false")+ }+}++func TestUnsupportedAlgorithm(t *testing.T) {+ privPEM, _ := sign.GeneratePrivateKey(sign.RSA4096)++ _, err := sign.Sign([]byte("data"), privPEM, "INVALID_ALGO", false)+ if err == nil {+ t.Fatal("expected error for unsupported algorithm")+ }+}++func TestUnsupportedKeyAlgorithm(t *testing.T) {+ _, err := sign.GeneratePrivateKey("DSA_2048")+ if err == nil {+ t.Fatal("expected error for unsupported key algorithm")+ }+}