How to Encrypt/Decrypt a String

Screenshot of example program

Environment: VC6 SP5, Windows XP SP1p

Based on the article “Encrypting and Decrypting Sensitive Data Using CryptoAPI” by Jorge Lodos in the Miscellaneous/CryptoAPI section and many questions in the forum (how to encrypt/decrypt a string—also from me), I have adapted this project for this purpose. My project doesn’t use the Registry; the string is returned from the function.

Three functions are needed for encryption/decryption:

  • Initialize CryptoAPI.
  • Encryption function that takes the original string and the key.
  • Decryption function that takes the encrypted string and the key and returns the decrypted function.

The prototypes for the functions are:

BOOL SetupCryptoClient();
BOOL EncryptString(TCHAR* szPassword,TCHAR* szEncryptPwd,TCHAR
BOOL DecryptString(TCHAR* szEncryptPwd,TCHAR* szPassword,TCHAR

The meanings of the functions and parameters are following:

  • BOOL SetupCryptoClient();

    Initialize the crypto client

  • BOOL EncryptString(TCHAR* szPassword,TCHAR*
                              szEncryptPwd,TCHAR *szKey)

    Encrypt a string:

    • Where szPassword is the original password,
    • szEncryptPwd is the result, and
    • szKey is the key for encryption.
  • BOOL DecryptString(TCHAR* szEncryptPwd,TCHAR*
                              szPassword,TCHAR *szKey)

    Decrypt a string:

    • Where szEncryptPwd is the encrypted password,
    • szPassword is the decrypted password, and
    • szKey is the key for decryption, which must be the same as in the encryption function.

The main routine of the console application should explain the function of the encryption/decryption functions.

Condition for Compiling

It costs me hours to resolve a compiler error where the data type HCRYPTPROV is not defined. The reason:

  • clear the #define WIN32_LEAN_AND_MEAN (doesn’t compile often-used parts)
  • #define _WIN32_WINNT 0x0400
  • For Linker: add library “advapi32.lib” in settings

Considerations for the C++ Class

  • Generate a class: for example, CCryptString.
  • In the constructor, call the init-function SetupCryptoClient and save the result in a member variable.
  • Copy the encryption/decryption functions in the class.

The second program contains an example of such a class and also the usage.

For background information about decryption, read the above-mentioned article and the MSDN. A lot of stuff also be found on the Internet.

I hope this project meets your expectations.

If you found any errors, please let me know. If I have time, I will implement solutions to the errors found.

Best regards,
Ing. Georg Hasenöhrl
Working as a software developer (C++/VB/SQL) at Hakom (IT Consulting)


Crypt String with C-functions – 5 Kb

Crypt String as C class – 6 Kb

More by Author

Must Read