Shape Before You Build: Secure Cryptographic Code Generation via Prompt Optimization
摘要
Cryptographic programming is a critical yet challenging task in software development, demanding extensive knowledge of cryptography and hands-on implementation experience. Minor oversights such as improper parameter configuration or outdated library usage can easily lead to cryptographic misuse, introducing severe security vulnerabilities. With the advancement of large language models (LLMs), LLM-assisted cryptographic programming has become increasingly popular, offering substantial support to developers with limited cryptographic expertise. However, due to limitations in training data and the inherent hallucination problems of LLMs, the security of generated cryptographic code remains inadequate, with a high risk of misuse. In this study, we propose Nemo, a prompt-level secure cryptographic code generation framework. Nemo employs a multi-task learning-based prompt risk analysis strategy alongside a multi-source security enhancement strategy to detect and optimize potential misuse risks embedded in developer prompts, thereby ensuring secure code generation. We evaluate Nemo on 2,775 real-world cryptographic code comments collected from GitHub projects and 366 cryptographic programming queries collected from Stack Overflow. Experimental results show that Nemo can effectively analyze the potential risk regarding specific cryptographic programming tasks and significantly improve code security while preserving functional correctness: it can successfully identify potential risks for over 90% of cryptographic programming tasks and reduce the rate of cryptographic misuse by 94.7% compared to direct code generation. Furthermore, relative to state-of-the-art automatic program repair approaches, Nemo achieves an additional 76% and 78% reduction in misuse cases, respectively, with negligible extra token overhead.