Various encryption algorithms involved in CTF reverse engineering

RC4 principle research

In cryptography, RC4 (abbreviation from Rivest Cipher 4) is a stream cipher algorithm with variable key length. It uses the same key for encryption and decryption, so it is also a symmetric encryption algorithm. RC4 is the encryption algorithm used in Wired Equivalent Privacy (WEP) and was once one of the algorithms available for TLS. The principle of the RC4 algorithm is very simple, including the initialization algorithm (KSA) and the pseudo-random sub-password generation algorithm (PRGA).

Simple implementation of RC4 algorithm flow

1. 1-256 Initialize S-Box and temporary vector T

for i in range(0,255):</code><code>S[i]=i</code><code>T[i]=K[imodkeylen]

2. Initial arrangement of S-Box and shuffle processing

j=0</code><code>for i in range(0,255):</code><code>j=(j + S[i] + T[i]) %6</code><code>swap(s[i],s[j])

3. Generate key stream len: plaintext is len bytes

int i=0,j=0,t;</code><code>while(len--)</code><code>i=(i + 1)%6;</code><code>j=(j + S[i])%6;</code><code>S[i]=S[i] + S[j];</code><code>S[j]=S[ i]-S[j];</code><code>S[i]=S[i]-S[j];</code><code>t=(S[i] + S[j]) %6;</code><code>k.push_back(S[t]);
  1. XOR the subkey sequence with the plaintext to obtain the ciphertext

Data[k]^=S[T]

A brief summary of the RC4 algorithm process

Maybe this is still not easy to understand. Let’s simply write it:

1. First initialize the state vector S (256 bytes, used as seed 1 for key stream generation)

In ascending order, assign each byte a value of 0,1,2,3,4,5,6….,254,255

2. Initial key (entered by user), any length

If input length is less than 256 bytes, rotate until full

For example, if the key entered is 1,2,3,4,5, then the key entered is 1,2,3,4,5,1,2,3,4,5,1,2,3,4,5 ……..

3. Start replacing the state vector S (used to disrupt the initial seed 1)

Follow these rules:

Starting from the zeroth byte, it is executed 256 times to ensure that each byte is processed and that the processed state vector S has a certain degree of randomness.

j = 0;</code><code>for (i = 0 ; i < 256 ; i + + ){<!-- --></code><code>j = (j + S[ i] + T[i]) mod 256;</code><code>swap(S[i] , S[j]);</code><code>}

4. Key stream generation and encryption

Assume that my plaintext bytes are datalength=1024 bytes (of course it can be any number of bytes)

i=0;</code><code>j=0;</code><code>while(datalength--){//This is equivalent to executing 1024 times, and the secret key stream generated in this way is also 1024 words. section</code><code>i = (i + 1) mod 256;</code><code>j = (j + S[i]) mod 256;</code><code>swap(S[i ] , S[j]);</code><code>t = (S[i] + S[j]) mod 256;</code><code>k = S[t];K here is the current A bit in the generated key stream</code><code>//can be encrypted directly here. Of course, you can also save the key stream in an array, and finally perform XOR and it will be ok</code><code>data[]=data[]^k; //Encrypt, "^" is the XOR operator</code><code>}

RC4 algorithm reverse feature recognition

What characteristics should we pay attention to when using reverse analysis software such as ida to identify the RC4 algorithm? There are three main ones:

The data filling process of S box and T box: 2 For loops with a length of 256, data exchange when the S box is out of order, and the final XOR encryption and decryption

Data filling process of S box and T box: 2 For loops with a length of 256, filling 1~255

Data exchange process when s boxes are out of order

XOR/encryption and decryption operations

Software-assisted identification:

For standard encryption algorithms, you can also use PEID’s “Krypto ANALyzer” plug-in or IDA’s “FindCrypt2” plug-in to identify them.

RC4 algorithm question setting and solving

Question: A rookie’s c++ rc4 encryption attempt

Through the above introduction, we have a preliminary understanding of the RC4 algorithm, so we try to use c++ to write a simple rc4 encryption reverse problem. The source code is as follows

#include<bits/stdc + + .h></code><code>#include<windows.h></code><code>using namespace std;</code><code>char* base64Encode( char const* origSigned, unsigned origLength) //Since rc4 encryption mostly contains invisible characters or garbled characters, base64 is used as an intermediary</code><code>{ </code><code>static const char base64Char[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /"; </code><code>unsigned char const* orig = (unsigned char const*)origSigned; </code><code>if (orig == NULL) return NULL; </code>
<code>unsigned const numOrig24BitValues = origLength/3; </code><code>bool havePadding = origLength > numOrig24BitValues*3; </code><code>bool havePadding2 = origLength == numOrig24BitValues*3 + 2; </code> <code>unsigned const numResultBytes = 4*(numOrig24BitValues + havePadding); </code><code>char* result = new char[numResultBytes + 1]; </code>
<code>// Map each full group of 3 input bytes into 4 output base-64 characters: </code><code>unsigned i; </code><code>for (i = 0; i < numOrig24BitValues; + + i) </code><code>{ </code><code>result[4*i + 0] = base64Char[(orig[3*i]>>2) & amp;0x3F]; </code><code>result[4*i + 1] = base64Char[(((orig[3*i] & amp;0x3)<<4) | (orig[3*i + 1]>>4)) & amp;0x3F ]; </code><code>result[4*i + 2] = base64Char[(((orig[3*i + 1] & amp;0x0f)<<2) | (orig[3*i + 2] >>6)) & amp;0x3F]; </code><code>result[4*i + 3] = base64Char[(orig[3*i + 2] & amp;0x3f) & amp;0x3F]; </code><code>} </code>
<code>// Now, take padding into account. (Note: i == numOrig24BitValues) </code><code>if (havePadding) </code><code>{ </code><code>result[4* i + 0] = base64Char[(orig[3*i]>>2) & amp;0x3F]; </code><code>if (havePadding2) </code><code>{ </code><code> result[4*i + 1] = base64Char[(((orig[3*i] & amp;0x3)<<4) | (orig[3*i + 1]>>4)) & amp;0x3F]; </code><code>result[4*i + 2] = base64Char[((orig[3*i + 1] & amp;0x0f)<<2) & amp;0x3F]; </code><code> } </code><code>else </code><code>{ </code><code>result[4*i + 1] = base64Char[((orig[3*i] & amp;0x3)<< 4) & amp;0x3F]; </code><code>result[4*i + 2] = '='; </code><code>} </code><code>result[4*i + 3] = '='; </code><code>} </code>
<code>result[numResultBytes] = '/0'; </code><code>return result; </code><code>} </code><code>?</code><code>?</code><code>void mima_init(unsigned char *s,unsigned char *key,unsigned long Len)//Initialization</code><code>{<!-- --></code><code>char t [256]={0};</code><code>unsigned char tmp=0;</code><code>for(int i=0;i<256;i + + )//Initialize s box</code><code>{<!-- --></code><code>s[i]=i;</code><code>t[i]=key[i%Len];</code> <code>}</code><code>for(int i=0;i<256;i + + )//s box out of order</code><code>{<!-- --></code><code>int j=(j + s[i] + t[i])%6;</code><code>tmp=s[i];</code><code>s[i]=s [j];</code><code>s[j]=tmp;</code><code>} </code><code>} </code><code>//Encryption and decryption shared function</code><code>char mima_crypt(unsigned char *s,unsigned char *Data,unsigned long Len)</code><code>{<!-- --></code><code>int i=0,j= 0,t=0;</code><code>unsigned long k=0;</code><code>unsigned char tmp;</code><code>for(k=0;k<Len;k + + )</code><code>{<!-- --></code><code>//Key stream</code><code>i=(i + 1)%6;</code><code>j=(j + s[i])%6;</code><code>tmp=s[i];</code><code>s[i]=s[j];</code> <code>s[j]=tmp;</code><code>t=(s[i] + s[j])%6;</code><code>//XOR encryption and decryption</code> <code>Data[k]^=s[t]; </code><code>} </code><code>}</code><code>?</code><code>int getStr(char * buffer,int maxLen){<!-- --></code><code>char c; // A character read</code><code>int len = 0; // The currently input string The length of </code><code>// Read one character at a time and save it to buffer</code><code>// Stop reading until a newline character (\\
) is encountered or the length exceeds maxLen</code><code>while( (c=getchar()) != '\\
' ){<!-- --></code><code>buffer[len + + ]=c; / / Save the read characters to buffer</code><code>if(len>=maxLen){<!-- --></code><code>break;</code><code>}</code><code>}</code><code>buffer[len]='\0'; // End of reading, manually add the string end flag at the end</code><code>fflush( stdin); // Refresh the input buffer</code><code>return len;</code><code>}</code><code>?</code><code>?</code><code> int main(int argc,_TCHAR* argv[])</code><code>{<!-- --></code><code>char key[256]={""};//Yes Custom key</code><code>char flag[25];</code><code>uint8_t keyLen = 0;</code><code>char pData[256]={"f5pwXQlV5R9HMfFL6pt3YdVEeP5d9DA="}; //Cryptotext</code><code>unsigned char s1[256]={0},s2[256]={0};</code><code>unsigned long len= strlen(pData);</code><code>printf("please input your flag:\\
");</code><code>getStr(flag,23);</code><code>//Initialization</code><code>//unsigned long len= strlen(flag2);</code><code>mima_init(s1, (unsigned char*)key, strlen(key));</code><code>mima_crypt(s1, (unsigned char *)flag, len);</code><code>//cout<<(unsigned char*)base64Encode(flag,strlen(flag));</code><code>if(!strcmp("rFZuHVPo6wTcVnbgu176lPOJWixo93wdm2ULsM5fFrc= 0",base64Encode(flag,strlen(flag))))//Violent judgment caused by imperfect writing of the judgment mechanism</code><code>printf("you are right good boy!\\
") ;</code><code>else</code><code>printf("Try again!");</code><code>cout<<(unsigned char*)base64Encode(flag,strlen(flag) );</code><code>} </code>

Question: [Anheng Cup 2018-September] NewDriver

The old rule is to check the shell first when you get the re question. Shellless 32-bit. ida open.

The whole fake flag deceives our feelings.

Found three suspicious functions that may be related to encryption and decryption

It is obviously a base64 encryption, and the custom base64 table was found in the search string, confirming our guess.

Follow up on the remaining two key functions and discover rc4 encryption features (XOR, s box initialization, %6 in key stream processing)

In ida, you can directly obtain the ciphertext. To obtain the key, you need to use dynamic debugging to read it from the memory.

At this time we only need to simulate the XOR process

key = '7a a6 6a da cd 0f 16 74 8b be 29 67 aa 79 79 b2 42 64 b2 2c bc 93 18 07 19 6f b7 64 fd 52 59 4f 96 ea 49 3c 11 89 66 39 87 d3 59 84'</code><code>en_flag = '20 C3 1A AE 97 3C 7A 41 DE F6 78 15 CB 4B 4C DC 26 55 8B 55 E5 E9 55 75 40 3D 82 13 A5 60 13 3B F5 D8 19 0E 47 CF 5F 5E DE 9D 14 BD'</code><code>key = key.split(' ')</code><code>en_flag = en_flag.split(' ')</code> <code>en_flags = []</code><code>keys = []</code><code>?</code><code>g = ''</code><code>for i in key :</code><code>keys.append(int(i, 16))</code><code>for i in en_flag:</code><code>en_flags.append(int(i, 16))</code><code>?</code><code>for q in range(len(key)):</code><code>g + = chr(keys[q] ^ en_flags[q])</code><code>print(g)</code>
After running the script, base64 decrypt to get the flag

By the way, save a base64 table change script to prepare for offline competitions that cannot be connected to the Internet.

import base64</code><code>import string</code><code>?</code><code>str1 = "x2dtJEOmyjacxDemx2eczT5cVS9fVUGvWTuZWjuexjRqy24rV29q"</code><code>?</code><code>string1 = "ZYXABCDEFGHIJKLMNOPQRSTUVWzyxabcdefghijklmnopqrstuvw0123456789 + /"</code><code>string2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 + /"</code><code>?</code><code>print (base64.b64decode(str1.translate (str.maketrans(string1,string2))))

Digression

Many people who are new to the computer industry or graduates of computer-related majors from universities encounter difficulties in finding employment due to lack of practical experience. Let’s look at two sets of data:

  • The number of college graduates nationwide in 2023 is expected to reach 11.58 million, and the employment situation is grim;

  • Data released during the National Cyber Security Awareness Week show that by 2027, the shortage of cyber security personnel in our country will reach 3.27 million.

On the one hand, the employment situation for fresh graduates is grim every year, and on the other hand, there is a shortage of one million cybersecurity talents.

On June 9, Max Research’s 2023 Employment Blue Book (including the “2023 China Undergraduate Employment Report” and “2023 China Higher Vocational Students Employment Report”) was officially released.

The top 10 majors with the highest monthly income for college graduates in 2022

Undergraduate computer majors and higher vocational automation majors have higher monthly incomes. The monthly incomes of the 2022 undergraduate computer majors and higher vocational automation majors are 6,863 yuan and 5,339 yuan respectively. Among them, the starting salary of undergraduate computer majors is basically the same as that of the 2021 class, and the monthly income of higher vocational automation majors has increased significantly. The 2022 class overtook the railway transportation major (5,295 yuan) to rank first.

Looking at the major specifically, the major with the highest monthly income for the 2022 undergraduate class is information security (7,579 yuan). Compared with the class of 2018, undergraduate majors related to artificial intelligence such as electronic science and technology and automation performed well, with starting salaries increasing by 19% compared with five years ago. Although data science and big data technology are new majors in recent years, they have performed well and have ranked among the top three majors with the highest monthly income for 2022 undergraduate graduates six months after graduation. French, the only humanities and social sciences major that entered the top 10 highest-paying undergraduates five years ago, has dropped out of the top 10.

Picture

“There is no national security without cybersecurity.” At present, network security has been elevated to the level of national strategy and has become one of the most important factors affecting national security and social stability.

Characteristics of the network security industry

1. The employment salary is very high and the salary increases quickly. In 2021, Liepin.com announced that the employment salary in the network security industry is the highest per capita of 337,700!

Picture

2. There is a large talent gap and many employment opportunities

On September 18, 2019, the official website of the “Central People’s Government of the People’s Republic of China” published: my country’s demand for cyberspace security talents is 1.4 million, but major schools across the country train less than 1.5 million people every year. Liepin.com’s “Cybersecurity Report for the First Half of 2021” predicts that the demand for network security talents in 2027 will be 3 million. Currently, there are only 100,000 employees engaged in the network security industry.

Picture

The industry has huge room for development and there are many jobs

Since the establishment of the network security industry, dozens of new network security industry positions have been added: network security experts, network security analysts, security consultants, network security engineers, security architects, security operation and maintenance engineers, penetration engineers, information security management Officer, data security engineer, network security operations engineer, network security emergency response engineer, data appraiser, network security product manager, network security service engineer, network security trainer, network security auditor, threat intelligence analysis engineer, disaster recovery professional , Practical attack and defense professionals…

Great career value-added potential

The network security major has strong technical characteristics, especially mastering the core network architecture and security technologies at work, which has an irreplaceable competitive advantage in career development.

As personal abilities continue to improve, the professional value of the work they do will also increase with the enrichment of their experience and the maturity of project operations, and the room for appreciation will continue to increase. This is the main reason why it is popular with everyone.

To a certain extent, in the field of network security, just like the medical profession, the older you get, the more popular you become. Because the technology becomes more mature, your work will naturally be taken seriously, and promotion and salary increases will come naturally.

If you are interested in getting started with network security, then you click hereCSDN gift package: “Hacker &Introduction to Network Security&Advanced Learning Resource Pack” to share for free h3>

If you are interested in network security, learning resources are shared for free, guaranteed to be 100% free! ! ! (Heyke introductory tutorial)

1. Growth roadmap & learning plan

To learn a new technology, as a novice, you must learn the growth roadmap first. In the wrong direction, efforts will be in vain.

For students who have never been exposed to network security, we have prepared a detailed learning and growth roadmap & learning plan for you. It can be said to be the most scientific and systematic learning route. It will be no problem for everyone to follow this general direction.

Picture

Picture

2. Video tutorial

Many friends don’t like obscure texts, so I have also prepared video tutorials for everyone. There are 21 chapters in total, and each chapter is a condensed essence of the current section.

Picture

Picture

3.SRC & Hacker Books

Everyone’s favorite and most concerned SRC technical books & hacker technology are also included

SRC technical documents:

Picture

Since hacker information is a sensitive resource, it cannot be displayed directly here!

4. Information on network protection operations

Regarding the HW network protection operation, corresponding information has also been prepared. This content can be equivalent to the golden finger of the competition!

Picture

5. A must-read list for hackers

Picture

6. Collection of interview questions

When you learn this by yourself, you will start to think about finding a job, and the things that cannot be avoided in work are real questions and interview questions.

Picture

To prevent harmonization, you can scan and obtain more content~

Picture

This complete version of the network security (Heyke) complete set of learning materials has been uploaded to the CSDN official. If you need to click the link belowyou can also scan the WeChat 2 v code below to obtain the network A complete set of information for engineers[100% free guaranteed]

If you need it, you can click CSDN gift package: “Hey Guest & Network Security Introduction & Advanced Learning Resource Pack” to share for free

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Algorithm skill tree Home page Overview 57284 people are learning the system