{"record":{"id":"53f45feacf553d5a","repo":"shadowsocks/shadowsocks-windows","slug":"failed-to-set-key","errorCode":null,"errorMessage":"failed to set key","messagePattern":"failed to set key","errorType":"exception","errorClass":"System.Exception","httpStatus":null,"severity":"critical","filePath":"shadowsocks-csharp/Encryption/AEAD/AEADMbedTLSEncryptor.cs","lineNumber":66,"sourceCode":"            {\r\n                _decryptCtx = ctx;\r\n            }\r\n\r\n            MbedTLS.cipher_init(ctx);\r\n            if (MbedTLS.cipher_setup(ctx, MbedTLS.cipher_info_from_string(_innerLibName)) != 0)\r\n                throw new System.Exception(\"Cannot initialize mbed TLS cipher context\");\r\n\r\n            DeriveSessionKey(isEncrypt ? _encryptSalt : _decryptSalt,\r\n                _Masterkey, _sessionKey);\r\n            CipherSetKey(isEncrypt, _sessionKey);\r\n        }\r\n\r\n        private void CipherSetKey(bool isEncrypt, byte[] key)\r\n        {\r\n            IntPtr ctx = isEncrypt ? _encryptCtx : _decryptCtx;\r\n            int ret = MbedTLS.cipher_setkey(ctx, key, keyLen * 8,\r\n                isEncrypt ? MbedTLS.MBEDTLS_ENCRYPT : MbedTLS.MBEDTLS_DECRYPT);\r\n            if (ret != 0) throw new System.Exception(\"failed to set key\");\r\n            ret = MbedTLS.cipher_reset(ctx);\r\n            if (ret != 0) throw new System.Exception(\"failed to finish preparation\");\r\n        }\r\n\r\n        public override void cipherEncrypt(byte[] plaintext, uint plen, byte[] ciphertext, ref uint clen)\r\n        {\r\n            // buf: all plaintext\r\n            // outbuf: ciphertext + tag\r\n            int ret;\r\n            byte[] tagbuf = new byte[tagLen];\r\n            uint olen = 0;\r\n            switch (_cipher)\r\n            {\r\n                case CIPHER_AES:\r\n                    ret = MbedTLS.cipher_auth_encrypt(_encryptCtx,\r\n                        /* nonce */\r\n                        _encNonce, (uint) nonceLen,\r\n                        /* AD */\r","sourceCodeStart":48,"sourceCodeEnd":84,"githubUrl":"https://github.com/shadowsocks/shadowsocks-windows/blob/891d971682eefcaa2e640258d3b352a3ad3b2233/shadowsocks-csharp/Encryption/AEAD/AEADMbedTLSEncryptor.cs#L48-L84","documentation":"Thrown from CipherSetKey when MbedTLS.cipher_setkey returns non-zero after the session subkey is derived. cipher_setkey configures the context for encrypt/decrypt with the given key and key length; failure indicates the key length or mode is invalid for the loaded cipher (e.g. key length not matching the cipher's expected size).","triggerScenarios":"keyLen does not match what the loaded cipher expects (e.g. 24-byte key passed to AES-128-GCM); the context was set up for a cipher that rejects the key size; keyLen computed incorrectly from EncryptorInfo.","commonSituations":"EncryptorInfo.KeySize wrong for the method; a salt/key buffer shorter than declared so derived key is wrong length; using a method whose key size the mbedTLS build does not support.","solutions":["Confirm EncryptorInfo.KeySize matches the cipher spec (AES-128-GCM = 16, AES-256-GCM = 32, chacha20-poly1305 = 32).","Verify the master key buffer was fully derived to keyLen before SetKey.","Ensure the mbedTLS build supports the key length for that cipher."],"exampleFix":"// before\nint ret = MbedTLS.cipher_setkey(ctx, key, keyLen * 8, isEncrypt ? MbedTLS.MBEDTLS_ENCRYPT : MbedTLS.MBEDTLS_DECRYPT);\nif (ret != 0) throw new System.Exception(\"failed to set key\");\n\n// after\nif (ret != 0)\n    throw new System.Exception($\"failed to set key (ret={ret}, keyLen={keyLen}, bits={keyLen*8})\");","handlingStrategy":"validation","validationCode":"// Confirm key length matches the cipher before setkey\nif (key.Length != keyLen) throw new ArgumentException($\"key length {key.Length} != {keyLen}\");","typeGuard":"bool KeyLengthMatchesCipher(string method, int keyLen) =>\n    (method.Contains(\"-128-\") && keyLen == 16) ||\n    (method.Contains(\"-256-\") && keyLen == 32) ||\n    (method.StartsWith(\"chacha20\") && keyLen == 32);","tryCatchPattern":"try { CipherSetKey(isEncrypt, key); }\ncatch (Exception ex) when (ex.Message == \"failed to set key\")\n{ /* log keyLen vs cipher expectation, abort session */ }","preventionTips":["Verify EncryptorInfo.KeySize matches the cipher spec.","Ensure the master key is fully derived to keyLen bytes.","Log keyLen and the native return code on failure."],"tags":["encryption","aead","mbedtls","key","configuration"],"backgroundTag":null,"analyzedSha":"891d971682eefcaa2e640258d3b352a3ad3b2233","analyzedAt":"2026-08-13T10:12:34.434Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}