How to encryptdecrypt a string

xiaoxiao2021-03-06  14

Author: John_Sheridan

[Translator] This paper introduces a use of directly calling the CryptoAPI function to encrypt and decrypt the string, which is very simple, practical. Among them, there is an encrypted / decryption class packaged by the author, which is the source code that can be reused. I think it is possible to solve some of our practical problems. Moreover, the initialization function is packaged in the constructor, and it is also very clever, and for beginners, it is a good textbook.

Three functions required for encryption / decryption:

1. Initialize the function of CRYPTOAPI.

2, encryption function. The input parameter is the original string and a key.

3, decryption function. Enter the parameter as the encrypted string and a key.

The prototype of these functions is as follows:

Bool setupcryptoclient ();

Bool Encryptstring (Tchar * Szpassword, Tchar * Szencryptpwd, Tchar

* szkey);

Bool Decryptstring (tchar * szencryptpwd, tchar * szpassword, tchar

* szkey); the function and its parameters have the following:

Bool setupcryptoclient (); This function initially disinsubes the client.

Bool Encryptstring (Tchar * Szpassword, Tchar *

Szencryptpwd, tchar * szkey)

Encrypt a string

1, szpassword is the original string

2, szencryptpwd is the result after encryption

3, SZKEY is an encrypted key

Bool Decryptstring (tchar * szencryptpwd, tchar *

Szpassword, tchar * szkey)

Decrypt a string

1, SzencryptPWD is an encrypted string

2, szpassword is the restriction of the decryption

3, SZKEY is the decryption key. It must be consistent with the keys used when the string is encrypted.

The program is a console program that mainly wants to explain the use of encryption / decryption functions.

Compilation conditions

If the data type of HcryptProv is referenced, the compilation cannot be passed, and the following method can be solved:

1, clear #define win32_lean_and_mean

2, plus: #define _win32_winnt 0x0400

3, in the link setting, add library "Advapi32.lib"

C consider

1, generate a class, such as ccryptstring.

2. In the constructor, the initialization function setupCryptoClient is called, and the result is saved in a member variable.

3. Pack the encryption / decryption function directly in the member function of the class.

The second example contains a class of usage.

For background information about the encryption technology, please read the relevant content of MSDN. There are also many relevant information on the Internet. I hope this demo project can meet your needs.

Code download

转载请注明原文地址:https://www.9cbs.com/read-50261.html

New Post(0)