{"record":{"id":"51af4a06f71abb3b","repo":"siyuan-note/siyuan","slug":"requires-a-32-byte-aes-256-key","errorCode":null,"errorMessage":" requires a 32-byte (AES-256) key","messagePattern":" requires a 32-byte \\(AES-256\\) key","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"kernel/util/kdf.go","lineNumber":151,"sourceCode":"\treturn out\n}\n\n// EncryptWithAAD 用 AES-256-GCM 加密并绑定 AAD（附加认证数据）。\n// AAD 不被加密，但参与 GCM 认证——解密时必须提供相同 AAD，否则认证失败。\n// 把用途/boxID/路径等元数据放入 AAD，可防止同 box 内密文被替换用途或路径（bind 到上下文）。\n// 返回格式与 Encrypt 一致，但 AAD 参与校验。\nfunc EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error) {\n\treturn encryptGCM(key, plaintext, aad, \"EncryptWithAAD\")\n}\n\n// DecryptWithAAD 对应 EncryptWithAAD 的解密。格式无效、AAD 不匹配或密文被篡改时返回错误。\nfunc DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error) {\n\treturn decryptGCM(key, ciphertext, aad, \"DecryptWithAAD\")\n}\n\nfunc encryptGCM(key, plaintext, aad []byte, operation string) ([]byte, error) {\n\tif len(key) != 32 {\n\t\treturn nil, errors.New(operation + \" requires a 32-byte (AES-256) key\")\n\t}\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgcm, err := cipher.NewGCM(block)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnonceSize := gcm.NonceSize()\n\tnonce := make([]byte, nonceSize)\n\tif _, err = rand.Read(nonce); err != nil {\n\t\treturn nil, err\n\t}\n\tenvelope := make([]byte, encryptionEnvelopeHeaderSize, encryptionEnvelopeHeaderSize+nonceSize+len(plaintext)+gcm.Overhead())\n\tcopy(envelope, encryptionMagic[:])\n\tenvelope[len(encryptionMagic)] = EncryptionSpec\n\tenvelope[len(encryptionMagic)+1] = encryptionAlgorithmAES256GCM","sourceCodeStart":133,"sourceCodeEnd":169,"githubUrl":"https://github.com/siyuan-note/siyuan/blob/9f775e8a12daef8255556097396f9b2739078892/kernel/util/kdf.go#L133-L169","documentation":"encryptGCM enforces that the key passed to Encrypt or EncryptWithAAD is exactly 32 bytes, since the envelope uses AES-256-GCM. The operation name (e.g. \"Encrypt\", \"EncryptWithAAD\") is prepended to the message. A shorter or longer key is rejected before any AES work, because a non-256-bit key would silently produce AES-128 or fail in NewCipher.","triggerScenarios":"Calling Encrypt(key, plaintext) or EncryptWithAAD(key, plaintext, aad) with a key slice whose len() != 32 — e.g. a raw passphrase string used as the key, a 16/24-byte key, a hex-encoded 64-char string (64 bytes), or a truncated DeriveKey output.","commonSituations":"Developers pass a user password directly instead of running it through DeriveKey (Argon2id) or DeriveSubKey first; store a hex/base64 encoded key without decoding; or hand-roll key material with KeyLength != 32 in Argon2Params (which ValidateArgon2Params would also reject).","solutions":["Derive a 32-byte key with util.DeriveKey(password, salt, util.DefaultArgon2Params()) instead of using raw password/encoded bytes","Decode hex/base64 key material to raw bytes and verify len(key) == 32 before calling Encrypt/EncryptWithAAD","If using a master DEK, derive the purpose-specific subkey with util.DeriveSubKey(dek, purpose), which always returns 32 bytes","Add a caller-side guard: if len(key) != 32 { return errors.New(...) } before encryption calls"],"exampleFix":"// before\nkey := []byte(userPassword)\nciphertext, err := util.Encrypt(key, data)\n// after\nsalt := make([]byte, 16)\nio.ReadFull(rand.Reader, salt)\nkey := util.DeriveKey(userPassword, salt, util.DefaultArgon2Params()) // 32 bytes\nciphertext, err := util.Encrypt(key, data)","handlingStrategy":"validation","validationCode":"func validKey(key []byte) bool { return len(key) == 32 }\nif !validKey(key) { return nil, fmt.Errorf(\"key must be 32 bytes, got %d\", len(key)) }","typeGuard":null,"tryCatchPattern":"if err != nil {\n    if strings.HasSuffix(err.Error(), \"requires a 32-byte (AES-256) key\") {\n        // re-derive key via util.DeriveKey / DeriveSubKey and retry once\n    }\n    return err\n}","preventionTips":["Always obtain keys from util.DeriveKey or util.DeriveSubKey, never from raw passwords or encoded strings","Decode hex/base64 key storage formats to raw bytes immediately after load","Assert key length in unit tests for every code path that constructs keys","Run util.ValidateArgon2Params on persisted Argon2Params so KeyLength is always 32"],"tags":["go","crypto","aes-256-gcm","key-validation"],"backgroundTag":"invalid-argument-value","analyzedSha":"9f775e8a12daef8255556097396f9b2739078892","analyzedAt":"2026-09-19T03:17:15.984Z","contentChangedAt":"2026-09-19T03:17:15.984Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}