In wireless sensor networks, the sensors transfer data through radio signals to a remote base station. Sensor nodes are used to sense environmental conditions such as temperature, strain, humidity, sound, vibration, and position. Data security is a major issue in wireless sensor networks since data travel over the naturally exposed wireless channel where malicious attackers may get access to critical information. The sensors in wireless sensor networks are resource-constrained devices whereas the existing data security approaches have complex security mechanisms with high computational and response times affecting the network lifetime. Furthermore, existing systems, such as secure efficient encryption algorithm, use the Diffie–Hellman approach for key generation and exchange; however, Diffie–Hellman is highly vulnerable to the man-in-the-middle attack. This article introduces a data security approach with less computational and response times based on a modified version of Diffie–Hellman. The Diffie–Hellman has been modified to secure it against attacks by generating a hash of each value that is transmitted over the network. The proposed approach has been analyzed for security against various attacks. Furthermore, it has also been analyzed in terms of encryption/decryption time, computation time, and key generation time for different sizes of data. The comparative analysis with the existing approaches shows that the proposed approach performs better in most of the cases.