FHE-Coder: Benchmarking Secure Agentic Code Generation for Fully Homomorphic Encryption
Authors: Mayank Kumar
Jiaqi Xue
Mengxin Zheng
Qian Lou
Venue: ICLR 2026 Poster (2026)
Keywords: Large Language Models
Agents
Code generation
Fully Homomorphic Encryption
Retrieval Augmented Generation
Primary area: alignment, fairness, safety, privacy, and societal considerations
TL;DR: We built a three-phase agentic framework that enables Large Language Models to automatically generate secure and functional TFHE code, bridging the expertise gap that currently limits the adoption of privacy-preserving computation.

Abstract: Fully Homomorphic Encryption (FHE) is a foundational technology for confidential computing, yet its practical adoption remains limited by the need for specialized cryptographic expertise and error-prone parameter configuration. To lower this barrier, we investigate whether Large Language Model (LLM) agents can reliably generate secure FHE code from natural-language specifications. We present FHE-Coder, a three-phase agentic framework that addresses the key failure modes of FHE code generation: semantic ambiguity, API misuse, and cryptographic insecurity. The framework integrates (1) a Prompt Formalizer that structures user intent and enforces secure parameterization, (2) a specialized retrieval-augmented generation (RAG) module that supplies scheme-specific API and documentation knowledge, and (3) an automated Security Verifier that performs iterative validation and feedback to detect and correct cryptographic flaws. We evaluate FHE-Coder across four leading LLMs on a benchmark of ten FHE programming tasks spanning increasing functional and security complexity. While baseline agents frequently produce code that compiles and passes functional tests, they often violate security constraints or misuse cryptographic parameters. In contrast, FHE-Coder consistently generates solutions that are compilable, functionally correct, and verifiably secure across schemes including TFHE and CKKS. Our work establishes a systematic methodology and benchmark for agentic FHE code generation, providing a practical step toward democratizing secure computation without compromising cryptographic guarantees.

Published as a conference paper at ICLR 2026
FHE-CODER: BENCHMARKING SECURE AGENTIC CODE GENERATION FOR FULLY HOMOMORPHIC EN- CRYPTION
Mayank Kumar, Jiaqi Xue, Mengxin Zheng Qian Lou Department of Computer Science
University of Central Florida
(mayank. kumar, r, jiaqi xue, mengxin wenngggii..nnnn..o.oommmmm gian. lou) edu
ABSTRACT
Fully Homomorphic Encryption (FHE) is a foundational technology for confi- dential computing, yet its practical adoption remains limited by the need for specialized cryptographic expertise and eπrоr pror-pronne parameter configuration. To lower this barrier, we investigate whether Large Language Model (LLM) agents can reliably generate secure FHE code from natural-language specifications. We present FHE-Coder, three-phase agentic framework that addresses the key fail- ure modes of FHE code generation: semantic ambiguity, API misuse, and crypto- graphic insecurity. The framework integrates (1) a Prompt Formalizer that struc- tures user intent and enforces secure parameteriization (2) specialized retrieval- augmented generation (RAG) module that supplies scheme- -peeif-- API and doc- umentation knowledge, and (3) automated Security Verifier that performs it- erative validation and feedback to detect and correct cryptographic flaws. We evaluate FHE-Coder across four leading L.MMs benchmark of ten FHE pro- gramming tasks spanning increasing functional and security complexity. While bascline agents frequently produce code that compiles and passes functional tests, they often violate security constraints or misuse cryptographic parame- ters. In contrast, FHE-Coder consistently generates solutions that are compil- able, functionally correct, and verifiably secure across schemes including TFHE and CKKS. Our work establishes systematic methodology and benchmark for agentic FHE code generation, providing a practical step toward democratizing se- cure computation without compromising cryptographic guarantees. Project page: attps://fhe- coder rithub.ii
INTRODUCTION
Fully Homomorphic Encryption (FHE) (Gentry) 2009 Lou & Jiang 2019 Zhang et al. 2024 Lou
al. 2021) enables computation directly over encrypted data, eliminating the need for decryption
during processing (Brakerski et al. 2014 Lou & Jiang 2021 Brakerskil 2012 Zhang et al. 2023
Fan Vercauteren| 2012|Cheoo Cheon al.]
20176; Chillotii al. 2020 Xue et 2022: Zhang al.
2025
Lou et al.) 2019a; Zheng et al.- 2023). As a foundational primitive for privacy pwwycccyeeseevvngggg
computation, it supports encrypted machine learning (Gilad Bachrach al.) 2016 Lou 2019b
Santriaji et al. 2024). secure multi-party computation (Jin et al. (023), private blockchains (Ma-
dathil & Scafuro 2023). and medical diagnostics (Raisaro et al. 2018).
Among modern schemes, TFHE Chillotti et al. (2020) and CKKS Cheon et al. (2017a) are widely regarded as the most industry-relevant FHE frameworks, with deployments across major technology platforms. Apple has integrated FHE--bsed private contact discovery and private email retrieval since iOS 18 (Apple 2024). benefiting over 1.5 billion iPhone users as of 2025. Microsoft has also deployed FHE in its Browser Password Monitor (Research) 2020). Furthermore, Zama's 's FHE-based ecosystem enables encrypted machine learning (Concrete ML (Zamal (024)), private smart contracts (fhEVM La.ss 2024)), ) and blockchain infrastructures (Madathil & Scafuro 2023)

---

Published as a conference paper at ICLR 2026
Despite this momentum, widespread adoption remains hindered by steep learning curve. Unlike general-purpose programming, developing secure FHE applications requires precise coordination of tightly coupled cryptographic components. Developers must ensure strict parameter compatibil- ity to satisfy Learning With Errors (LWE) security bounds while carefully managing noise growth across homomorphic operations. Even minor misconfigurations can render programs insecure or non-functional. This complexity is reflected in community benchmarks such as the 2025 FHERMA competitions (FHERMA 2025a b), where implementing standard activation function (R) and convolution inference remains challenging due to noise-sensitive constraints. This expertise gap raises fundamental question: can LLM agents translate natural language into secure FHE code?
Recent advancements in Large Language Models (LLMs) (Jiang et al., 2024) have demonstrated strong capabilities in natural language understanding and code generation (Mastropaolo al. 2023] Nijkamp et al., (022). These models can synthesize executable programs from high-level descrip- tions and assist developers debugging and implementation. This progress raises the possibility of leveraging LLM agents to automate FHE programming tasks, including secure parameter configu- ration and correct API usage. Reliable automation would lower expertise barriers and democratize access to confidential computing.
However, naive application of general- purpose code generation agents to FHE of- ten fails. As illustrated in Fig. Ta agents frequently generate plaintext implementa- tions instead of homomorphic programs (Fig. [bb). This failure arises from sev- eral domain-specific challenges. First, models trained on general-purpone code lack awareness of FHE- FHE-specific program structure and cryptographic constraints. They frequently hallucinate APIs or mis- use existing functions, violating homo- morphic properties. Second, parame- ter configuration requires scheme-specific reasoning about security levels and noise coarhh-aapablitiien absent from standard prompting pipelines. Finally, conventional evaluation metrics such as @ass@k (Chen al. 202I) measure only functional cor- reciness, not cryptographic security. A program may pass such tests while operating on plaintext data, entirely defeating its privacy- preserving objective. Thus, functional correctness is a flawed proxy for secure code generation.
No encryption Inputs int result = & b;
(a) Plaintext program.
Panimatar Satup Key Garenatio
const int minimum Lambda 110; TFheGate.. ParameterSet* params TFheGate SecretKeySet* key
Enerystion
bootsSyaEncrype (bctx_a
Homomorghhon Openstio
bootsAND (wr.slt@rrsut_ccm
Decrypion Dutpul
bootsSymDecrypt (Eresult_cco ctx [i]
(b) TFHE program.
Figure 1: Illustrating the differences between a plaintext pro- gram and a TFHE-based FHE program.
To address these limitations, we introduce a novel agentic workflow and evaluation framework for secure FHE code generation, illustrated in Fig- 2 Our workflow consists of three tightly integrated components designed mitigate the identified failure modes. First, the FHE Prompt Formalizer (Fig. 3a) translates user intent into a structured specification with securely derived cryptographic parameters. Second, the FHE API RAG Retriever (Fig. 3bb) supplies scheme-specific documenta- tion and expert-curated usage examples to prevent API hallucination and misuse. Third, the FHE Security Verifier (Fig. 4 introduces an automated feedback loop that enforces security invariants and detects plaintext leakage parameter inconsistencies. Together, these components transform unconstrained code generation into a security-awan iterative synthesis process.
We summarize contributions follows:
We propose FHE-Coder, an agentic framework that enables reliable and security- aware FHE code generation using LLM agents. It introduces three core components: an FHE Prompt Formalizer that derives parameters grounded in LWE-based security analysis,
Expert-Enrichee RAG Retriever that bridges gaps in cryptographic API knowledge, and an FHE Security Verifier that enforces privacy invariants through automated validation.
We show traditional functional metrics are insufficient for private computing and introduce a rig- orous security evaluation methodology. featuring new @ 1 (func_sec metric and a multi- stage pipeline ensuring functional and cryptographic correctness.
2

---

Published as a conference paper at ICLR 2026
User Prompt
Prompt
Formal Prompt
LLM Agent
implement The LWEE parameter 1024.
Context: You are exportcry exporteryptorcoree ptorcoder.
Objective: 4Intent Here>
Estimator
Reference Pscudocade:
Developer
Loop
#include <ttha/tfha.lt #include <tfhe/tfhe_ja.h
atenny Check
Securiy Check
Question: [..]
</code>
Compile Functional: 3/5 Tests Passed Security:
Latency: NA
THEE Docs
Took Ratreive
Security
Formal Error Prompt
FHE API RAG Retreiver
Figure 2: Overview of our secure FHE code generation workflow, Our key components (highlighted with stars) are: (1) the FHE Prompt Formalizer, which enriches developer's prompt with securely derived param- eters using Lattice Estimator; (2) the FHE API RAG Retriever, which provides expert-annotated API usage examples; and (3) the FHE Security Verifier, which establishes an automated feedback loop for security and correctness. Maximum iterations are set to 10.
We establish a comprehensive benchmark for agentic FHE generation across TTHE and CKKS. We show that while baselines fail security-critical tasks, our framework excels on complex architectures (e.g., Transformers), offering a blueprint for automated secure software engineering.
2 BACKGROUND
2.1 FULLY HOMOMORPHIC ENCRYPTION
Fully Homomorphic Encryption (FHE) enables arbitrary computation over encrypted data with- out requiring decryption, providing strong confidentiality guarantees grounded in hard lattice prob- lems such as Learning With Errors (LWE). Modern FHE schemes can broadly categorized into boolean-gates bate--att---eedee---ee-e systems (e.g.. TFHE) and arithmetie-circuii--aset systems (e.g.. BGV (Braker- ski et al. 2014) and CKKS (Chcon et al. 2017b)).
TFHE (Fully Homomorphic Encryption over the Torus) (Jiang al. 2022 operates over boolean circuits and supports logical gates (NOT, AND, OR) with highly efficient Programmable Boot- strapping (PBS), enabling evaluation of non- non-linear functions while refreshing ciphertext noise. In contrast, arithmetic schemes like BGV and CKKS operate over polynomial rings, optimizing integer or real-number computation for encrypted ML workloads.
Despite their structural differences, these schemes share common cryptographic constraints. Devel- opers must carefully manage noise growth across homomorphic operations, ensure strict compati- bility among interdependent security parameters (e.g., security level A, lattice dimension, modulus size), and avoid silent decryption failures caused by parameter misconfiguration. In CKKS, ad- ditional challenges arise from approximation error control and rescaling strategies, while TFHE requires precise bootstrapping configuration and gate-level orchestration.
Consequently, although modern FHE schemes provide powerful functionality, implementing secure and efficient FHE applications requires specialized cryptographic expertise. This complexity hinders widespread adoption across both boolean and arithmetic FHE.
2.2 LLM AGENTS FOR CODE GENERATION
Code generation has emerged as a core application of large language models, with systems such as CodeGen (Nijkamp et al. 2022). CodeX (Chen et al. (02T), and CodeT5 (Wang al.) 2021) demonstrating strong performance in mainstream programming languages due to the availability of large-scale training corpora. However, generating secure code for niche crypto libraries is harder due to sparse documentation, domain-specific APIs, and mathematical constraints.
Recent advances extend beyond standalone LLMs toward LLM agents, which integrate planning, retrieval, and tool-use capabilities into iterative reasoning pipelines. In adjacent domains such as High-Level Synthesis (HLS) and Register Transfer Level (RTL) hardware design (Thakur et al. Xiong al. 2024). LLM--ased systems have demonstrated the ability to
2023
Liao et al.
2024

---

Published as a conference paper at ICLR 2026
reason about logical operations (e.g., ANDIOR gates) and structured transformations. his suggests LLM agents possess reasoning that aligns with circuit-oriented FHE schemes.
However, unlike standard program synthesis tasks, FHE code generation imposes additional security-critical constraints: correctness depends not only on syntactic validity and functional be- havior, but also cryptographic soundness, parameter security margins, and ciphertext-only com- putation guarantees. Traditional prompting cannot enforce these invariants. This motivates using structured, security-aware LLM agents with parameter derivation, API grounding, and verification to reliably generate FHE programs for schemes like TFHE and CKKS.
3 OUR METHOD: FHE-CODER
Our Agentic workflow 2 has three main components: FHE Prompt Formalizer, FHE API RAG Retriever and FHE Security Verifier. The Agent uses ReAct Yao et al, 2023 prompting.
3.1 FHE PROMPT FORMALIZER
PHE Prompt Formalizer
User Prompt
implament
Implament tomarptic using
Perball Spesificttion
STEP2
should be 2004.
Intent Dimection
A NULL
Findl
aanarbycc
2024
oeport crypto-coder.
Comtatt You are
Estimator
Latisee
Dafry-Gode
snakers
Objective: sintant Heree
Apply Promptt Temp ate on Inpurs
inverrth 1200
The
Reference
woal tiettaars jobks
Preurforade
<ialrry onde heees
Gatde Reqquimmercs
ecodae requinmennts
Functional
Correctroce E.1
Foomal Speelf caltion
Parge
Secustig
(b) An offline, human-in-the loop process maps expert- enriched doestrings TFHE code snippets.
Lattice Estimator transform a developer's prompt into secure and structured set instructions. The pro- cess extracts intent and solves for cryptographic parameters.
(a) LLMs
Figure Overview of the instruction and generation phase. (a) The online instruction generation and param- eter estimation. (b) offline code mapping process.
The FHE Prompt Formalizer, illustrated in Figure 3a addresses a critical failure mode in base- line agents: the inability select secure cryptographic parameters through probabilistic generation. While standard LLMs often hallucinate inconsistent parameters or insecure noise budgets due to lack of coomain-specifie mathematical structure, our workflow replaces this heuristic guesswork with cryptographic certainty. The process begins by extracting the user's high-level intent, which is then passed to a Lattice Estimator (Albrecht et al. 2015) to mathematically solve for the precise security parameter, X, rather than predicting it. A second LLM utilizes this secure config- uration to generate formal specification containing Daïny (Leino 2010) pseudocode. This step transforms ambiguous natural language into rigorous structural constraints; for instance, the gener- ated ensure statements explicitly guide the agent to embed a assert checks in the final C++ code, ensuring the solution adheres to valid ciphertext structures and intermediate invariants.
While our FHE-Coder framework demonstrates strong performance on atomic tasks, Figure 6 shows that direct generation degrades complex, compositional problems that require multi-step reason- ing (e.g., matrix-vector multiplication, MLP). To address this, we use a structured decomposition strategy: the agent first generates secure primitives (e.g., dot product); then, a "composer" agent receives these verified subroutines and the high-level goal to build the final program.
3.2 FHE API RAG RETRIEVER
The FHE API RAG Retriever, illustrated in Figure 3b addresses the limitations of standard trieval methods, which fail almost entirely in this domain because LLMs lack the intrinsic struc- ture interpret strict cryptographic APIs respect ciphertext-only computation rules B To bridge

---

Published as a conference paper at ICLR 2026
the semantic gap between natural-language intent and these rigid library constraints, construct a knowledge base using expert-enriched metadata. Specifically, we transform FHE method (e.g,, TFHE) doestrings" into the Doxygen forma utilizing structured tags such as @o cobjective to emhed machine-readable semantic instructions. This enrichment enables the agent to retrieve pre- cise, aecurity-compliany code snippets based cryptographic purpose rather than ambiguous key- word matching, ensuring the selected APIs adhere to necessary noise and parameter rules. Crucially, this offline preparation a one-time, lightweight security step designed eliminate API hallucina- tions, making the process fully scalable. Extending the framework to another scheme (e.g., CKKS) simply requires replacing the documentation corpus with that scheme's library documentation, ren- dering cross- cross-scheme adaptation essentially plug-and-play. In our experiments, the chunking-size was set to 600, and the chunk-overlap was set to 120.
3.3
FHE SECURITY VERIFIER
Parameter Instruction
= 128
PHE Security Verifier
Code from Agent
Latency Check
Check
Functional Check
Compite
dinclude <therthett> dindludo -thermee_jaa Ja.he dinclude ostdle hn mtkiiif /code here')
Rejost
Latency Comparision with reforance
2. mimmmtih from Lifice- elemrator Incorruct Ensnyylion Impars
1. THE AP1 as not used
So lsioon Not aptrrized loed reforance
Formal Error Report
Security Fallure Reason
Number of Tests Passed
Complee Eroor Message
STOP
Complte: OK Functional: 3/5 Tosts
Passed Becurity: Laboncy:
Figure This automated pipeline validates generated code across four stages: Compile, Functional, Security, Latency. The critical Security Check verifies correct API usage, secure parameter configuration, and proper input encryption. If any stage fails, a consolidated Formal Error Report is generated and returned to the agent for iterative correction; otherwise, the solution is accepted.
The FHE Security Verifier, detailed in Figure 4 introduces novel, complementary validation layer that addresses the critical limitation of standard code generation metrics. While traditional Pass@k functional testing (implemented here via unit tests) ensures the code aligns with the user's op- erational intent, our experiments show that baseline LLMs often produce code that passes these functional tests while remaining cryptographically insecure (e.g., using plaintext operations). To bridge this gap, pipeline subjects the agent's code to a specialized Security Check rooted in the mathematical hardness of the Learning With Errors (LWE) problem. Unlike simple heuristic checks, this module strictly enforces LWE-based parameter bounds derived from the Lattice Esti- mator and mandates exclusive homomorphic API usage to prevent data leakage. When a violation is detected alongside Compile, Functional, Latency errors, the system generates structured Fo rormal 1 Error Report, driving an automated feedback loop that forces the agent to converge on solution that is simultaneously functionally accurate and mathematically secure.
EXPERIMENT DESIGN SECTION
4.1 PROBLEM DEFINITION
We introduce the LLM-Agentic FHE Generation and Evaluation Framework, illustrated in Figure 2 In this framework, each TFHE task is formulated as a natural language prompt and provided to the agent. Leveraging its reasoning capabilities, the agent may (optionally) consult external documen- tation through surreval-auugenter generation (RAG) before implementing the corresponding code. The generated code subsequently evaluated by the Security Verifier, which consolidates any com- pilation or verification errors into structured feedback and returns it to the agent for refinement. The agent iteratively revises its solution until security checks pass or the 10-step limit is reached.
'httss///tfhhe http://ghhabbohohottttttoootarpa https:/www.doxygen...
5

---

Published as a conference paper at ICLR 2026
4.2 WORKLOAD SELECTION
We describe the workloads for the code generation breifly in Table
Table I: Benchmark workloads for evaluating TTHE code generation, categorized by complexity.
Complexity
Workload
Description
AND
Bitwise AND between two 32-bit integers.
ReLU
ReLU a signed bit integer.
Primitives
Adder
Addition of two 32-bit integers.
Multiplier
Multiplication two 32-bit integers.
Vector Add
Vector addition between two integer vectors of length 5.
Dot Product
anner-product of two integer vectors of length
Linear Algebra
Mat- Vec Mult
Multiplication between an encrypted vector a plaintext matrix.
Mat-Mat Mult
Multiplication between an encrypted matrix and a plaintext matrix.
MLP
A simple 3-layer MLP with ReLU activation.
CNN
A small Convolutional Neural Network with a fully con- nected layer.
Deep Learning
Softmax
Computes the Softmax activation function over an input vector.
Atlention
Single-head self-attention mechanism (Query, Key, Value).
Transformer
A complete Translormer block combining attention and feed-forward layers.
These tasks collectively evaluate LLMs' ability to synthesize both low-level cryptographic primi- tives and high-level machine learning components using TFHE's gate-level programming paradigm. However, in Section 5.3
we evaluate more complex workloads well.
4.3 MODEL SELECTION
We select the latest LLMs to drive our agent. For open-source LLMs, we choose Qwen3-Coder 480B-A35B (Yang et al. 2025)) (QWE) and Deepseek-V25 V3.1 (Liu al. (D24) For closed- source LLMs, we select Gemini-2.5-Pro (Comanici et al. (GEM) and GPT-5( (OpenAl, 2025 (GPT). For all studied L.Mss, set the temperature to 0.5. Furthermore, there heavy local resource consumption for generation, as models are accessed via the OpenRouter API.
Note that, mitigate issues stemming from the randomness of model generation, the experimental results presented in this paper are obtained by conducting five repeated experiments and averaging the results. For RAG, we used OpenAl's text embeddingg- -mmamal
4.4 METRICS
In our framework, we employ three key metrics to judge the quality of the generated codes. Fol- lowing prior works on code generation, we use 1. Pass Pass@k(func) denote the fraction of generated codes that pass the unit tests. We present our novel metric 2. Pass@k(func.sed which denotes the fraction of generated codes that are both functionally correct and cryptographically secure. A program is considered secure only if it passes an automated analysis verifying: (i) exclusive use of TFHE APIs to prevent plaintext data leakage, (ii) correct configuration cryptographic parameters against secure values from the Lattice Estimator, and (iii) proper encryption of all inputs before their use. A failure in any these checks renders the code insecure. Our third metric is 3. Latency, compared to expert-written reference codes. This is computed as the ratio of execution times of the generated solution and the expert-written solution.
4.5 BASELINES
Our first baseline denotes a regular code generation workflow. Concretely, given the same natural- language task description, the agent directly generates TFHE code in single shot (or with its de- fault self-revision), without (i) the Prompt Formalizer (no enforced program skeleton or parameter

---

Published as a conference paper at ICLR 2026
GPT pazs0l llunctionllty)
Intenoy peaiifnee seo eetutuna
1.0
03
00
Sccnique
and
relu
adder
multiplier
vector add
dot product
matrix -vector matrix
matrix
mip
cnn
Figure 5: Performance of GPT-5 across representative tasks. A comparison of framework (FHE-Coder) against Baseline (BAS) and Chain-of-Thour (COT) techniques. FHE-Codee consistently produces code that both functionally correct verifiably secure.
derivation), (ii) the API RAG Retriever (no documentation-grounee API lookup), and (iii) the Se- curity/Latency verification loop (no iterative feedback from compilation, functional tests, or security checks as in Fig. 2..W abbreviate it as BAS. Our second baseline is Zero-shot Shain-of-Thoughe agent, which builds upon the regular workflow by appending a step-by-step worked example of correct TFHE code generation. We abbreviate it as COT.
EVALUATION RESULTS
This section presents a comprehensive empirical analysis our proposed agentic framework (de- noted FHE-Coder) in comparison regular code generation workflow (BAS) and Zero-shot Chain-of- Though agent (COT). We first evaluated four leading LLMs on benchmark of ten TFHE programming tasks with varying complexity, and then extended the scheme CKKS.
5.1 IN-DEPTH ANALYSIS ON A STATE-OF-THE-ARR MODEL
We first conduct detailed analysis using the state-of-the-art GPT-5 model to illustrate the core performance differences between our framework and the baselines across all tasks. The results are presented in Fig.
Functional Correctness: As shown the top chart of Figure 5 the baseline methods (BAS and COT) demonstrate partial success tasks with low complexity, such and and relu. We defer discussion of tougher, compositional tasks to Section 5.3
Security: A critical distinction between our framework and the baselines is revealed in this evalua- tion. Both the BAS and COT methods yield a pass@1 (func sec) approaching zero for tasks evaluated. This finding indicates that they consistently fail produce secure code, often generating plaintext implementations that, while sometimes functionally correct, do not adhere to the required cryptographic protocols. Conversely, the FHE-Coder framework achieves near-perfect scores across the entire benchmark. This outcome underscores the necessity of a guided, multi-phase process- encompassing the proposed prompt formalization, accurate API retrieval, and security verification- to meet the specific requirements of secure code generation.
Latency: The performance trade-offs are detailed in the bottom chart of Figure 5 While the FHE- Coder framework naturally incurs higher latency due to its iterative feedback loop, the specific computational overhead introduced by our verification logic is minimal. The Compile and Secu- rity Checks rely lightweight static analysis and complete in the order of milliseconds, while the Latency Check adds negligible overhead. The majority the time is consumed by the Functional Check, which ranges from seconds (for simple gates) minutes (for complex circuits like Matrix Multiplication). but this duration is intrinsic to the execution of the generated FHE code itself rather than the framework's 's processing. This overhead is deliberate design choice, representing practi- cal trade-off for significant improvements in security. The absolute execution runtimes of generated codes of the representative workloads mentioned in Table

---

Published as a conference paper at ICLR 2026
COT
task, voctor addition - passg]]/funccem sec)
t25k det product passglfunc sec)
task matrix pats@I(tung
1.0
9.6
0.8
0.0
0.2
0.2
task vector addition
latancy
metrix
Intency
eneenyy
D5C
GWT
GPT
D0C
DWWF
CFT
Figure 6: Comparison of FHE-Coder against baselines (BAS, COT) across four LLMs. Baselines universally fail security checks, whereas FHEE-Coee consistently ensures security, showing model-agnostic benefits. Note: Latency measures the relative runtime overhead of the generated code.
5.2 GENERALIZABILIT ACROSS DIVERSE LLMS
To ensure our findings are not model-specific, we assessed the generalizability of our framework by applying it to four different LLMs. Fig. 6 presents a comparative analysis three representative tasks. The results confirm that the performance patterns persist across all models. The security defi- ciencies of the baseline methods are regardless the LLM used. contrast, the Coderr framework is the only approach that enables the models to consistently produce functional and secure outputs. While the overall performance ceiling influenced by the base model's intrinsic capabilities- capabilities-wiil wiith GPT-5 and Gemini-2.5-pmi generally outperforming Deepseek-V3, and Qwen3-Coder -our framework provides consistent and essential security impoves for all tested models.
both BAS and COT fail to generate secure code
5.3 SOLVING COMPLEX TASKS WITH STRUCTURED DECOMPOSITION
As detailed in Figure 7 struc- tured decomposition approach effectively solves tougher compo- sitional tasks (e.g., matrix-vector multiplication and CNN) where the direct method fails. By inte- grating structured decomposition (With SD), the agent achieves strong passè1 (func_sea) scores across most tasks meaks-reaching 0.70 for matrix-vector multiplication and 0.60 for CNNs-whereas direct generation (Without SD) yields near-zero success. The increased compositional complexity of the MLP task lowers the combined pass rate to approximately 0.35, suggesting a link between logical cireuit depth and the agent's ability simultaneously maintain functionality and security protocols. Overall, this hierarchical strategy of composing verified sub-tasks extends the agent's capabilities to previously unsolvable problems.
Decomposition
Wheee
Mesto/edar
Figure 7: Performance: PHE-Coder + structured decomposition.
Scaling to Complex Non-Linear TFHE Architectures. We further test this decomposition strat- egy on complex non-linear TFHE circuits (Softmax, Attention, and Transformer). Figure I0 shows that baselines (BAS, COT) consistently fail to produce valid and secure code, yielding a pass@l (func_sec) of approximately 0.0. In contrast, FHE-Coder combined with structured de- composition achieves perfect pass@ 1 (func sec) scores on Softmax and Attention for the GPT model. However, the reduced pass rate Transformers (e.g., 0.4 for GPT) and DSK's failure
8

---

Published as a conference paper at ICLR 2026
on Softmax indicate that while the framework successfully scales to deeper circuits, overall perfor- mance remains partially constrained by the base LLM's intrinsic reasoning capabilities.
5.4 GENERALIZATION TO CKKS SCHEME
Figure 9 shows that our workflow generalizes beyond TFHE to CKKS on non-linear workloads (Softmax, Attention, Transformer). Baselines (BAS, COT) yield near-zero pass@l ( (func-sec) scores across all tasks. In contrast, FHE-Coder-using CKKS parameter estimator and documen- tation achieves perfect pass@l Suuc_sect results on Attention for both models, and on Softmax for GPT. However, DSK's failure on Softmax and both models' moderate Transformer performance (+r 0.4) indicate that while the framework adapts to new cryptographic schemes, overall success remains constrained by the underlying LLM's intrinsic limits.
5.5 ABLATION STUDY
CPTT task vactor addition
To quantitatively assess the contribution of each com- ponent within our framework, we conduct a component analysis by systematically integrating each of our three key modules: the FHE Prompt Formalizer (FP), the FHE API RAG Retriever (RAG), and the FHE Security Ver- ifier. The results for the GPT-5 model on the represen- tative Vector Addition task, shown in Figure 8, reveal a clear cumulative performance hierarchy.
The study establishes that the Baseline (BAS) agent, lacking our modules, is unable to produce valid and secure TFHE code, yielding a pass@l (func_sec) score of upproximately 0.0. Integrating the FHE Prompt Formalizer (+ FP) provides the initial structural guid- ance and secure parameter derivation necessary to elevate the pass@1 1 (f (func_sect score to 0.6. Subsequently adding the FHE API RAG Retriever (+ FP + RAG) sup- plies the agent with precise cryptographic documenta- tion, further improving the score to 0.8 by mitigating API hallucinations. Finally, the full FHE-Coder framework, which incorporates the automated feedback loop of the FHE Security Verifier, the only configuration to achieve a perfect 1.0 pass@1 (func_sec) score. This confirms that all three components are essential and comple- mentary, working in concert to enforce both functional correctness and strict cryptographic security.
645
1960
Figure 8: Ablation Study on Vector Addition. Component Analysis on Vec- tor Addition. Progressively adding mod- ules (+ FP, + RAG) improves the base- line pass (func_sec) score, but the full FHE-Coder framework is required to achieve perfect 1.0.
Table 2: Illustrative absolutte execution Times for FHE workloads.
Task (Complexity)
Average Execution Time
AND (Elementary Gate Logic)
10.45 milliseconds
ReLU (Simple Bitwise Circuit) MatMul (Complex Compositional Circuit)
11.50 milliseconds
2.54 minutes
DISCUSSION
Our work demonstrates that automating the generation of secure FHE code requires moving beyond simple prompt-to-code workflows, which we show consistently fail in security-critical domains. The core finding is that while baseline agents may achieve functional correctness, they lack the intrinsic mathematical reasoning to select secure parameters or adhere to strict ciphertext-only constraints, resulting in near-zero security pass rate. This highlights a fundamental misalignment: traditional metrics like Pass @ kifunc) are misleading proxies for success in cryptographic programming. Our framework addresses this by elevating verifiable security to primary objective, grounding the gen- eration process in the mathematical hardness of the Learning With Erorr (LWE) problem via the Lattice Estimator, rather than relying on probabilistic L.M heuristics.

---

Published as a conference paper at ICLR 2026
DSK
GPT
OKKS
OKRS
Bask Joftmax bitun sec)
task attention passgliftunc sec)
tranffomer passgll((uns
1.0
1.3
0.
6.8
0.0
0.0
0.5
6.4
682
001
Fil--Ceder Strumtued
895
001
FIE-Cader Stuctindd
1845
001
FIE-Coder Stracuund
Figure 9: Generalization to CKKS. FHE-Coder Structured Decomposition significantly outperforms failing baselines non-linear architectures. While GPT achieves high pass@ (func_see) across all tasks. DSK'S failure on Softmax indicates that the framework's effectiveness remains partially constrained by the base LLM's intrinsic capabilities.
DSK
GPT
task softmex
passgelfunc secl
task, attertion
pass@rlifunc sec)
task transformer pespg g sec)
1.0
1.0
0.5
0.0
0.8
0.6
6.6
6.0
0.0
CDT
Doder Strccured
Codar Stuctand
RA5
COT
PiF-CCdder Strumundd
Figure 10: Complex TFHE Tasks. FHE-Coder Structured Decomposition significantly outperforms failing baselines (BAS, COT) on non-linear circuits. While it enables perfect pass@ (func_sec) scores for GPT on Softmax and Attention, DSK's s failure on Softmax and both models' lower Transformer scores indicate that base LLM capabilities can still constrain performance on deeper circuits.
Crucially, our extended evaluation confirms that this agentic architecture serves as generalizable blueprint for confidential computing, not just TFHE-specific solution. The modular design of our three components-Prowwe Prompt Formalizer, RAG Retriever, and Security Verifier-enables "plug-and- play" adaptation other schemes. As evidenced by our results with CKKS, achieved high secu- rity scores by simply swapping the underlying parameter solver and documentation corpus, proving that the workflow's effectiveness is scheme-agnostic. Furthermore, tured Decomposition reveal that the framework scales to state-of-the-art complexity. While direct generation struggles with deep circuits, agents excel "composers" when provided with verified primitives, successfully implementing complex non-linear architectures like Attention mechanisms and Transformers. FHE-Coder demonstrates that with structural knowledge and security feedback, LLMs can evolve from unreliable assistants into verifiable partners for secure software engineering.
experiments with Struc-
7 CONCLUSION
Fully Homomorphic Encryption has emerged as cornerstone of modern confidential computing, enabling unique programmable bootstrapping capabilities that drive widespread industry adoption; however, utilizing this powerful tool is severely limited by steep learning curve. In this work, we introduced FHE-CODER, a structured agentic framework that bridges this gap by integrating prompt formalization. aarreval-augmeented generation, and critical security verification loop. Our findings reveal that while standard agents consistently fail due to lack of domain constraints, our framework succeeds by strictly grounding the generation process the mathematical hardness the Learning With Errors (LWE) problem. Beyond establishing the first robust benchmark for TFHE, our extended evaluation demonstrates significant generalization and scalability: we proved that the framework's 's modular design serves as scheme-agnostic blueprint, successfully adapting to the CKKS scheme, and that a structured decomposition strategy enables the synthesis of state-of-the-an non-linear architectures, such as Attention mechanisms and Transformers. By enabling developers to reliably generate code that is simultancously functional and verifiably secure, this work takes a technologies.
definitive step toward democratizing access these advanced
10

---

Published as a conference paper at ICLR 2026
8
ETHICS STATEMENT
Large language models (LLMs) were used to check grammer and polish writing.
REPRODUCIBILITY STATEMENT
In order to ensure reproducibility, we fixed the seed while inferencing the models. As noted in Section the results of the experiments shown aggregated after 5 independent runs with htte///heecorrr
different seed values. Source code & leaderboard: E github. io/
10 ACKNOWLEDGEMENTS
This material is based upon work supported by the National Science Foundation under Grant Nos. CCF-2523407 and CNS-2413232. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.
REFERENCES
Martin R Albrecht, Rachel Player, and Sam Scott, On the concrete hardness of learning with errors. Journal of Mathematical Cryptology, 9(3):169-200 2015.
Apple. Homomorphic encryption. encrypytoon https: ht///maciine learning apple. ctaple..com/eseaacce. Mommomozphii--enrrryeeoo ion 2024. Accessed: 2025.
Zvika Brakerski. Fully homomorphic encryption without modulus switching from classical gapsvp.
In Anmual cryptology conference, pp. 166. Springer, 2012.
Zvika Brakerski, Craig Gentry, and Vinod Vaikuntanathan. (leveled) fully homomorphic encryption without bootstrapping. ACM Transactions Computation Theory (TOCT), 6(3):1-36, 2014.
Mark Chen, Jerry Tworek, Heewoo Jun, Qiming Yuan, Henrique Ponde De Oliveira Pinto, Jared Kaplan, Harri Edwards, Yuri Burda, Nicholas Joseph, Greg Brockman, et al. Evaluating large language models trained on code. arXiv preprint arXiv:2107.0333 2021.
Jung Hee Cheon, Andrey Kim, Miran Kim, and Yongsoo Song. Homomorphic encryption for arith- metic of approximate numbers. In International conference the theory and application of cryptology and information security, pp. 409-437. Springer, 2017a.
Jung Hee Cheon, Andrey Kim, Miran Kim, and Yongsoo Song. Homomorphic encryption for arith- metic of approximate numbers. In Advances in Maanooogy-ASSAARPPP 2017: 23rd international conference the theory and applications of cryptology and information security, Hong kong, China, December 3-7, 2017, proceedings, part 23, pp. 409-437. Springer, 2017b.
Ilaria Chillotti, Nicolas Gama, Mariya Georgieva, and Malika Izabachène. Thhe: fast fully homo- morphic encryption over the torus. Journal of Cryptology, 33(1):34-91, 2020.
Gheorghe Comanici, Eric Bieber, Mike Schaekermann, Ice Pasupat, Noveen Sachdeva, Inderjit Dhillon, Marcel Blistein, Ori Ram, Dan Zhang, Evan Rosen, al. Gemini 2.5: Pushing the frontier with advanced reasoning, multimodality, long context, and next generation agentic capa- bilities. arXiv preprint arXiv:2507.06261. 2025..
Junfeng Fan and Frederik Vercauteren. Somewhat practical fully homomorphic encryption. Cryp-
tology ePrint Archive, 2012.
FHERMA. Fherma challenge: Cnn inference.
https::/fherma.i1/// lengess/ 2025a. Accessed: 2025.
652bf 352b666455337770.002222222
FHERMA. Fherma challenge: Mlp inference.
httr:://heamm..oocchllleeggg
bf 648485c3787
2025b. Accessed: 2025.

---

Published as a conference paper at ICLR 2026
Craig Gentry. A fully homomorphic encryption scheme. Stanford university, 2009.
Ran
Nathan Dowlin, Kim Laine, Kristin Lauter, Michael Naehrig, and John Werns- ing. Cryptonets: Applying neural networks to encrypted data with high throughput and accuracy. In International conference on machine learning, pp. 201-210. PMLR, 2016.
Juyong Jiang, Fan Wang, Jiasi Shen, Sungju Kim, and Sunghun Kim. A survey on large language models for code generation. arXiv preprint arXiv:2406.0055 2024.
Lei Jiang, Qian Lou, and Nrushad Joshi. Matcha: A fast and energy-efficient accelerator for fully homomorphic encryption over the torus. In The Design Automation Conference (DAC 2022),
2022.
Weizhao Jin, Yuhang Yao, Shanshan Han, Jiajun Gu, Carlee Joe- Wong. Srivatsan Ravi, Salman Avestimehr, and Chaoyang He. Fedml-he: An efficient cammomopphi--ncccyptoo---sssssse privacy- preserving federated learning system. arXiv preprint arXiv:2303. 10837, 2023.
K Rustan M Leino. Dafny: An automatic program verifier for functional correctness. In Interna-
tional conference on logic for programming artificial intelligence and reasoning, pp. 370-370. Springer, 2010.
Yuchao Liao, Tosiron Adegbija, and Roman Lysecky. Are ilms any good for high-level synthesis? arXiv preprint arXiv:2408. 10428, 2024.
Aixin Liu, Bei Feng, Bing Xue, Bingxuan Wang, Bochao Wu, Chengda Lu, Chenggang Zhao, Chenggi Deng, Chenyu Zhang, Chong Ruan, et al. Deepseek-v3 technical report. arXiv preprint 2944:22412.19437, 2024.
Qian Lou and Lei Jiang. She: A fast and accurate deep neural network for encrypted data. In Advances in Neural Information Processing Systems (NeurIPS) 2019, pp. 10035-10043, 2019.
Qian Lou and Lei Jiang. Hemet: A comommophic-enccrytioon---m neural network architecture. ICMI. 2021, 2021.
mobile
Qian Lou, Bo Feng, Geoffrey Fox, and Lei Jiang. Glyph: Fast and accurately training deep neural networks on encrypted data. NeurlPS 2020 (Advances in Neural Information Processing Systems), 2019a.
Qian Lou, Feng Guo, Lantao Liu, Minje Kim, and Lei Jiang. Autoq: Automated kernel-wir neural network quantization. In International Conference on Learning Representations (ICLR) 2020, 2019b.
Qian Lou, Yilin Shen, Hongxi Jin, and Lei Jiang. Safenet: A secure, accurate and fast neural network inference. 2021.
Varun Madathil and Alessandra Scafuro. Prifhete: Achieving full-privacy in account-based cryp- tocurrencies is possible. Cryptology ePrint Archive, 2023.
Antonio Mastropaolo, Luca Pascarella, Emanuela Guglielmi. Matteo Ciniselli, Simone Scalabrino, Rocco Oliveto, and Gabriele Bavota. On the robustness of code generation techniques: An em- pirical study github copilot. In 2023 IEEE/ACM 45th International Conference Software Engineering (ICSE), pp. 2149-2160 IEEE, 2023.
Erik Nijkamp, Bo Pang, Hiroaki Hayashi, Lifu Tu, Huan Wang, Yingbo Zhou, Silvio Savarese, and Caiming Xiong. Codegen: An open large language model for code with multi-turn program synthesis. arXiv preprint 22X1: 2022.
OpenAl. Introducing GPT5. https:// httt:////////////rrrcciiiiiginn. gust 2025. Accessed: 2025-09-21.
Au- Jean Louis Raisaro, Gwangbae Choi, Sylvain Pradervand, Raphael Colsenet, Nathalie Jacquemont, Nicolas Rosat, Vincent Mooser, and Jean-Pierre Hubaux. Protecting privacy and security of ge- nomic data in i2b2 with homomorphic encryption and differential privacy. IEEE/ACM transac- fions computational biology and bioinformatics, 15(5):1413-1426, 2018.
12

---

Published as a conference paper at ICLR 2026
Microsoft
Research. crosoft edge.
Password monitor:
Safeguarding passwords in mi-
https::/www.micet http:///ww..oocrss.fffooooo
2020.
Accessed: 2025.
Muhammad Husni Santriaji, Jiaqi Xue, Qian Lou, and Yan Solihin. Dataseal: Ensuring the verifia- bility of private computation on encrypted data. arXiv preprint arXiv:2410.1522 2024.
Shailja Thakur, Baleegh Ahmad, Zhenxing Fan, Hammond Pearce, Benjamin Tan, Ramesh Karri, Brendan Dolan-Gavitt, and Siddharth Garg. Benchmarking large language models for automated verilog rtl code generation. In 2023 Design, Automation Test in Europe Conference & Exhibi- fion (DATE), pp. 1-6. IEEE, 2023.
Yue Wang, Weishi Wang, Shafiq Joty, and Steven CH Hoi. Codet5: Identifier-awarr unified pre-trained encoder-decoder models for code understanding and generation. arXiv preprint arXiv:2109.00859, 2021.
Chenwei Xiong, Cheng Liu, Huawei Li, and Xiaowei Li. Hlspilot: Lim-based high-level synthesis. arXiv preprini wrXiv:2408.068111 2024.
Jiaqi Xue, Lei Xu, Lin Chen, Weidong Shi, Kaidi Xu, and Qian Lou. Audit and improve robustness of private neural networks encrypted data. arXiv preprint arXiv:2209.09980 209.22999...99 2022.
An Yang, Anfeng Li, Baosong Yang, Beichen Zhang, Binyuan Hui, Bo Zheng, Bowen Yu, Chang Gao, Chengen Huang, Chenxu Lv, et al. Qwen3 technical report. arXiv preprint arXiv:2505.09388, 2025.
Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao. React: Synergizing reasoning and acting in language models. In International Conference on Learning Representations (ICLR), 2023.
ZlLabs. What is fhevm? https: zwlabs hhl.aaa.aa/yyppheres-eee--ttttho
what-1s- what-1s-fhevm 2024. Accessed: 2025.
Zama. Concrete ml documentation. http::::/docss.aaa.orrog..
2024.
2024. Ac-
cessed: 2025.
Yancheng Zhang, Xun Chen, and Qian Lou. Hebridge: Connecting arithmetic and logic operations in fv-style he schemes. In Proceedings of the 12th Workshop Encrypted Computing & Applied Homomorphic Cryptography, pp. 23-35, 2023.
Yancheng Zhang, Mengxin Zheng, Yuzhang Shang, Xun Chen, and Qian Lou. Heprune: Fast private training of deep neural networks with encrypted data pruning. Advances in Neural Information Processing Systems, 37:51063-51084, 2024.
Yancheng Zhang, Jiaqi Xue, Mengxin Zheng, Mimi Xie, Mingzhe Zhang, Lei Jiang, and Qian Lou. Cipherprune: Efficient and scalable private transformer inference. arXiv preprint 257. 2025.
Mengxin Zheng, Qian Lou, and Lei Jiang. Primer: Fast private transformer inference on encrypted data. DAC 2023, 2023.
A APPENDIX
A FULL CODE EXAMPLE: BITWISE RELU
Below is full working example for bitwise ReLU operation. Listing 1 provides complete, runnable program demonstrating the plaintext bitwise logic, which reads an integer from standard input. Listing shows the full, equivalent implementation using the TFHE library.
13

---

Published as a conference paper at ICLR 2026
#inelude <stdio.h>
Vinclude <stdint.h>
// Flaintext bitwise ReLJ for 32-bit signed integer. int32_t r input) {
int32_t mask input 31;
int32_t cutput input & "mask;
return output;
int main()
12
int32_t input_val;
13
scanf ("Sd", sinput_val);
16
printf("Sdhn", (eigptuuttvval)
17
18
return 0;
Listing 1: Complete, runnable plaintext C code for bitwise ReLU.
#include <tihe/tfhe.be h>
#inalude <tfhe/tfhe_io
#inalude <stdio.h>
#include <assert.h>
// The plaintext relu function would be included here int32_t relu input);
int
(ain()
// 1. Generate keyset
const int minimum_lambon 110;
12
ThicareBoosstrppppngaaaaatteeeee params new
moinimum_lamblaa
13
// Generate deterministic key reproducibility
15
uint32_t seed| 314, 1592, 657 );
16
efhe_rreiiomngeeerrttosssstttee (seed 3);
17
ineesteesrrtrrrpppngeeeertrreaee key
neg_:cabornggggeboooerrrrrrrannr (params);
19
int32_t plaintextl; scanf ("$d", &plaintextl);
20
// 2. Encrypt the 32-bit signed integer bit by bit IwcSamplc* ciphertext1 ooo._atfcbbottrrapppo...ollttttd params);
23
(32,
24
for (int i 0, i < 32; i++) {
beotssynEncrypt (sciphertext [i], (plaintextl >> i) & 1, key);
27
28
// 3. Homemorphically compute ReLU: result = input & "mask
29
LweSample* result hes.aatt_eccsrrppppiigeeeeeereee params); LweSample* mask ber.alteeeattrrppppppppppeeerrer
params)
31
// 3a. Create 32-bit mask from the encrypted sign bit (bit 31) for (int i=0; i<32; i++) {
34
bootsCoPY (maask[), sciphertext1(31) skey->cloud);
35
36
// 3b. Invert the mask homomerphically for (int i-0; i<32; i++){
14

---

Published as a conference paper at ICLR 2026
bootsNNT (ámask (i), smask[il, akey->aloud),
40
41
42
// 3c. Compute the final result: input & "mask for (int i = 0; i 32; i+t){
bootsAND (fresult sciphertextl smask(il, skey->cloud) ;
45
46
47
4. Decrypt the result for verification
int32_t sinal result 0; for (int i 32; i++) {
50
int bit byotssymp (Gresult[i), key); final_result 1- (bit << i);
51
printf ("Sdht", final_resuly
54
55
// Verify against the plaintext function assert (final_resule == relu(plaintext1))
56
// Cleanup
59
de delete_gatd
(32, mask);
60
delete_
(32, result);
delete_ htt.://www.oottsaooooo.oooooorra (32, ciphertextl);
delete belete_gate satte.bootsttapppngssseeetttttte keyset (key):
63
delete gate www.stoappiggggoottt.. pwwppppppppipppppttaeaeaeeaeee (params)
64
65
return 0;
Listing 2: Full secure TFHE implementation for bitwise ReLU,
B USING VANILLA RAG
Table 3: Results for Using Vanilla RAG with Documentation (without preprocessing with expert summary). Standard RAG fails to provide robust security functionality.
Workload
pass@1 (func.)
pass 1 (sec.)
ReLU
0.40 + 0.02
0.20 + 0.01
MatMul
0.20 + 0.01
0.00 0.00
C RESULTS ON ADDITIONAL TASKS (AND SCHEMES)
Table 4: Comparison of functional correctness and security Pass@I rates for TFHE workloads using GPT-5 across different prompting strategies (BAS, COT, and FRS).
Workload
I
p (sec.)
pi (9es.)
pul
FHEECCoder (sex.)
MarMul
0.00 0.00
0.00 + 0.00
0.00 0.00
0.00 0.00
0.80 : 0.05
1.00 0.00
Sotmax
0.80 = 0.03
0.00 + 0.00
0.60 = 0.02
0.00 2 0.00
1.00 0.00
1.00 : 0.00
Amention
0.00
0.00
0.02
Transformrr
0.00 0.00
0.00 4: 0.00
0.20 0.00
0.00 0.00
0.40:1000
0.50 2: 0.02
Table 5: Comparison of functional correctness and security Pass@1 I rates for CKKS workloads using GPT-5 across different prompting strategies (BAS, COT, and FHE- (oderr.er).
Workloud
BAS (func.)
BAS
COT (func.)
COT por (sec.)
FHle-Coder (func.)
FHlE-Coder (sec.)
MarMol
100 0.10
1.001 12000
0.50 0.01
0.10 0.00
1.30100 0.01
0.00 0.02
Soltma
1.00 0.00
0:00 4: 0.00
0.80 - 0.03
0.00 2 0.00
0.80 0.02
0.60 1:00:200 0.02
Atsenion
0.10 = 0.02
6.00 1 0.00
0.30 2 0.01
0.00 2: 0.00
1.00 4 0.00
1.00 1 0.00
Transfommer
0.00
0.00 0.00
0.03
15

---

Published as a conference paper at ICLR 2026
D SAMPLE FORMAL PROMPTS: AND TASK
To concretely illustrate the output of the FHE Prompt Formalizer (Section 3.1 we show the developer-supplied natural-language description and the corresponding structured formal prompt generated for the AND task (bitwise AND of two 32-bit integers).
Developer input.
Implement homomorphic bitwise AND between two 32-bit integers using THEE. The LIE parameter should be 1024.
Formal prompt (output of FHE Prompt Formalizer).
Context:
You are expert crypto-coder with deep knowledge of the TFEE C library. Generate only ciphertext-compl iant code using the TFHE gate-bootstrapping API. Do not use plaintext values in any homomorphic operation.
Objective:
Implement a bitwise AND operation on two encrypted 32-bit signed integers.
Each integer is represented as an array of 32 LweSample ciphertexts, where bit i of plaintext is stored in ciphertext(i).
Security Parameters (derived via Lattice Estimator):
minimun_lambar 110 (targeting lambda 128-bit LWB security)
Use: nev_randon_.atte_oottttaaaapppp
(minimum_lambda) keyset (params)
Use:
Code Requirements:
Functional:
for all in [0, 32)
decrypt (result decrypt (a[l) decrypt (bli])
Security:
(i) All inputs must be encrypted with bootssymEnerypt before any gate call.
(ii) plaintext integers may be passed directly gate operations.
(iii) Cryptographic parameters must satisfy sinimum_lambde >= 110.
Reference Pseudocode (Dafny formal specification):
method BitwiseAND (a: array<twesSmmplee>
b: array<lweSSapple>>
key: ThosaceBoostrapiingecrretteeerrr returns (result: array([weSamplee>
requires Length = 32 & b. Length == 32 requires forall i
<= i < 32 ==>
(a
key) & IsEncrytted (b key)
ensures DssultLength)
32
ensures forall i :: 0 <= i < 32 ==> Decrypt (result key) (Decrypt (a[i), key) & Decrypt (b[i], key)
result := new [
for := to 31 { bootsAND (result(i), a[i), b[i], key.cloud)
assert (ressul [i], key);
16

---

Published as a conference paper at ICLR 2026
The four fields Context, Objective, Security Parameters, and Reference Pseudocode gen- erated by the Formalizer. Note that the user's original (incorrect) LWE value of 1024 is silently overridden: the Lattice Estimator determines that minimum 1ambda=110 is the correct parame- ter to achieve the target security level, and this derived value appears in the formal prompt instead. The RAG Retriever then augments this prompt with relevant TFHE API snippets (e.g., boot SAND usage examples) before it is delivered to the ReAct agent.
D UNIT TEST CREATION
Test unit construction. For each benchmark task, fixed set of 5 unit tests is manually written by the authors (as illustrated in the Formal Error Report in Figure which shows "Functional: 3/5 Tests Passed"). Each test specifies a concrete input drawn from the task's valid input domain for example, pair of 32-bit signed integers for AND and Adder, an integer vector of length 5 for Dot Product and Vector Addition, or an integer matrix for Mat-Vec and Mat-Mat executes the generated FHE program with that input, decrypts the ciphertext output, and compares it against a plaintext reference implementation that serves as ground truth. Inputs are sampled randomly within the valid domain using a fixed seed for reproducibility Since results are aggregated over five independent runs with distinct seeds, the reported variance in Pass @ (func) reflects both LLM output stochasticity and sensitivity to input values.
E STRUCTURED PROMPT CREATION
Concretely, the composer agent's 's prompt is constructed by concatenating the fully verified C++ im- plementations of all required primitives each already checked by the Security Verifier into the Reference Pseudocode field of the standard formal prompt, followed by the high-level compo- sition goal the Objective. This supplies the agent with eryptographically sound building blocks directly in context, eliminating the need to regenerate or re-verify sub-routines during composition. We evaluate this strategy in detail in Section 5.3
F RAG PIPELINE CREATION
The RAG knowledge base for TFHE is built from two primary sources: (i) the official TFHE C library headers and gate-bootstrapping API documentation, and (ii) expert-curated code snippets demonstrating correct API usage (e.g., proper bit-level encryption with boot cor- rect noise-aware gate sequencing). As illustrated in Figure 3b human FHE experts perform a one-time offline annotation pass in which each function's docstring enriched with structured @ob jobjectio i ve tag encoding its cryptographic purpose, noise constraints, and usage preconditions, then paired with a representative code snippet. Retrieval operates over these annotated entries so that the agent receives snippets matched by cryptographic intent rather than surface-level keyword similarity. For CKKS, the corpus is constructed identically by substituting the TFHE documenta- tion and annotation set with the corresponding CKKS library sources, confirming that RAG corpus construction is scheme-aa acheme-agnostic and requires no Tramework-lewe changes.
17


Reviews:
[{"review_id": "lSTTmaEBS9", "reviewer": "Reviewer_jFYL", "summary": "This paper investigates the potential of Large Language Model (LLM) agents to automate the generation of secure Fully Homomorphic Encryption over the Torus (TFHE) code from natural language. (Fig 2 of the paper gives a giid outline of the method.) The role of LLMs is to respond to user intent, configure secure parameters,  adapt the API, and leverage an automated security verifier that provides iterative feedback to correct cryptographic flaws. The system produces code that is compilable, functionally correct, and verifiably secure.  The focus on TFHE, as opposed to other FHE schemes, is based on the  efficient gate bootstrapping and functional bootstrapping, which allow computation of arbitrary functions while refreshing noise.", "questions": "What would be needed to generalize this work beyond TFHE?  There are likely other programming tasks where LLMs could have relevant knowledge about parameters and there could be appropriate verification techniques.  If someone provided versions of FHE Prompt Formalizer, FHE API RAG Retriever and FHE Security Verifier. for another problem, would hte method be likely to work?  Why or why not?", "limitations": "", "rating": 6, "confidence": 3, "soundness": 3, "presentation": 3, "contribution": 3, "strengths": "This seems to be a good case study of using LLMs, in combination with structured workflow and other tools, to solve a specific programming problem with modest scope.  The focus on TFHE will be a plus for specific audience.", "weaknesses": "From an application perspective, the focus on TFHE is specialized, limiting the apparent audience for this work.  How many people need TFHE code and how much variety is there among possible users? \nFrom a scientific perspective, it is not clear how much of the difficulty, or how much of the apparent success of the approach is due to particular characteristics of TFHE.   \nFurther, it is hard to see from the conference-length writeup how broad the solution is (how different are different requests for TFHE code?) and how compelling the verification is.   A little more information on how fully the code is verified would be helpfui.", "quality": null, "clarity": null, "significance": null, "originality": null, "strengths_and_weaknesses": "", "was_revised": false, "final_justification": "", "rebuttal": "", "claims_and_evidence": "", "methods_and_evaluation_criteria": "", "theoretical_claims": "", "experimental_designs_or_analyses": "", "relation_to_broader_scientific_literature": "", "essential_references_not_discussed": "", "other_strengths_and_weaknesses": "", "other_comments_or_suggestions": "", "questions_for_authors": "", "summary_of_paper": "", "summary_of_recommendation": "", "technical_quality": "", "clarity_of_presentation": "", "potential_impact": "", "robotics_focus": "", "quality_of_limitations": "", "questions_for_rebuttal": "", "reasons_to_accept": "", "reasons_to_reject": "", "questions_to_authors": "", "extra_scores": {}}, {"review_id": "pGImVYqN2F", "reviewer": "Reviewer_er3J", "summary": "This paper targets an important problem of automatically generating secure API calls and parameters for Fully Homomorphic Encryption over Torus (TFHE). It proposes to leverage the power of agentic large language models (LLMs) to generate TFHE API calls and parameters, with the assistance of Retrieval-Augmented Generation (RAG) and post validation techniques. Evaluation on a set of tasks shows that the method outperforms vanilla prompting and Chain-of-Thought (CoT) prompting.", "questions": "Generating secure API calls and parameters for TFHE is an important problem, as developers often lack cryptographic expertise in programming TFHE applications. The proposed method leverages agentic LLMs with enhancements like RAG and post validation to improve the generation accuracy. However, there are several concerns over the empirical evaluation and technical contributions.\n\nThe evaluation of the proposed method is limited. The benchmark tasks are simple Machine Learning (ML) tasks, which are as simple as vector/matrix multiplications and basic ML models like MLP or CNN. These tasks are often too simple to demonstrate the effectiveness of the proposed method, as human developers can also easily implement these tasks. It would be more convincing to show the effectiveness of the method on more complex and diverse tasks, including natural language processing models, transformer-based models, and other non-ML tasks. Additionally, the reproducibility of the evaluation is not well demonstrated. Although the paper mentions that the seeds are fixed, the randomness in LLM generation can still lead to variance in results. It would be helpful to repeat each experiment multiple times and report the average performance with confidence intervals.\n\nThere is limited guarantee on the security and functional correctness of the generated TFHE programs. While the post validation step is a safe-guard to filter out incorrect programs, the paper cannot ensure that the validation conditions are correct and comprehensive. For instance, how do we know that the verification conditions in Dafny code are sufficient to eliminate all security vulnerabilities? Also, it is not clear that how the proposed method can ensure that the generated conditions are aligned with the developer's intent. More discussion on these aspects would be helpful.\n\nThe technical contributions of the paper appear incremental. The use of RAG and post validation are not new techniques in the context of LLMs. This work is a simple application of such techniques to the TFHE domain. The contributions would be stronger if such a technique can also extend to other cryptographic domains other than TFHE, such as MPC, partial HE, or ZK proofs.", "limitations": "", "rating": 4, "confidence": 4, "soundness": 2, "presentation": 3, "contribution": 2, "strengths": "- Addresses an important and practical problem of generating secure TFHE API calls and parameters.\n- Clear writing and well-structured presentation.", "weaknesses": "- The evaluation tasks are limited in complexity, diversity, and reproducibility.\n- No guarantee on the security and functional correctness of the generated programs.\n- Limited novelty in the technical contributions, where RAG and post validation are not new.", "quality": null, "clarity": null, "significance": null, "originality": null, "strengths_and_weaknesses": "", "was_revised": false, "final_justification": "", "rebuttal": "", "claims_and_evidence": "", "methods_and_evaluation_criteria": "", "theoretical_claims": "", "experimental_designs_or_analyses": "", "relation_to_broader_scientific_literature": "", "essential_references_not_discussed": "", "other_strengths_and_weaknesses": "", "other_comments_or_suggestions": "", "questions_for_authors": "", "summary_of_paper": "", "summary_of_recommendation": "", "technical_quality": "", "clarity_of_presentation": "", "potential_impact": "", "robotics_focus": "", "quality_of_limitations": "", "questions_for_rebuttal": "", "reasons_to_accept": "", "reasons_to_reject": "", "questions_to_authors": "", "extra_scores": {}}, {"review_id": "oRdlIsZWcj", "reviewer": "Reviewer_c3tK", "summary": "The paper introduces TFHE-CODER, a three-stage agentic framework for secure Fully Homomorphic Encryption (FHE) programming. Unlike conventional code generation approaches that rely solely on post-hoc human inspection, TFHE-CODER enables large language models (LLMs) to proactively integrate security constraints during the generation process. The framework comprises three key components: FHE Prompt Formalizer, FHE API RAG Retriever, and FHE Security Verifier. To systematically evaluate the framework’s effectiveness, the authors constructed the TFHE-CODER Benchmark, consisting of ten FHE programming tasks. Experimental results demonstrate that large language models can autonomously generate FHE programs that are not only functionally correct and compilable but also verifiably secure.", "questions": "Please refer to my comments on weaknesses.", "limitations": "", "rating": 6, "confidence": 3, "soundness": 3, "presentation": 3, "contribution": 3, "strengths": "1. The authors propose an end-to-end agentic framework explicitly designed around security. By integrating prompt formalization, retrieval, and automated security verification into a closed feedback loop, the system treats security correctness as a primary objective rather than a post-generation check.\n2. The framework’s security verifier can automatically identify multiple classes of critical vulnerabilities and generate structured Formal Error Reports, enabling the agent to iteratively refine and correct insecure code.\n3. The paper introduces a novel metric specifically tailored for security-critical code generation. This metric complements traditional functional correctness measures and prevents misleading conclusions based solely on task completion accuracy.", "weaknesses": "1. The RAG dictionary requires offline preparation and manual expert involvement, which limits the framework’s degree of automation and scalability.\n2. The paper does not provide detailed measurements of computational overhead, runtime latency, or resource consumption introduced by the multi-stage verification process, making it difficult to assess practical efficiency.\n3. While the framework performs well on simple FHE operations, its success rate drops significantly on more complex tasks.", "quality": null, "clarity": null, "significance": null, "originality": null, "strengths_and_weaknesses": "", "was_revised": false, "final_justification": "", "rebuttal": "", "claims_and_evidence": "", "methods_and_evaluation_criteria": "", "theoretical_claims": "", "experimental_designs_or_analyses": "", "relation_to_broader_scientific_literature": "", "essential_references_not_discussed": "", "other_strengths_and_weaknesses": "", "other_comments_or_suggestions": "", "questions_for_authors": "", "summary_of_paper": "", "summary_of_recommendation": "", "technical_quality": "", "clarity_of_presentation": "", "potential_impact": "", "robotics_focus": "", "quality_of_limitations": "", "questions_for_rebuttal": "", "reasons_to_accept": "", "reasons_to_reject": "", "questions_to_authors": "", "extra_scores": {}}]

Author rebuttal:

Decision: Accept (Poster)