You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+5-2Lines changed: 5 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,19 +1,22 @@
1
+
# Fucking algorithm
2
+
1
3
English translation is in progress... Some articles are still in Chinese, but most are completed. Please **star** this repo. The full translation will eventually be finished. Enjoy.
2
4
3
5
These articles go over different kinds of **Algorithmic Thinking**. All are based on LeetCode problems. They are **not only the solution code for the problem, but also WHY the solution works and HOW we can figure it out**.
4
6
5
7
I don't like one-liners. They can be confusing. I like clear, easily understandable code.
6
8
7
-
The **Gitbook** has been deployed and will sync with this branch of the repo: https://labuladong.gitbook.io/algo-en/
9
+
The **Gitbook** has been deployed and will sync with this branch of the repo: [https://labuladong.gitbook.io/algo-en/](https://labuladong.gitbook.io/algo-en/)
8
10
9
11
If you want to clone this repo, please use following command:
10
12
11
13
```shell
12
14
git clone --depth 1 --branch english https://github.com/labuladong/fucking-algorithm.git
13
15
```
16
+
14
17
This command specifies the `english` branch and will limit the depth of the clone and get rid of the Git commit history, which can be faster to clone.
15
18
16
-
# Table of Contents
19
+
##Table of Contents
17
20
18
21
* I. Dynamic Programming
19
22
*[Dynamic Programming in Details](dynamic_programming/AnalysisOfDynamicProgramming.md)
Copy file name to clipboardExpand all lines: common_knowledge/Cryptology.md
+21-19Lines changed: 21 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,3 +1,5 @@
1
+
# Cryptology
2
+
1
3
Speaking of cipher, the first thing that comes to our mind is the password to login, but from the point of cryptography, it is the unqualified cipher.
2
4
3
5
Why? Because the password of our account depends on crypticity, that is I keep the password in my mind and do not let you know,so you can not login in with my account.
@@ -11,9 +13,9 @@ if the receiver know the way to decrypt,the eavesdropper should also know.
11
13
12
14
In the following **we will introduce symmetric encryption algorithm、key exchange algorithm、asymmetrical encryption algorithm、digital signature、public-key certificate** to explain how we solve the problem of secure transmission.
13
15
14
-
###First、Symmetric Encryption
16
+
## First, Symmetric Encryption
15
17
16
-
symmetric ciphers,also called shared key cipher,as the name suggests,it uses the same key to encrypt and decrypt.
18
+
Symmetric ciphers,also called shared key cipher,as the name suggests,it uses the same key to encrypt and decrypt.
17
19
18
20
First of all,we know information consists of 0/1 bits sequence and the xor of two identical bits sequence is 0.
19
21
@@ -30,7 +32,7 @@ invulnerable algorithm is broken.
30
32
31
33
Therefore, the two most common algorithms to solve the key distribution problem are diffie-hellman key exchange algorithm and asymmetric encryption algorithm.
32
34
33
-
###Second、Key exchange algorithm
35
+
## Second、Key exchange algorithm
34
36
35
37
The secret key as we say is a big number, the algorithm use this number to encrypt and decrypt. The problem is that transition is insecure and the data can be eavesdropped.In other words, is there a way that it can let two people exchange the key in the front of others?
36
38
@@ -73,14 +75,14 @@ Above is the basic flow, as for picking which number, it is exquisite and I won'
73
75
Under the premise of the third party's eavesdropping, the algorithm can calculate a secret which can not be calculated by others as the key of symmetric encryption algorithm and start the communication of symmetric encryption.
74
76
75
77
About this algorithm, Hack come up with a crack way, not to eavesdrop Alice and Bob's communication, but to pretend to be Alice and Bob at the same time, that is man-in-middle attack.
76
-
78
+
77
79

78
80
79
81
In this way, both parties can't realize that they are sharing secrets with Hack. As a result, Hack can decrypt or even modify data.
80
82
81
83
**So, key exchange algorithm can not perfectly resolve the distribution of the key, the weakness lies in not being able to verify the identity of the receiver**.So, before using exchange key algorithm, we must verify the identity. For example, using the digital signature.
82
84
83
-
###Third、Asymmetrical encryption
85
+
## Third、Asymmetrical encryption
84
86
85
87
The thinking of the asymmetrical encryption is that don't sneak around with the transmission key. I separate the encryption key from the decryption key and use the public key to encrypt and the private to decrypt.Only send the public key to the receivers and they can send me encrypted data that I can use my private key to decrypt.About the eavesdropper,it is useless to get the data and the public key, because only the private key can be used to decrypt.
86
88
@@ -107,7 +109,7 @@ Digital signature takes the advantage of asymmetrical encryption,but reverses th
107
109
108
110
You may ask what is the purpose? The public key can decrypt the data,but I still encrypt the data and release.Isn't that a superfluous act?
109
111
110
-
Yes,but **the digital signature is not used to ensure the confidentiality of the data,but is used to verify your identity,** to prove that the data comes from you.
112
+
Yes,but **the digital signature is not used to ensure the confidentiality of the data,but is used to verify your identity,** to prove that the data comes from you.
111
113
112
114
You can image the data encrypted by you private key can only be decrypted by you public key,so if the encrypted data can be decrypted by you public key,can't it prove that the data comes from yourself?
113
115
@@ -120,35 +122,36 @@ Of course,the encrypted data is just a signature that should be released with th
120
122
3 Alice receives the data the the signature and needs to check does the data come from Bob.So he use the public key released by Bob to decrypt and compare the decrypted data with the received data.If they are the same,it proves that the data is origin and comes from Bob.
121
123
122
124
Why Alice can conclude? After all,the data and the signature,either can be exchanged.The reason is as follows:
123
-
1 If someone modify the data,Alice will know after he decrypt the data and find the difference.
124
125
125
-
2 If someone exchange the signature,Alice will get the wrong code after decryption and it is obviously different from the original data.
126
+
1. If someone modify the data,Alice will know after he decrypt the data and find the difference.
126
127
127
-
3 someone may tend to modify the data and regenerate the signature so that Alice can not find the difference;but he can not generate the signature because he do not have the private key of Bob.
128
+
2. If someone exchange the signature,Alice will get the wrong code after decryption and it is obviously different from the original data.
129
+
130
+
3. someone may tend to modify the data and regenerate the signature so that Alice can not find the difference;but he can not generate the signature because he do not have the private key of Bob.
128
131
129
132
In Summary,**digital signature can verify the origin of the data to some degree**.The reason is that it can be cracked by man-in-middle attack. Once it comes to the distribution of the public key, the receiver may receive the fake public key and make the wrong verification, Which can not be avoided.
130
133
131
134
Ridiculously, digital signature is a way verify the identity of others with the assumption that the identity of others is real.It seems like a dead cycle.**There must exist a trusted origin to verify the identity of others,Or no matter how many processes are used, they are just transferring problems, not really solving them.**
132
135
133
-
###Fifth、Public-key certificate
136
+
## Fifth, Public-key certificate
134
137
135
138
**The public-key certificate is the public key plus the signature,issued by a trusted third party certification authority**。Introducing the trusted third part is one of the feasible solution of dependency cycle.
136
139
137
140
The process of certificate is as follows:
138
141
139
-
1 Bob goes to the trusted certification authority to verify the identity of himself and provide his public key.
142
+
1. Bob goes to the trusted certification authority to verify the identity of himself and provide his public key.
140
143
141
-
2 Alice who wants to communicate with Bob, request the public key of Bob from the certification authority and then certification authority will give the certificate of Bob(it contains Bob's public key and the signature of his public key) to Alice.
144
+
2. Alice who wants to communicate with Bob, request the public key of Bob from the certification authority and then certification authority will give the certificate of Bob(it contains Bob's public key and the signature of his public key) to Alice.
142
145
143
-
3 Alice check the signature adn verify that the public key comes from the certificate authority and not tampered in halfway.
146
+
3. Alice check the signature adn verify that the public key comes from the certificate authority and not tampered in halfway.
144
147
145
-
4 Alice encrypts the data through this public key and starts to communicate with Bob.
148
+
4. Alice encrypts the data through this public key and starts to communicate with Bob.
PS: the above is for description.In real,certificate is only installed once instead of request from certificate authority every time and it is the server sends the certificate to client not the certificate authority.
152
+
> PS: the above is for description.In real,certificate is only installed once instead of request from certificate authority every time and it is the server sends the certificate to client not the certificate authority.
150
153
151
-
Some people may ask if Alice want to verify the validity of the certificate, he must have the public key of the authority.Isn't it the dead cycle mentioned just now?
154
+
Some people may ask if Alice want to verify the validity of the certificate, he must have the public key of the authority.Isn't it the dead cycle mentioned just now?
152
155
153
156
The regular browser we pre-installed contains trusted certificate to verity the identity of certificate authority,so the certificate is credible.
154
157
@@ -158,7 +161,7 @@ Except for the trusted public key of Bob, the communication of Alice and Bob is
158
161
159
162
Most of the regular websites nowadays apply HTTPS protocol, that adds a SSL/TLS secure layer between the HTTP protocol and the TCP protocol. After the TCP handshake, SSL protocol layer also handshake to exchange secure information including the certificate of the website, so that the browser can verify the website. After SSL layer finish the verification, the data in the HTTP protocol is encrypted to guarantee secure transmission.
160
163
161
-
###Sixth、Summary
164
+
## Sixth, Summary
162
165
163
166
Symmetric encryption algorithm use the same secret key to encrypt and decrypt, is hard to crack, encrypt quickly, but has the problem of secret key transmission.
164
167
@@ -174,4 +177,3 @@ The public-key certificate is the public key plus the signature,issued by a trus
174
177
The SSL/TLS secure layer in HTTPS protocol includes these encryption methods above.**So do not install irregular browser and certificate of unknown source**.
175
178
176
179
Cryptography is a little part of the security.Even though the HTTPS websites certified by a formal authority are not totally trusted,it only indicates the transition of the data is safe.Technology can not protect you.The most important thing is to improve personal safety awareness,pay more attention and handle sensitive data carefully.
Copy file name to clipboardExpand all lines: common_knowledge/SessionAndCookie.md
+30-33Lines changed: 30 additions & 33 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -6,7 +6,7 @@
6
6
7
7
Everyone should be familiar with cookies. For example after logging on the website, you will be asked to log in again. Or some guys play with python, but websites just block your crawlers. These are all related to cookies. If you understand the server backend's processing logic for cookies and sessions, you can explain these phenomena, and even drill some holes indefinitely, let me talk it slowly.
8
8
9
-
###1.Introduction to session and cookie
9
+
## 1.Introduction to session and cookie
10
10
11
11
The emergence of cookie because HTTP is a stateless protocol, In other words, the server can't remember you, and every time you refresh the web page, you have to re-enter your account password to log in. It's hard to accept. Cookie is like the server tagged you, and the server recognizes you every time you make a request to the server.
12
12
@@ -18,18 +18,18 @@ Cookie can be set on the sever through the “SetCookie” field of HTTP, such a
18
18
19
19
```go
20
20
funccookie(whttp.ResponseWriter, r *http.Request) {
21
-
//设置了两个 cookie
22
-
http.SetCookie(w, &http.Cookie{
23
-
Name: "name1",
24
-
Value: "value1",
25
-
})
26
-
27
-
http.SetCookie(w, &http.Cookie{
28
-
Name: "name2",
29
-
Value: "value2",
30
-
})
31
-
//将字符串写入网页
32
-
fmt.Fprintln(w, "页面内容")
21
+
//Set up two cookies
22
+
http.SetCookie(w, &http.Cookie{
23
+
Name: "name1",
24
+
Value: "value1",
25
+
})
26
+
27
+
http.SetCookie(w, &http.Cookie{
28
+
Name: "name2",
29
+
Value: "value2",
30
+
})
31
+
//Write string back
32
+
fmt.Fprintln(w, "content")
33
33
}
34
34
```
35
35
@@ -65,25 +65,24 @@ This type of plugin can read the browser's cookies on the current web page, open
65
65
66
66
The above is a brief introduction to cookies and sessions. Cookie is a part of the HTTP protocol and are not complicated. So let's take a look at the code architecture to implement session management in detail.
67
67
68
-
###2.Implementation of session
68
+
## 2.Implementation of session
69
69
70
70
The principle of session is not difficult, but it is very skillful to implement it. Generally, three components are required to complete it. They respectively are`Manager`,`Provider` and `Session` three classes (interface).
71
71
72
72

73
73
74
-
1.The browser requests the page resource of the path `/content` rom the server over the HTTP protocol, there is a Handler function on the corresponding path to receive the request, parses the cookie in the HTTP header, and gets the session ID stored in it,then send this ID to the `Manager`.
74
+
1.The browser requests the page resource of the path `/content` rom the server over the HTTP protocol, there is a Handler function on the corresponding path to receive the request, parses the cookie in the HTTP header, and gets the session ID stored in it,then send this ID to the `Manager`.
75
75
76
-
2.`Manager`acts as a session manager, mainly storing some configuration information, such as the lifetime of the session, the name of the cookie, and so on. All sessions are stored in a `Provider` inside the `Manager`.So `Manager` passes the `Sid` (session ID) to the `Provider` to find out which session that ID corresponds to.
76
+
2.`Manager`acts as a session manager, mainly storing some configuration information, such as the lifetime of the session, the name of the cookie, and so on. All sessions are stored in a `Provider` inside the `Manager`.So `Manager` passes the `Sid` (session ID) to the `Provider` to find out which session that ID corresponds to.
77
77
78
-
3.`Provider` is a container, most commonly a hash table that maps each `Sid` to its session. After receiving the `Sid` passed by the `Manager`, it finds the session structure corresponding to the `Sid`, which is the session structure, and returns it.
78
+
3.`Provider` is a container, most commonly a hash table that maps each `Sid` to its session. After receiving the `Sid` passed by the `Manager`, it finds the session structure corresponding to the `Sid`, which is the session structure, and returns it.
79
79
80
-
4.`Session` stores the user's specific information. The logic in the Handler function takes out this information, generates the user's HTML page, and returns it to the client.
80
+
4.`Session` stores the user's specific information. The logic in the Handler function takes out this information, generates the user's HTML page, and returns it to the client.
81
81
82
82
So you might ask, why make such a trouble, why not directly in the Handler function to get a hash table, and then store the `Sid` and `Session` structure mapping ?
83
83
84
84
**That's the design trick!** Let's talk about why it is divided into `Manager`、`Provider` and `Session`。
85
85
86
-
87
86
Let's start with `Session` at the bottom. Since session is a key-value pair, why not use a hash table directly, but abstract such a data structure?
88
87
89
88
First, because the `Session` structure may not only store a hash table, but also some auxiliary data, such as `Sid`, number of accesses, expiration time, or last access time, which is easy to implement algorithms like LRU and LFU.
@@ -94,12 +93,12 @@ Therefore, `Session` structure provides a layer of abstraction to shield the dif
94
93
95
94
```go
96
95
typeSessioninterface {
97
-
//设置键值对
96
+
//Set key-value pairs
98
97
Set(key, val interface{})
99
-
//获取 key 对应的值
98
+
//Get the value by key
100
99
Get(key interface{}) interface{}
101
-
//删除键 key
102
-
Delete(key interface{})
100
+
//Remove key
101
+
Delete(key interface{})
103
102
}
104
103
```
105
104
@@ -111,25 +110,23 @@ Therefore, `Provider` as a container is to shield algorithm details and organize
111
110
112
111
```go
113
112
typeProviderinterface {
114
-
//新增并返回一个 session
113
+
//Add and return session
115
114
SessionCreate(sid string) (Session, error)
116
-
//删除一个 session
115
+
//Delete a session
117
116
SessionDestroy(sid string)
118
-
//查找一个 session
117
+
//Read a session
119
118
SessionRead(sid string) (Session, error)
120
-
//修改一个session
119
+
//Update a session
121
120
SessionUpdate(sid string)
122
-
//通过类似 LRU 的算法回收过期的 session
123
-
SessionGC(maxLifeTime int64)
121
+
//Recycle expired sessions through an algorithm similar to LRU
122
+
SessionGC(maxLifeTime int64)
124
123
}
125
124
```
126
125
127
-
128
126
Finally, `Manager`, most of the specific work is delegated to `Session` and the `Provider`, `Manager` is mainly a set of parameters, such as the survival time of the session, the strategy to clean up expired sessions, and the session's available storage methods. `Manager` blocks the specific details of the operation, and we can flexibly configure the session mechanism through `Manager`.
129
127
130
128
In summary, the main reason for the session mechanism to be divided into several parts is decoupling and customization. I have seen several use Go to implement session services on Github, the source code is very simple, if you are interested you can learn:
0 commit comments