.NET

Announce Upload video
Free open source development platform
open 2 entries with the same name
Collection
zero Useful+1
zero
. NET is a free open source development platform for building a variety of applications C# F# or Visual Basic to write. NET application. [10] . NET is used to generate multiple types of application program And library to develop web applications Web API And microservices, serverless functions in the cloud, cloud native applications Mobile applications , desktop applications, Windows WPF , Windows Forms, Universal Windows Platform( UWP ), games Internet of Things ( IoT )、 machine learning Console Application Windows Services 。. NET Class library Share functions in different applications and application types. No matter which type of application is built, the code and project files look the same. You can access the same runtime API And language functions. [1]
Software name
.NET
software platform
Windows Linux macOS Docker etc. [2]
Online time
November 2000
Last updated
February 9, 2021
Software language
C #, F #, VB, etc
Developers
Microsoft [2]
Software Licensing
MIT and Apache 2 licenses [3]
Software version
5.0.6 [4]
3.1.15(LTS)
2.1.28(LTS)
Software size
5.6 to 6.8 MB

Background

Announce
edit
. NET is Open Source (Hosted in GitHub ), using MIT and Apache 2 licenses NET is NET Foundation NET is Microsoft Used to implement XML ,Web Services, SOA (Service oriented Architecture Service oriented architecture) and agility. Technicians want to really understand what is NET, You must understand first NET technology and the problems it wants to solve must first understand why they need XML, Web Services and SOA. Technicians generally Microsoft As a platform manufacturer. Microsoft build Technical platform And technicians create application systems on this technology platform. From this point of view NET can also be defined as follows: NET is Microsoft The new generation of Technical platform , and build interconnected application systems for agile commerce. These systems are standard based, connected, adaptable, stable, and high-performance. From a technical point of view, one NET application is an application running on NET Framework application program (To be more precise, a. NET application is written using the. NET Framework class library and run on Common Language Runtime Common Language Runtime application program 。) If a application program Follow NET Framework is irrelevant, it cannot be called NET program. For example, just using XML is not NET application. It is not just to use the SOAP SDK to call a Web service NET application.
April 2014 At the Build Developer Conference, Microsoft Announce a batch of open source NET library and related technologies, established NET Foundation to manage and guide the development of open source components. Microsoft will also open source under the Apache 2.0 license Roslyn Compiler stack, Roslyn It is Microsoft's so-called compiler as a service, including C# And Visual Basic NET compiler NET Foundation is composed of GitHub and Xamarin The Xamarin consists of GNOME Founder Miguel de Icaza et al NET open source implementation. Xamarin Contributed part of its library to the Foundation. In an interview, de Icaza said that Microsoft has changed, not only removing the restrictions in the license, but also working with Xamarin to solicit design feedback and publish documents under the Creative Commons License.
On November 13, 2014, in order to further expand the cloud computing market, Microsoft Will not put NET, Visual Studio and other key software technologies are limited to the Windows platform, and will be compatible with Linux, Mac OS X, iOS and Android in the future. In addition, Microsoft also announced that it will open NET core server running environment and the source code of the framework, so that external developers can also contribute to this software development platform. [3]
As part of this change, Microsoft will allow developers to use it NET running environment and framework to develop server based and cloud based applications for Linux and Mac. Microsoft also launched a new version of Visual Studio 2013 with full functions, which will be free for independent developers, students, small businesses and other users. [3]

Operating environment

Announce
edit
. NET 5 and .NET CORE All support Windows, Linux, and macOS systems. [5]
As shown in the figure Version History and the Version Installed by Windows, it summarizes the version history and identifies the version installed by Windows.
Version history and the version installed by Windows
Each new version of NET Framework will retain the features in previous versions and add new features. The CLR is determined by its own version number. Some versions of NET Framework contains a new version of CLR, while other versions of NET Framework uses an earlier version of the CLR. For example NET Framework 4 includes CLR 4, while NET Framework 3.5 includes CLR 2.0. (There is no version 3 CLR.) Although NET Framework 4.5 is NET Framework 4. The basic CLR version number becomes CLR 4.5.
Normally, you should not uninstall the installation on your computer NET Framework, because the application you use may depend on a specific version and may be broken if you remove that version. You can load on one computer at the same time NET Framework. This means that it can be installed NET Framework, There is no need to uninstall the old version.

Application component

Announce
edit

Client application

Composition. net Software Technology component, one of the components, "smart" client Application software and operating system , including PC, PA, mobile phone or other mobile devices. Through the Internet and Web Services technology, users can get the information and services they need at any time and anywhere. For example, you can read news, order air tickets, browse online photo albums, etc. on your mobile phone. CRM system , applied NET solution, all business personnel can directly access customer information through mobile phones or PDAs [6]

WebServices

Web service is Intelligent terminal Software The foundation of, Microsoft It provides a complete set of rich solutions for users to create intelligent terminals, including:
.NET Framework -Intelligent terminal realizes cross platform (device independence)
Visual Studio. NET – Build and integrate web services and application program Rapid development tools for
Microsoft Windows Server 2003 – Next generation enterprise server for building and publishing solutions
Microsoft Office Professional Edition 2003 – The built-in toolset can also help develop intelligent terminals
.net
Web service is NET core technology. Just as the Web is the way for a new generation of users to interact with applications, XML is the new generation program The way of communication is the same. Web Services is a common data transmission format between new generation computers, which can make it easier for different computing systems to exchange data. Web services have the following features: Web services allow data sharing between applications; Web services are scattered code Unit; Based on XML, a common language for data exchange on the Internet, it realizes cross platform and cross platform operating system , cross language. that Microsoft What is the difference between ASP and Web services? ASP is still the product of a centralized computing model, but it is dressed in a layer of Internet. But Web Services is a totally different spirit“ Software It is the true saying of "service", and it conforms to the trend of distributed computing mode. And its existing form is similar to that of the past Software Different. This component mode is compact and single, and the development cost is low for developers.
It is pointed out here that Web services are not Microsoft The invention is also not exclusive to Microsoft. Web services is an open standard, just like HTTP, XML and SOAP. They are an industry standard, not Microsoft Standards. WS-I is an alliance organization to promote Web Services interoperability. It was originally initiated by IBM and Microsoft. Other members include BEA System, HP Computer, Oracle Intel (Intel) and Sun Microsystem. Most of the Web services that exist on the network today are not actually used NET architecture, Web services have interoperability properties, you can also use Windows development client To call the methods of Web services running on Linux.

interface specification

microsoft .net
The interface specification mentioned earlier is in NET, the Web service interface usually uses the Web Services Description Language( WSDL )Description. WSDL uses XML to define such interface operation standards and input/output parameters, which looks much like the Interface Definition Languages (IDLS) of COM and CORBA. After the interface is defined, some protocols must be used to call the interface, such as SOAP protocol, SOAP It originates from a protocol called XML RPC (XML remote procedure calling), while Java uses XML-RPC Developed their own JAX-RPC The protocol is used to call Web services. UDDI is used to publish and access the interface of Web services. Here we only need to know that WSDL uses XML to define the Web services interface, access Web services through SOAP, and find Web services on the Internet to use UDDI. Server architecture - Microsoft Windows Server System Microsoft provides the best server architecture - Microsoft Windows Server System - to facilitate publishing, configuration, management, and orchestration of Web services. To meet the needs of distributed computing Microsoft A series of Server system These systems with built-in security technology all support XML, which speeds up the system application program And integration between partner applications that also use Web Services.
Microsoft Windows Server System includes:
Microsoft Application Center 2000 - Configuring and Managing the Web application program
Microsoft BizTalk Server 2002 - Build XML based cross application and organizational Business logic
visual studio .net
Microsoft Commerce Server 2002 – a solution that can quickly establish large-scale e-commerce
Microsoft Content Management Server 2002 - Management Dynamics E-commerce website Contents of
Microsoft Exchange Server 2000 – for anytime, anywhere communication collaboration
Microsoft Host Integration Server 2000 – for and Host system Transfer data between
Microsoft Internet Security and Acceleration Server 2000 (ISA Server) – internet connection
Microsoft Mobile Information Server 2002 – for supporting handheld devices
Microsoft Operations Manager 2000 – describes the operational management of enterprise class solutions
Microsoft Project Server 2002 - Best Practices for Project Management
Microsoft SharePoint Portal Server 2001 – Query, share, publish business information
Microsoft SQL Server 2000 - Enterprise Database
Microsoft Visual Studio. NET and Microsoft .NET Framework For setup, publish and run the Web Services solution.
Microsoft Official Tutorial. [7]

CLR and CIL

NET Framework Environment
The primary components of. NET are CIL and CLR. CIL is a set of operating environment descriptions, including General system , basic class library and machine independent Intermediate code , full name is Common intermediate language (CIL)。 CLR is the platform for confirming that the operation password conforms to CIL. Before CIL execution, the CLR must instructions Compile and convert into original mechanical code in time.
All CILs( Common intermediate language )All available NET self expression. The CLR checks the metadata to ensure that the correct method is called. Metadata is usually defined by the language compiler But developers can also create their own metadata by using customer attributes.
If a language implementation generates CIL, it can also be called by using CLR, so that it can work with any other NET language. CLR is also designed to be operating system independent.
When an assembly is loaded, the CLR performs various tests. Two of these tests are verification and validation. When confirming, the CLR checks whether the assembly contains valid metadata and CIL, and checks the correctness of the internal table. Verification is less precise. Inspection of verification mechanism code Whether some "unsafe" operations will be performed. The algorithm used for verification is very conservative, resulting in some "safe" code It will not pass the verification. Unsafe code The assembly will only be executed if it has a "skip verification" license, which usually means that the code is installed on the local machine.
Passed NET, You can use SOAP to interact with different Web services.

Version 3.0

Announce
edit
.NET Framework 3.0 (Former name WinFX )Yes Microsoft Specially designed for the operating system Windows Vista (formerly "Longhorn") API 。. NET Framework . NET Schema and Win32 API Extension of. Although the Win32 API still exists in Windows Vista, it cannot be called directly in WinFX. In addition, WinFX will be provided to . NET Programmer It is easier to call functions in Windows
. NET Framework 3.0 can also be used in Windows XP and Windows Server 2003 This increases the ability to run NET Framework 3.0 program. Backward compatibility makes it easier to introduce these technologies to developers and end users. On September 1, 2006, Microsoft released NET Framework 3.0, developers can experience these new technologies without installing Vista.
There is no new version of. NET Framework 3.0 CLR , but in NET Framework 2.0, so no programming language has new syntax features NET Framework 3.0, Must be installed first NET Framework 2.0 and. NET Framework 3.0 can be fully backward compatible NET Framework 2.0。
. NET Framework 3.0 mainly consists of four parts:
  • WPF (Windows Presentation Foundation), the internal code "Avalon", is based on XAML (eXtensible Application Markup Language)、. NET and vector graphics technology API , which makes full use of the 3D graphics card hardware functions and Direct3D Technology.
  • WCF (Windows Communication Foundation), internal code "Indigo", is a service-oriented communication framework, which can be used to realize the interaction between local and remote programs.
  • WF (Workflow Foundation) was published in August 2005. The workflow engine provided by Microsoft can realize task automation and transaction integration.
  • InfoCard It is the code of a software component, which is used to safely save and use the user's digital identity, and provides a unified interface to select identity for specific transactions, such as logging on a website.

Dynamic programming

Announce
edit
C # is static Strongly typed language In many cases, it is common to provide "dynamic" behavior, such as access at runtime through reflection NET type, call Dynamic language Object, access COM object, etc., cannot be obtained by static type. Therefore, C # 4.0 introduces a new keyword dynamic, which also improves the interaction between static types and dynamic objects. This is Dynamic Lookup. For example:
public static void Main() { dynamic d = GetDynamicObject(); d.MyMethod(22); // Method call d. A=d.B;//Attribute assignment d[“one”] = d[“two”]; // Indexer assignment Int i=d+100;//Operator call string s = d(1,2); // Delegate call }
Just like an object can represent any type, dynamic enables type determination at runtime, and method calls, property access, and delegate calls can be dynamically dispatched. At the same time, the dynamic feature is also reflected in the construction of a dynamic object. The type of IDynamicObject interface is implemented in C # 4.0, which can fully define the meaning of dynamic operation# compiler As a runtime component to complete operations deferred by the static compiler, for example:
dynamic d = new Foo(); string s; d.MyMethod(s,3,null);
In the specific execution process, C #'s runtime binder obtains the actual type Foo of d through reflection based on runtime information, and then performs method lookup and heavy load Parse and execute the call, which is the secret behind dynamic calls: DLR. At NET 4.0 will introduce the important underlying component DLR (Dynamic Language Runtime, Dynamic language Runtime). In addition to the basic support for dynamic lookup, DLR also serves as an infrastructure to provide a unified interoperability mechanism for dynamic languages such as IronRuby and IronPython. In a word, dynamic programming will bring great changes to C # in the following fields:
·Office programming interacts with other COM.
· Dynamic language Yes, it will not be difficult to consume IronRuby dynamic language types in C #, and experience dynamic language features is just around the corner.
·Enhanced reflection support.
Taking calling IronPython as an example, we just need to introduce IronPython. dll, IronPython.Modules.dll,and Microsoft.Scripting.dll, You can create a ScriptRuntime to host the IronPython environment in C # to operate Dynamic language Type information of.
ScriptRuntime py = Python.CreateRuntime();
dynamic mypy = py.UseFile("myfile .py");
Console.WriteLine(mypy. MyMethod("Hello"));
Although from Microsoft In the technical materials and CTP presentations currently provided, there are still more or less problems with dynamic search, but in today's "dynamic" popular, we cannot avoid and must embrace this future protagonist, because I firmly believe that tomorrow will be better.

Parallel computing

The emergence of parallel computing is the inevitable result of the development of computer science computer hardware The rapid development of Multi-core processor The traditional programming mode must be compatible with the new hardware environment in order to make the computer performance achieve a reasonable application effect. In the words of Master Anders, parallel computing will become the mainstream in the next five to ten years programing language The direction that cannot be ignored, and 4.0 is the first shot for C # to realize concurrency.
Future NET Framework 4.0 will integrate TPL (Task Parallel Library) and PLINQ (Parallel LINQ), which also means that in the future we can apply C # 4.0 to achieve parallel applications and unified work scheduling program The parallel coordination of hardware will be greatly improved application program While reducing the complexity of existing concurrency models.
Then, we should take a look at the cool feeling of using C # weapons to develop concurrent environments The Threading. Parallel static class provides three important methods: For, Foreach, Invoke, which can give us a try:
//Apply TPL to execute parallel loop tasks Parallel.For(0,10,i =>{DoSomething(i);});
In the case of thread contention execution, the same operation is run on the dual core platform, and the accurate time test is conducted with StopWatch. The execution time in the parallel environment is 2001ms, while that in the non parallel environment is 4500ms. The charm of parallel computing really deserves its name. We continue to apply PLINQ to query and sort parallel operations. Currently, PLINQ supports two methods: ParallelEnumerable class and ParallelQuery class, such as:
int[] data = new int[] { 0,1,2,3,4,5,6,7,8,9 }; int[] selected = (from x in data.AsParallel()select x + 1). ToArray();
More detailed comparison examples will be discussed by readers in practice. Parallel computing is managed code In multi-core environment performance optimization It provides a unified solution, and we will do better in the future.
Note: In fact, we can choose to download and install Microsoft Parallel Extensions to the NET Framework 3.5June 2008 CTP package NET 3.5 environment Parallel computing The endless charm of.

Covariance and contravariance

Covariance and contravariance are born to solve problems. To figure out what kind of problems to solve, we need to first clarify a few simple concepts. First, let's do something:
Derived d = new Derived();
Base b = d;
The Derived type inherits from the Base type. The Derived reference can be safely converted to the Base reference, and this conversion capability can be seamlessly implemented in Derived arrays and Base arrays, such as:
Derived[] ds = new Derived[5];
Base[] bs = ds;
The variability in the same direction of the original transformation (from subclass to parent) is called covariant; Its reverse operation is called contravariant. When the same situation applies to generic paradigm For example:
List ds = new List();
List bs = ds;
Similar operations are not feasible. Therefore, this becomes a perfect problem in C # 4.0—— generic paradigm Covariance and contravariance of:
List bs = new List(); List ds = new List();
bs = ds; //List; Support for T covariant
ds = bs; //List; Support T inversion
In C # 4.0, with the addition of covariant and contravariant features, C # introduces two in and out keywords to solve the problem.
public interface ICovariant {
T MyAction();
}
public interface IContravariant
{
void MyAction(T arg);
}
Where, out represents a type parameter that can only be used as a return value, and in represents a type parameter that can only be used as a parameter. However, an interface can have both out and in, so it can support both covariant, contravariant, and simultaneous support, for example:
public interface IBoth
{
}

Default Parameters

Named parameters and optional parameters are two relatively simple features programing language The optional parameters are not new to developers who provide default values for parameters
public void MyMethod(int x,int y = 10,int z = 100) {
}
Therefore, we can call the MyMethod method by calling MyMethod (1) and MyMethod (1,2). Named parameters solve the problem of passing Real parameter Avoid omitting Default Parameters Resulting heavy load For example, when the second parameter y is omitted, it can be passed by declaring the parameter name:
MyMethod(20,z: 200);
It is equivalent to calling MyMethod (20,10200), which is very similar to the calling method of Attribute. Although it is only a small skill, it has also been improved Method overload The flexibility and adaptability of C # reflect the increasingly perfect development track of C # language.
Of course, beyond that NET 4.0 has also added many desirable platform features, which will also bring unprecedented new experience to C # coding.
The above copyright belongs to the author.

. NET Controls

. NET Standards Controls are divided into two categories according to their application environment:
Windows Form Control: mainly used for the development of Windows applications. All Windows controls are derived from the Control class, which includes Windows Form Component, which also includes the Form class. The Control class includes many attributes, events and methods shared by all controls. It contains check boxes, text boxes, buttons, labels, image lists, and so on.
Web Form Control: mainly used for the development of Web applications. It is specifically targeted at Asp NET Web Forms. Web form controls are contained in the namespace System In Web.UI.WebControls, when a user uses Visual Studio to create a Web form page, a Using statement referencing the namespace will be automatically added to the background code file. [8]
. NET Compact Framework provides Windows Form Control. To use functions that these controls do not have, you can derive your own custom controls from public controls. You can create a custom control by defining a public type that inherits from a Control class or from an existing UserControl in an assembly.
The simplest control customization is to override the methods of common controls. For example, you can override the OnKeyPress inheritance method of the TextBox control to provide code that restricts input to numeric characters.
If you feel Custom Controls It is too time-consuming and complex, and can also be downloaded from trusted sources control , and import by adding references Custom Controls Support these customized NET controls include: ComponentOne Studio ,Spread, ActiveReports MultiRow [9] Etc.

Encryption processing

Announce
edit
Information security is one of the most important problems in computer application NET encryption function examples are few and far between. In view of this, this paper discusses the existing problems in NET platform, and provides a tool to encrypt/decrypt files.
Web Services The rapid development with an unquestionable trend has prompted many units to consider NET. However, out of concern about security issues, some organizations always have concerns about adopting new technologies. Fortunately, there are many mature security and network technologies, such as virtual private network (VPN) and firewall It can greatly improve the security and performance of Web service applications and give developers the freedom to choose security technologies instead of having to use XML security technologies that are still developing.
Although security is the primary issue of information systems, but related NET security and encryption tools are few examples. Look at most NET books, we can't find any questions about security, let alone about Cryptosystem The discussion of.
In view of this, this article will introduce how to use in VB development NET encryption and secret key Generate class, which provides a tool Cryptography that can be used to encrypt and decrypt files. With this tool, you can save various Confidential , such as all password/user name information, revenue and expenditure files, and other information that you want to keep confidential. You can also encrypt files sent over the Internet. Encryption technology has a wide range of uses. You can further customize the tools provided in this article to meet some special needs, such as adding Batch processing Ability, etc.

Security threats

Attacks and leaks are two major security threats faced by computers. The attack may come from a virus, such as deleting files, slowing down the machine, or causing other security problems. In contrast, the leakage of secrets is often much more concealed, which infringes your privacy: unauthorized access to hard disk files, interception of emails sent through the Internet, and so on. Disclosure may also be accompanied by attacks, such as modification Confidential Etc.
The best precaution against leakage is encryption. Effective encryption not only eliminates the leakage of secrets, but also prevents attacks caused by leakage of secrets. Encryption technology is sometimes used to Authentication ——If a user knows the password, he should be the person with this identity.
However, it must be noted that no security technology to prevent leakage is absolutely solid, because the password may be obtained by unauthorized people.

Encryption premise

First, you need to use NET security function, you must use the Imports statement to introduce the package for encryption. Test any of the code Before, please add the following Imports statement at the top of the VB code window:
Imports System
Imports System.Text
Imports System.Security.Cryptography
Second, the US government used to restrict the export of certain encryption technologies. Although these restrictions are no longer valid NET framework has disabled the "advanced" encryption technology in the export version of Windows. If your Windows does not have advanced encryption capabilities, you can Microsoft Download the update package from the website: For Windows 2000, install the High Encryption Pack included in Service Pack 2; For NT, install Service Pack 6a. For Windows ME, 95, 98 users, IE 5.5 also includes the High Encryption Pack.

Tool Overview

The tools provided in this article can be used to encrypt and decrypt files File encryption , just start the tool provided later in this article.
This tool provides a Text Box And a text box for key input, providing encryption, decryption and key generation functions through a convenient user interface. Upper Text Box Used to enter the name of the file to be encrypted/decrypted; The text box below is used to enter an 8-character password. After the encryption operation, a new file will be generated. The encrypted file and the original file are in the same directory, and the file name is the same as the original file, but with the suffix "xx" added. For example, if the original file is MyFile.txt, the encrypted file is MyFilexx.txt.
After encryption, the original file may not have to be deleted, but it is generally best to delete it, because the basic purpose of encryption is to hide the data of the original file. If you want to recover the original file from the encrypted file Text Box Enter MyFilexx.txt, and then provide the password. The Cryptography tool will create a MyFile.txt file that is the same as the original file. That is to say, Cryptography regards the "xx" after the file name as a sign to require decryption of ciphertext.
Note: If you forget the password used to encrypt the file after encrypting it, it is impossible to recover the original file. Of course, this is related to the complexity of the password itself. To ensure the security of documents, it is better to use more complex passwords, such as mixed use of letters, numbers and special characters (such as the "$" symbol).
. NET provided Encryption technology There are more than one, but this article mainly discusses Symmetric encryption Symmetric encryption Also called private Key encryption It is characterized by that encryption and decryption use the same key (actually the same algorithm), and both the decrypting party and the encrypting party are responsible for ensuring the security of the password (for public key and asymmetric encryption, there are two keys, one of which is public, which is currently recognized as the most effective Encryption technology , but in terms of speed Symmetric encryption algorithm A lot slower).
In official use NET encryption class, you must first generate a key from the password provided by the user. The key can be generated by using the Hash function, which converts the user's password string into a set of meaningless data similar to a random number sequence, which can be used as a key raw data Perform unique deformation processing.
For example, one way to encrypt data with a key is to raw data ASCII code of key plus ASCII code of key:
Key: ab=ASCII: 97,98
Data: berry=ASCII: 109101114114121
Add the ASCII code of this group of data to the ASCII code of the key (reuse the key if necessary), and the encryption result is:
97 98 97 98 97
+109 +101 +114 +114 +121
206 199 211 212218
For the same data, Hash algorithm The same result is always generated (that is, the same Hash algorithm always generates the same bit sequence for the same password). In fact, in the code Medium, use NET's SHA1CryptoServiceProvider class ComputeHash method can verify this. For example, for the same input parameter morph, the method always returns the following results at any time: 124230, 93253197206136, 72. Therefore, if someone knows the password and the algorithm for generating the key, he can also easily calculate the key.

Encryption/decryption

.NET Encryption technology The key must have a certain length. For example, the DES (Data Encryption Standard) function requires the key to be 64 bits long, while Rijndael requires 128, 192, or 256 bits long keys. The longer the key, the higher the encryption strength. For non DES encryption algorithm Query the LegalKeySizes attribute to get its allowed key length, including MinSize (the minimum key length supported), MaxSize (the maximum key length), and SkipSize (the increment). SkipSize indicates the interval between the maximum length and the minimum length of the key. For example, the SkipSize value of Rijndael algorithm is 64 bits.
Use the following code You can get the length information of the key:
'Create DES encryption object
Dim des As New DESCryptoServiceProvider()
Dim fd() As KeySizes
fd = des.LegalKeySizes() 'tells us the size(s),in bits
MsgBox ("Encryption Type="&des ToString() & Chr(13) & "minsize = " & fd(0). MinSize & Chr(13) & _
"maxsize = " & fd(0). MaxSize & Chr(13) & "skipsize = " & fd(0). SkipSize)
Run the above code , the result is 64, 64, 0. If you change the declaration of the encrypted object to TripleDESCryptoServiceProvider(), the results are 128, 192, 64.
Note: The DES algorithm requires an 8-byte password to be entered, but the actual key used is only 56 bits (7 bytes), and the last bit of each byte is not used (it is used as a check bit, but not for the actual encryption process).
Below code Start generating this article example program Key for:
Public Class Form1
Inherits System.Windows.Forms.Form
'8-byte array to store the key
Private TheKey(7) As Byte
'Put some random data into the vector
Private Vector() As Byte = {&H12,&H44,&H16,&HEE,&H88,&H15,&HDD,&H41}
first, code Two keys are defined to save the key and initial vector (see details later) variable The initial value of the vector is filled with random data here. Of course, the initial value of the vector can also be obtained through the password and Hash algorithm. The following procedure creates a key from the password entered by the user:
Sub CreateKey(ByVal strKey As String)
'Save the key's Byte array
Dim arrByte(7) As Byte
Dim AscEncod As New ASCIIEncoding()
Dim i As Integer = 0
AscEncod.GetBytes(strKey, i,strKey.Length,arrByte,i)
'Get the Hash value of the password
Dim hashSha As New SHA1CryptoServiceProvider()
Dim arrHash() As Byte = hashSha. ComputeHash(arrByte)
'Save the hash value to the key
For i = 0 To 7
TheKey(i) = arrHash(i)
Next i
End Sub
The user's password (strKey) is passed into the CreateKey process, which is decomposed into a set of ASCII values and saved in a byte array. Put this Byte array The ComputeHash method passed to the SHA1CryptoServiceProvider class returns a Hash value. Save the hash value to the TheKey array for future encryption/decryption processes (note that SHA1CryptoServiceProvider can actually support 160 bits, but this example program Only 64 bits).
So, what exactly does the initial vector do? this Byte array There are 8 elements, just like keys, but the functions of vectors and keys are different. Vectors are used to avoid a unique problem of algorithms such as DES. In algorithms such as DES, raw data It is divided into 8 bytes and processed separately. When DES encrypts a piece of data, it uses the mode of the previous piece of data, that is, if the raw data The content of all subsequent blocks will change with a character in the first block in the, thus avoiding the problem of duplicate blocks in a series of connected blocks.
For example, suppose you are happy and send an email with only a few repeated words "Melanie! Melanie! Melanie! Melanie!”, Under the joint action of the key and the previous block in the block sequence, the encrypted ciphertext will not repeat. However, further consideration of this encryption process shows that if multiple messages are encrypted with the same key, and the greetings at the beginning of the message are the same, part of the beginning of the message is vulnerable to attack. For this reason, we use the initial vector to simulate the previous block.
The following paragraph in the encryption/decryption tool of this article code Demonstrated how to encrypt files:
Sub Encrypt(ByVal inName As String, ByVal outName As String )
Try
'Create buffer
Dim storage(4096) As Byte
'Number of bytes written
Dim totalBytesWritten As Long = 8
'Number of bytes written each time
Dim packageSize As Integer
'Declare file stream
Dim fin As New FileStream(inName, FileMode.Open,FileAccess.Read)
Dim fout As New FileStream(outName, FileMode.OpenOrCreate,FileAccess.Write)
fout.SetLength(0)
' source file Size of
Dim totalFileLength As Long = fin.Length
'Create encrypted object
Dim des As New DESCryptoServiceProvider()
Dim crStream As New CryptoStream(fout,_
des.CreateEncryptor(TheKey,Vector),_
CryptoStreamMode.Write)
'Output encrypted files
While totalBytesWritten < totalFileLength
packageSize = fin.Read(storage,0,4096)
crStream.Write(storage,0,packageSize)
totalBytesWritten = Convert.ToInt32(totalBytesWritten + _
packageSize / des.BlockSize * des.BlockSize)
End While
crStream.Close()
Catch e As Exception
MsgBox(e.Message)
End Try
End Sub
Pay attention to this paragraph code Three file streams are created: fin, which represents the original file in clear text; fout, Encryption result file; crStream, The encryption stream is used to transfer the DES encryption result to the output file, fout. The advantage of adding a crStream stream is that it is not necessary to save the results to Temporary files Or buffer.
The only important difference between the encryption process and the decryption process is that we will use CreateDecryptor, another method of the DESCryptoServiceProvider object, when performing decryption. In addition, the other processing steps (including parameters, file streams, etc.) of the two are basically the same.

Prevent cracking

Hackers and cryptographers have two main methods to crack encrypted files. The first is to search whether the ciphertext is repeated. The second is to obtain the key by brute force. First, let's consider how the initial vector can prevent repetition, and then discuss the key problem of preventing brute force cracking.
The first way to crack ciphertext is to search for samples - especially duplicate samples. People always start letters with the same words, such as "Dear XXX", "Dear Sir", etc. If multiple messages have the same starting words and are encrypted with the same key, then each encrypted message has the same beginning. Assuming that all the encrypted letters Antonio wrote to Melanie have the same greeting "@ 4 ^ F (2 $@ Fx", the decryptor will first check whether the first few words are "Dear Melanie" Confidential An important step of is to guess the number of words that should appear in the file, so we should not provide this convenience to the decryptor. In the example in this article, the content of the initial vector is appended to the beginning of the file, thus preventing duplication. Only the beginning of a letter is vulnerable to such attacks.
Computer Operation speed And the precision is far superior to that of people, especially good at handling some repetitive tasks, such as trying every possible key combination to finally crack the key. DES encryption algorithm It is inherently insecure, and this encryption algorithm has been made public since the 1970s. Moreover, if the cracker wants to process automation It can also be used conveniently NET DESCryptoServiceProvider class.
For a 128 bit encryption scheme with key/initial vector, how long does it take the computer to try every possible key combination? Experts have different opinions. Some people think it will take several months. Others think that a 6-digit computer equipped with special hardware can verify billions of keys every second, and it only takes a few hours to crack DES ciphertext. If your secret is worth taking months to crack, you'd better use TripleDES or other encryption algorithm As you can guess from the name of TripleDES, this encryption method uses triple encryption Data Encryption Standard The length of the key is 192 bits instead of 64 bits of DES key. Remember, other things being equal, the longer the key, the higher the security.
Conclusion: Now you have understood NET DES encryption algorithm The use process of can be studied next NET, including an attractive public key encryption scheme. Although the public key encryption scheme is slower to implement, the encryption effect is generally better than TripleDES.