Simplified encryption in Microsoft .NET

xiaoxiao2021-03-06  21

Paul D. Sheriff

PDSA.com

October 2003

Suitable for: Microsoft® .NET Security Microsoft® Visual Basic® .NET C #

Summary: Learn how to use the .NET Framework's encryption function to create a package similar to this article to protect your data.

Download the Cryptosamplesample.msi and Cryptosamplevbsample.msi code examples related to this article. (Note that in the sample file, the programmer's annotation is used in English. In this article, it is translated into Chinese to facilitate the reader's understanding.)

table of Contents

Hash Introduction Creating Example Solutions Added "Salt" value in the hash

Do you want to save some confidential information on your computer? If so, this article describes how to encrypt! Encryption technology is to encode meaningful characters into meaningless characters that should not be accessed by those who should not access them. Encryption technology has existed for many years, and it has already existed before the computer is born. With the appearance of the computer, application encryption technology in the computer field can generate almost unbreakable code. Microsoft has developed and distributed encrypted APIs in Windows 95. Using Microsoft .NET, the newly created class can package these complex algorithms into properties and methods that are very easy to use.

Hash introduction

If you just don't want others to steal your password, you can create a hash for password data. Human is a one-way algorithm that once the data is converted, its original value will not be obtained. Most developers use the database store password. However, those who find user data in the database can also see these passwords. However, you can use a hash algorithm to encrypt your password and then store it in the database. After the user enters the password, you can use the hash algorithm to decrypt it, and then compare it with the hash stored in the database. One of the disadvantages of the hash is that even if the original data only occurs a small change, the data has a very large change. These two words are very similar, but the result after encryption using the hash algorithm is far from the result. You may not see anything between both.

.NET developers can use a variety of hash algorithms. The most commonly used are SHA1 and MD5. Let's take a look at how to generate a hash for a normal string such as "Paul", so that anyone can not recognize it.

Use SHA1 to generate a hash

We created a new routine and then use it to generate a hash as a string "paul". Open a new Windows application in the Visual Studio® .NET, place a command button on the form. When the Click event occurs on the command button, a method called HashText () is called. You can add the following code to the form and see the actual effect of this hash algorithm. Before writing the following code, you need to import namespace system.security.cryptography.

Private Sub Hashtext (Byval Texttohash As String)

Dim Sha1 As Sha1cryptoserviceProvider

DIM BYTVALUE () AS BYTE

DIM BYTHASH () AS BYTE

'Creating a new encryption service provider object

Sha1 = new sha1cryptoServiceProvider

'Convert the original string into byte arrays

ByTValue = _

System.Text.Encoding.utf8.getbytes (Texttohash)

'Calculate the hash and return a byte array

Bythash = sha1.computehash (bytvalue)

Sha1.clear ()

'Base64 encoded string of the column value (convert.tobase64string (bythash))

End Sub

You can pass different string values ​​to call this routine to view changes in the havexiety. For example, if you pass the string "paul" to this routine, the debug window will display the following text:

W2H6UYGMJT / NQ5ZQIHCBTEAXWV8 =

Now, change the input value in this process to "pauly". You will see the following output:

ProYwxj0znmpGF5SBB18 7GSASM =

As you can see, a small change in the input string produces a completely different character combination. This is the reason why the hash algorithm is effective, which makes it difficult to find the law of the input string, and it is difficult to figure out the character string in accordance with the encrypted characters.

Use MD5 can also generate a hash

After understanding the use of a hash class, basically understand all havers. The following method is used for the MD5 hash algorithm. Note that the code is identical except for the CryptoServiceProvider class.

Private sub hashtextmd5 (Byval Texttohash As String)

DIM MD5 AS MD5CryptoServiceProvider

DIM BYTVALUE () AS BYTE

DIM BYTHASH () AS BYTE

'Creating a new encryption service provider object

MD5 = New MD5CryptoServiceProvider

'Convert the original string into byte arrays

Bytvalue = system.text.encoding. _

Utf8.getbytes (TextTohash)

'Calculate the hash and return a byte array

Bythash = md5.computehash (BytValue)

Md5.clear ()

'Returning the Base64 encoded string of the column value

Debug.WriteLine (Convert.TOBASE64String (bythash))

End Sub

After entering "paul", the output results of the MD5 hash algorithm are as follows:

nvwbshh1mknctpiosyqytq ==

Similarly, the encrypted string looks far from the original input. These hash algorithms are very useful for creating a password without any meaning, but also make hackers to guess these passwords. The reason why the hash algorithm is used because the password can be encrypted and stored in the database. Then, when the user enters a real password, you decrypt your password, then send it to the database via the network, compare whether it matches the password in the database. Remember that the hash is one-way operation. Use a hash algorithm to encrypt the original password after encryption.

How to choose an algorithm

Both hash algorithms described herein perform the same operation. Different from the generated a hash size and algorithms used. The more you use the key, the safer is encrypted. For example, the encryption key used by the MD5 is larger than the key used by SHA1, so the MD5 hash is more difficult to crack.

Another point for the hash algorithm should be considered, see if there is a conflict from the perspective of practical or theory. Conflicts are all we don't want, because two different words may generate the same hash. For example, SHA1 does not have conflict from practice or theory. MD5 has theoretical possibilities in theory, but there is no conflicting possibility from practice. Therefore, which algorithm is selected dependent on the security level you need.

Create an exemplary row project

This article contains two sample hashes projects, with more common ways to encrypt any string using different hash algorithms. The names of these two sample items are cryptosamplevb.sln and cryptosamples.sln, respectively. The former is a Visual Basic .NET solution, the latter is a C # solution. Both solutions include a form similar to Figure 1, which allows you to enter the original string to encrypt through the hash algorithm, and provide an option button to select a hash algorithm and a display hash The text box of the result. Figure 1: Create a universal hash screen to try two hash algorithms.

When you click the Hash button on this screen, the Click event process of the button will run. This event process will call a routine called hashString ().

'Visual Basic .NET

Private sub bithhash_click (byval sender as system.object, _

Byval e as system.eventargs) Handles btnhash.click

TXTHASHED.TEXT = HashString (txtORIGINAL.TEXT)

End Sub

// c #

Private void cmdhash_click (Object Sender,

System.Eventargs E)

{

TXTHASHED.TEXT = HashString (txtORIGINAL.TEXT);

}

The HashString () method accepts the input value and calls the setHash () method. This method will determine which encryption service provider creates an instance of the method and returns the method based on the setting of the form of the form. A member variable named Mhash Hashalgorithm type will be created for the form. The Hashalgorithm type is the base class that creates all hash encrypted service providers.

'Visual Basic .NET

Private Mhash As Hashalgorithm

// c #

Private hashalgorithm mhash;

The setHash () method is as follows:

'Visual Basic .NET

Private function set () AS Hashalgorithm

IF OPTSHA1.CHECKED THEN

Return New Sha1cryptoserviceProvider

Else

IF OPTMD5.CHECKED THEN

Return New MD5CryptoServiceProvider

END IF

END IF

END FUNCTION

// c #

Private hashalgorithm sethash ()

{

IF (this.optsha1.checked)

Return New Sha1cryptoServiceProvider ();

Else

Return New MD5CryptoServiceProvider ();

}

Based on the option button you selected on your form, this method will create and return a different Hashalgorithm type. HashString () method performs actual data encryption on this form:

'Visual Basic .NET

Private function hashstring (byval value as string) _

As string

DIM BYTVALUE () AS BYTE

DIM BYTHASH () AS BYTE

'Creating a new encryption service provider object

Mhash = setshash ()

'Convert the original string into byte arrays

BytValue = system.text.encoding.utf8.getbytes (value)

'Calculate the hash and return a byte array

Bythash = mhash.computehash (bytvalue) Mhash.clear ()

'Returning the Base64 encoded string of the column value

Return Convert.TOBASE64STRING (Bythash)

END FUNCTION

// c #

Private string hashstring (String Value)

{

Mhash = setHash ();

// convert the original string into byte arrays

Byte [] bytvalue = system.text.Encoding.utf8.getbytes (value);

/ / Calculate the hash and return a byte array

Byte [] Bythash = Mhash.comPutehash (Bytvalue);

Mhash.clear ();

/ / Return to the Base64 encoding string of the column value

Return Convert.TOBASE64String (bythash);

}

In the HashString method, we created two byte arrays. The first array is used to save the user's raw string input. We use the System.Text.Encoding.utf8.getbytes () method to convert the string into byte arrays. After converting the original string into byte array, the hash value of the string is now calculated using the computehash () method of the service provider. This method accepts the byte array as an input and then returns the byte array of the string encryption format.

Note: Clearing a hash variable after completion is a good practice. Therefore, after you see the hash of the string, we call

Clear method.

Now we have obtained an encrypted byte array, which is the array returned from this method. Because we want to handle the original value and encryption values ​​as a string data type instead of byte arrays, it is necessary to return encrypted bytes by using the Convert.TOBASE64String method. This method is responsible for converting byte arrays to base64 encoded strings. The use of Base64 encoding is very important because it is possible to push this string to the web page or store it into the database. If you do not convert, some high-order ASCII characters in the encrypted string will not be displayed or stored correctly.

Add some "salt" value in the hash

So far, one of the problems exposed by hash algorithm is that if the two users happen to use the same password, the row value will be exactly the same. If hackers see the form that stores passwords, they will find regularities and understand that you are likely to use common words, then hackers will start dictionary attacks to determine these passwords. To make sure that the hash value of any two user passwords is different, a method is to add a unique value in each user's password before encrypted password. This unique value is called "salt" value. When operating this, it is necessary to ensure that the salt value of the use is stored as part of the user record. If you use a table to store user IDs and passwords, I recommend you to store salt values ​​in different forms. In this way, even if the database leaks, the salt value can provide you with extra security protection.

There are many ways to add salt values ​​in the user password. The easiest way is to take some information of the user (eg, a name, name, email address, or employee ID) and add it to the user password, and then encrypt. The disadvantage of this method is that because you need to store the salt value, if the hacker finds this value, you will have everything you do. Of course, hackers need to spend additional time to crack the salt value, but this is simply easy to make a hacker.

Another method is to create a random numeric string using the .NET Framework class RNGCRYPTOSERVICEPROVIDER. RNG represents a random number generator. This class can create an arbitrary length random byte array, and the length is specified. You can use this random byte array as the salt value of the hash algorithm. To use this method, the salt value must be safely stored.

In the example shown in Figure 2, you need to enter a string in the text box, select a specific hash type, then generate a salt value and a hash value including the salt value and the original string. Figure 2: Add a salt value to the hash value to create a safer password hash (you need to store the salt value to create the same hash again.)

This example is basically the same as the previous example in this article, and the difference is the routine of the creation of the salt value. Under the click event of the button on this screen, first call a method called createSalt () to generate a unique salt value and store the value in the TXTsalt text box. After obtaining a unique salt value, then call the HashString () method to combine these two values.

'Visual Basic .NET

Private sub bithhash_click (byval sender as system.object, _

Byval e as system.eventargs) Handles btnhash.click

TXTSALT.TEXT = CREATESALT ()

TXTHASHED.TEXT = HashString (TXTSALT.TEXT & _

txtORIGINAL.TEXT)

End Sub

// c #

Private void cmdhash_click (Object Sender, System.Eventargs E)

{

TXTSALT.TEXT = CREATESALT ();

TXTHASHED.TEXT = HashString (txtORIGINAL.TEXT);

}

The code of the CreateSalt () method is very simple. It first creates a length of 8 bytes of byte arrays and then you create a new RNGCryptoServiceProvider class instance. With the GetBytes () method of this object, populate the generated random character set into the byte array. This byte array is then converted to the base64 encoded string and returned from the function.

'Visual Basic .NET

Private function createsalt () AS STRING

DIM BYTSALT (8) as Byte

DIM RNG AS New RNGCRYPTOSERVICEPROVIDER

RNG.GetBytes (Bytsalt)

Return Convert.TOBASE64String (Bytsalt)

END FUNCTION

// c #

Private string createsalt ()

{

Byte [] Bytsalt = New Byte [8];

RNGCRYPTOSERVICEPROVIDER RNG;

RNG = New RNGCRYPTOSERVICEPROVIDER ();

RNG.GETBYTES (BYTSALT);

Return Convert.TOBASE64STRING (Bytsalt);

}

Data encryption is a double line

If you need to send information from two or more people or computers, and I hope that the other party can read data, and others cannot read, then encryption is the best way! The encryption algorithm allows you to cover up the data, except that the particular person can decrypt it, other people may not read the data by mathematical methods. But if you want someone to read this data, you can provide a specific "key" to decrypt and read data. A variety of available encryption / decryption algorithms in .NET Framework. This article mainly introduces the symmetrical algorithm, including the following:

DES RC2 RIJNDAEL Tripledes

Symmetric algorithm (or key algorithm) uses a key and a initialization vector (IV) to ensure the security of the data. Both sides using this data must know the key and initialization vector to encrypt and decrypt data. You must ensure that the key is secure, otherwise others will be able to decrypt the data and read the message. The initialization vector is just a randomly generated character set, using it to ensure that any two texts do not generate the same encrypted data. The built-in method of different encryption classes in .NET can export the key, as for how to export the key, it is not the content to be discussed herein. Other types of encryption algorithms are called asymmetric algorithms. Asymmetric algorithms use public key / private key pairs to create encrypted data. Asymmetric algorithms will be discussed below.

How to choose different encryption methods in different situations

Symmetric algorithm (or key algorithm) is very fast, very suitable for encrypting large data streams. These algorithms can encrypt data or decrypt data. They are quite safe, but if there is enough time, it may be broken because some people may search for each known key value combination. Since each algorithm uses a fixed key length or ASCII character, the computer program can attempt to combine each possible key combination and finally find the correct combination. These types of algorithms are generally used to store and retrieve the connection string of the database.

Asymmetric algorithm (or public key algorithm) has no symmetrical algorithm, but its code is difficult. These algorithms depends on two keys, one is a private key, and the other is a public key. The public key is used to encrypt the message, the private key is the unique key that can decrypt the message. The public key and private key are linked together by mathematical methods, so the encryption exchange must be successfully exchanged, and these two keys must be obtained. Since the computer performance may affect computer performance, the asymmetric algorithm is not suitable for encrypting a large amount of data. Common usage of asymmetric algorithms is to encrypt and transmit symmetric keys and initialization vectors. The symmetric algorithm is then encrypted and decrypted in the message sent back and forth between the two parties.

If you don't plan to restore the original value, especially if you don't want others to discover the original value, then use the hash value. Hats can encrypt the string of any length to a fixed byte set. This operation is unidirectional, and therefore usually used for a small amount of data such as a password. When the user enters the user password on a secure input screen, the program will encrypt this password and store the hash value into the database. Even if the database leaks, no one can read the password because the password has been encrypted. When the user logs in to the system, the same algorithm is used to decrypt the user typed, if the two hash values ​​match, the system can determine the value of the user input to the previously stored value.

Encryption exercise

The sample application includes a form that allows you to encrypt using the DES and TrIpledes Encryption Service Provider. The form name is frMencrypt, as shown in Figure 3.

Figure 3: The encryption algorithm allows you to encrypt and decrypt values.

On this screen, first you need to click the Gen Key button, then click the Gen IV button. Then enter some data in the Original String text box and click the Encrypt (Encryption) button. After clicking the Encrypt (Encrypted) button, the encrypted text will appear in the Encrypted String text box. If you want to use this encrypted string in your own application, you need to record the generated key and iv because you want to decrypt the string to use it again, you need to provide these two values. If the key and IV is lost, the connection string will never be recovered.

Now look at its source code to learn how to implement encryption and decryption routines. Take a look at the member variables of this class, which is used to save the reference to the corresponding encryption service provider. The type of variable is Symmetricalgorithm. All symmetrical algorithms are inherited from this base class.

'Visual Basic .NET

Private MCSP as Symmetricalgorithm

// c #

Private symmetricalgorithm mcsp;

This MCSP variable will be assigned to a specific symmetric algorithm class based on the option button you selected on this form. The setENC () method will be responsible for creating an appropriate type and returning it to a different way.

'Visual Basic .NET

Private function setnc () as symmetricalgorithm

If Optdes.checked Then

Return New DescryptoServiceProvider

Else

IF OPTTRIPLEDES.CHECKED THEN

Return New TripleDescryptoServiceProvider

END IF

END IF

END FUNCTION

// c #

Private symmetricalgorithm setnc ()

{

IF (Optdes.Checked)

Return New DescryptoServiceProvider ();

Else

Return New TripleDescryptoServiceProvider ();

}

As you can see, based on the option buttons you selected on the form, you will create the DescryptoServiceProvider object or the TrIpleDescryptoServiceProvider object.

Realize the key to encryption and decryption

To use a symmetrical algorithm, you must provide the key to use. Each CryptosyMmetricalGorithm implementation provides a generateKey method. They actually use a random number generator class built in the public language runtime (CLR) class. Let's take a look at the Click event handler of the Gen Key button to see how it generates the random key value to use.

'Visual Basic .NET

Private sub btnkeygen_click (byval sender as _

System.Object, ByVal e as system.eventargs_

Handles btnkeygen.click

MCSP = setENC ()

Mcsp.GenerateKey ()

TXTKEY.TEXT = Convert.TOBASE64String (mcsp.key)

End Sub

// c #

Private void btnkeygen_click (Object Sender,

System.Eventargs E)

{

MCSP = setENC ();

Mcsp.GenerateKey ();

TXTKEY.TEXT = Convert.TOBASE64STRING (McSP.Key);

}

Once the specific implementation of the service provider, simply call the GenerateKey method to create a new random key for encryption. The size of the key depends on the specific provider used to encrypt. For example, the size of the DES key is 64 bits, and the size of the TripleDes key is 192 bits. There is a Keysize property on each SymmetricalGorithm class that will return the size of the key used to generate the key.

We also need to generate the initialization vector (IV). Iv will help algorithms generate data blocks of the final encrypted string. IV is used to start the encryption of the first block. If IV is not provided, only the general data passed between the string is as long as the key is the same. Therefore, IV is required as a "random" component of encrypted data. In this way, as long as the IV is used, even if the key is the same, the same data will be encrypted into a completely different value. Below is the source code for generating a new IV Gen IV (Generate IV) button. 'Visual Basic .NET

Private sub btnivgen_click (Byval E AS System.EventArgs) Handles Btnivgen.Click

Mcsp.Generateiv ()

TXTIV.TEXT = Convert.TOBASE64String (Mcsp.IV)

End Sub

// c #

Private void btnivgen_click (Object Sender,

System.Eventargs E)

{

Mcsp.Generateiv ();

TXTIV.TEXT = Convert.TOBASE64String (Mcsp.IV);

}

This code looks very similar to the code that generates a key. There is a generateiv () method on each encrypted service provider class. If IV is provided, the method will generate an IV.

Encrypt data

After getting the key and initialization vector, you can now use the key, iv, and original string values ​​to create an encrypted version of the original string value. Click the Encrypt (Encrypted) button to run the following code.

'Visual Basic .NET

Private sub btnencrypt_click

Byval sender as system.Object, _

Byval e as system.eventargs) Handles cmdencrypt.click

TXTENCRYPTED.TEXT = EncryptString (txtoriginal.text)

End Sub

// c #

Private void cmdencrypt_click (Object Sender, System.Eventargs E)

{

TXTENCRYPTED.TEXT = EncryptString (txtORIGINAL.TEXT);

}

The Click event process will call a method called EncryPTString () to accept values ​​in the Original String text box and encrypt it. Then return this value and put it in the Encrypted String text box. Below is the code of the EncryPTString () method.

'Visual Basic .NET

Private function encryptstring (byval value as string) _

As string

DIM CT As Icryptotransform

DIM MS AS MemoryStream

DIM CS As CryptostReam

DIM BYT () as Byte

CT = mcsp.createencryptor (mcsp.key, mcsp.iv)

Byt = encoding.utf8.getbytes (value)

MS = new memoryStream

CS = New Cryptostream (MS, CT, CRYPTOSTREAMMODE.WRITE)

cs.write (byt, 0, byt.length)

cs.flushfinalblock () cs.close ()

Return Convert.TOBASE64STRING (ms.toarray ())

END FUNCTION

// c #

Private string encryptstring (String Value)

{

Icryptotransform CT;

MemoryStream MS;

CryptostReam CS;

BYTE [] BYT;

Ct = mcsp.createencryptor (mcsp.key, mcsp.iv);

Byt = encoding.utf8.getbytes (value);

MS = new memoryStream ();

CS = New CryptostReam (MS, CT, Cryptostreammode.write);

cs.write (byt, 0, byt.length);

cs.flushfinalblock ();

Cs.close ();

Return Convert.TOBASE64STRING (Ms.Toarray ());

}

Now let's take a look at each line of code and understand the role of these codes. The first is several variables of the encryption process.

DIM CT As Icryptotransform

DIM MS AS MemoryStream

DIM CS As CryptostReam

DIM BYT () as Byte

Icryptotransform is an interface. This interface is required to call the CREATEENCRYPTOR method on any service provider, and the service provider will return the actual Encryptor object that defines the interface.

The original string is then required to convert the original string into byte arrays. Most .NET encryption algorithms are handled by byte arrays instead of strings.

Byt = encoding.utf8.getbytes (value)

It is now possible to perform actual encryption. This process needs to create a data stream to write encrypted bytes to it. To use the MemoryStream object called MS, the icryptotransform object (provided to the constructor of the CryptostReam class) and the enumeration constant you want to create this class under what mode (read, write, etc.). After creating a CryptostReam object CS, the write method of the CryptostReam object is now written to the memory data stream. This is the method of performing actual encryption, when each data block is encrypted, the data will be written to the MemoryStream object.

MS = new memoryStream

CS = New Cryptostream (MS, CT, CRYPTOSTREAMMODE.WRITE)

cs.write (byt, 0, byt.length)

cs.flushfinalblock ()

cs.close ()

After creating MemoryStream, the code will perform a FLUSHFinalBlock method on the CryptostReam object to ensure that all data is written to the MemoryStream object. This process will close the CryptostReam object.

Finally, the process converts the memory data stream from the byte array back to the string, so that the string can be displayed in the text box on the form. You can use the memorystream toarray () method to get the byte array from the data stream, then call the Convert.TOBASE64String () method, which accepts the byte array input and uses the base64 encoding method to encode the string as readable content.

Decrypt data

After encrypting data, it is sometimes necessary to decrypt data. The process of decryption data is very simple, similar to the encryption process. You need to provide the key and initialization vectors used during encryption. The Key and IV properties of the Symmetricalgorithm class are defined as an array of bytes. Therefore, you need to provide the string you created and convert it into an array of bytes before setting these properties. Let's take a look at the DecryptString method used to decrypt strings in the form. This method is called from the Click event handler of the Decrypt (Decrypt) button on the form. 'Visual Basic .NET

Private function decryptstring (byval value as string) _

As string

DIM CT As Icryptotransform

DIM MS AS MemoryStream

DIM CS As CryptostReam

DIM BYT () as Byte

CT = mcsp.createdecryptor (mcsp.key, mcsp.iv)

Byt = Convert.FromBase64String (Value)

MS = new memoryStream

CS = New Cryptostream (MS, CT, CRYPTOSTREAMMODE.WRITE)

cs.write (byt, 0, byt.length)

cs.flushfinalblock ()

cs.close ()

Return encoding.utf8.getstring (ms.toarray ())

END FUNCTION

// c #

Private string decryptstring (String Value)

{

Icryptotransform CT;

MemoryStream MS;

CryptostReam CS;

BYTE [] BYT;

CT = mcsp.createdecryptor (mcsp.key, mcsp.iv);

BYT = Convert.FromBase64String (Value);

MS = new memoryStream ();

CS = New CryptostReam (MS, CT, Cryptostreammode.write);

cs.write (byt, 0, byt.length);

cs.flushfinalblock ();

Cs.close ();

Return encoding.utf8.getstring (ms.toarray ());

}

The Encrypt function and the Decrypt function have only three differences.

You need to create the CREATEDECRYPTOR method for the CryptoserviceProvider class to create the appropriate ICTRYPTORANSFORM object. You need to convert the base64 encoded string into byte arrays. You need to use the Convert.FromBase64String method to implement this conversion. By converting the original byte array, the byte array is converted into a corresponding memory data stream. The memory data stream is needed to convert the normal string that can be displayed on the form on the form. This conversion is required to be used using an Encoding.utf8.getstring () method.

note:

Encoding.utf8 class from

System.Text Namespace.

Can you make it simpler? !

Although it is not difficult to show the code that is displayed so far, there are many different classes and interfaces, you may not be used to use. In addition, I have to remember a lot of code. Below we learn how to make Cryptography classes to be used.

There are two classes called PDSacryptography, which are pdsahash and pdsaencryption, respectively. These two classes are used to encapsulate the actual mechanism for creating a column string or encrypted string. In addition, they also allow you to use enumerations to determine which hash or encryption algorithm to use. You don't have to remember all the different names of each different encryption service provider, you can get a good IntelliSense® provider list. Use pdsahash packaging hash

The PDSahash class contains attributes HashType, HashObject, OriginalString, HashString, SaltValue, Usesalt, and Saltlength. The method associated with this class includes STencryptor, CreateSalt, Reset, and Createhash. This class creates an enumeration called PDSahashType, which you can select the corresponding hash class you want to use. The role of this class is to simplify the code shown above into the following code.

Private sub usesdsahash ()

DIM Ph as new pdsahash (pdsahash.pdsahashtype.md5)

Messagebox.show (ph.createhash ("paul"))

End Sub

I would rather typing the above code and don't want to remember all the code displayed above. As you can see, this code is quite simple, identical to the code described above, just being packaged into an easy-to-use interface. You can find a complete class from the examples included in this article. The following listings can be listed below.

Public enum pdsahashtype as byte

MD5

SHA1

SHA256

SHA384

SHA512

END ENUM

Each algorithm is provided with a different security level for the final hashing. The full hash list list in .NET is as follows:

MD5CryptoServiceProvider Sha1cryptoserviceProvider Sha256Managed Sha384Managed Sha512Managed

For more information on these different hash types, see the Visual Studio .NET online documentation.

Use pdsaencryption packaging encryption

Just like the PDSahash class can be packaged in all the hash features in the .NET Framework, the PDSAEncryption class can be used to pack various symmetrical algorithms in the .NET Framework. The PDSAEncryption class includes the following enumeration type, allowing you to create a variety of encryption / decryption objects.

Public Enum PDSAENCRYPTIONTYPE AS BYTE

DES

RC2

Rijndael

Tripledes

END ENUM

Similarly, each service provider provides different security levels for encryption strings. This has a detailed introduction in the Visual Studio .NET online documentation, and details are not described here.

This class contains properties EncryptionType, OriginalString, EncryptedString, Key, Keystring, IV, IVSTRING, and Cryptoprovider. Most of these attributes are not self-definitive, but Key and IV are byte arrays, and keyString and IVString are string representations of these byte arrays.

This class also contains some methods. For example, Encrypt and Decrypt. There is also GenerateKey and GenerateIV methods. If there is no ready-made key and IV, you can use these two ways to create a key and IV. There is also a setEncryptor method that is used to create a new CryptoproVider object that will be used in various methods.

The role of this class is to make the encryption and decrypted strings easier. For example, the following code snippet shows how easy it is to use this class encrypted string.

Private sub btnhardcoded_click (_Byval Sender as system.object, _

Byval e as system.eventargs) Handles btnhardcoded.click

DIM PS AS New Pdsasymmetric (_

Pdsasymmetric.pdsaencryptionType.tripledes)

Messagebox.show (ps.encrypt (_

"Server = localhost; database = northwind; uid = sa; pwd = sa"))))

End Sub

summary

Classes in Microsoft .NET Framework can easily save confidential information in your computer. You will find that multiple classes in the Cryptography namespace can complete this task. Creating packaging for these classes can help you greatly reduce the amount of code you need to write. It is highly recommended that you create a similar package according to this article.

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

New Post(0)