IOS reverse development (a) cryptography RSA

IOS reverse development (2) Cryptographic HASH

IOS reverse development (3) application signature

IOS Reverse Development (21) Assembler – Basics

1. HASH algorithm introduction

1.1 What is HASH?

  • Hash algorithm (also called Hash algorithm)

A Hash is a Hash algorithm that transforms an input of arbitrary length into an output of fixed length, which is the Hash value. This transformation is a compression mapping, that is, the space of hash values is usually much smaller than the space of input, and different inputs may be hashed into the same output, so it is impossible to determine a unique input value from the hash value. Simply put, it is a function that compresses a message of any length into a message digest of a fixed length

Let me give you an example. Each of us living in the world needs a mark that identifies us in order to be able to participate in various social activities. You may think that your name or id card is enough to represent you, but this representation is fragile because there are many people with the same name and ID cards can be forged. The most reliable way to represent a person is to record all of their genetic sequences, but obviously, that’s not practical. Fingerprints seem like a good option, though some professional organizations can still simulate someone’s prints, but the cost is prohibitive. Just as important is how a document is identified as it travels through the Internet. For example, we download a file, the file download process will go through a lot of network servers, routers, how to ensure that this file is what we need? Since it is impossible to detect every byte of a file, or simply use easily disguised information such as file name and size, we need a fingerprint to check the reliability of the file. This fingerprint is the Hash algorithm we use today.

  • A Hash Algorithm, also known as a Hash Algorithm, is a method of creating small digital fingerprints from any file. Like a fingerprint, a hash algorithm is a token of a unique file with a short message that is related to every byte of the file, and it is difficult to find a reverse pattern. Therefore, when the original file is changed, its flag value will also change, which tells the file user that the current file is not the one you want.
  1. What does this sign mean? The previous file download process is a good example, in fact, most network deployment and version control tools now use hashing algorithms to ensure file reliability. On the other hand, when we use file system synchronization, backup and other tools, we use hash algorithm to mark the file unique performance to help us reduce the system overhead, which is applied in many cloud storage servers.
  2. Of course, as a fingerprint, the most important use of hashing algorithms is to add encryption protection to highly secure content such as certificates, documents, and passwords. The main reason for this is the irreversibility of hashing algorithms. Not only is it impossible to get the original file from a hash fingerprint, but it is also impossible to simply create a file and match its fingerprint to a target fingerprint. This irreversibility of hash algorithms keeps many security frameworks afloat,

1.2 Hash Features

  1. The algorithm is public

  2. The same data, you get the same answer

  3. The default result of different data operations, such as MD5, is 128 bits,32 characters (hexadecimal identifier).

  4. You can’t reverse it

  5. A good hash algorithm will implement:

  1. Forward fast: Given a plaintext and hash algorithm, a hash value can be computed in limited time and resources.
  2. Reverse difficulty: Given (several) hash values, it is difficult (almost impossible) to reverse derive plaintext in finite time.
  3. Input sensitivity: The hash value produced by modifying a bit of the original input should look very different.
  4. Conflict avoidance: It is difficult to find two pieces of plaintext with different contents that have the same hash value (conflict). That is, for any two different data blocks, the possibility of the same hash value is very small; For a given block, it is extremely difficult to find a block with the same hash value.

1.3 Functions of Hash

  • The main uses are:
  1. Encryption of user passwords
  2. Search engine
  3. copyright
  4. A digital signature
  • Application of Hash in cryptography

In cryptography, the hash algorithm is mainly used for message digest and signature, in other words, it is mainly used to verify the integrity of the entire message. For example, when we log in to Zhihu, we all need to enter a password, so if zhihu saves this password in plain text, hackers will easily steal everyone’s password to log in, which is particularly unsafe. So Zhihu came up with a method to generate a password signature using the hash algorithm, and zhihu only saved the signature value in the background. Since the hash algorithm is irreversible, it would be useless for a hacker to get the signature; If you enter your password on the login interface, Zhihu backstage will recaluate the hash value and compare it with the original hash value stored on the website. If it is the same, it will prove that you have the password of this account and allow you to log in. The same is true of banks, which do not dare to save the original text of the user password, but only the hash value of the password. In these application scenarios, collision and tamper resistance are highly required, and speed is secondary. A well-designed hash algorithm is highly collision-resistant. Take MD5 as an example, its output length is 128 bits, and the design expects the collision probability to be 2^128, which is a very, very small number — even after MD5 was decrypted by Professor Wang Xiaoyun, the upper limit of collision probability is as high as high, that is, it takes at least one search to have a 1/2 probability to find a hash value that is the same as the target file.

1.4 Popular Hash Algorithms

  • The current popular Hash algorithms include MD5, SHA-1, and SHA-2.

  • MD4 (RFC 1320) was designed in 1990 by Ronald L. Rivest of MIT, MD stands for Message Digest. Its output is 128 bits. MD4 has been shown to be unsafe.

  • MD5 (RFC 1321) is an improved version of MD4 developed by Rivest in 1991. It still groups inputs in 512 bits, and its output is 128 bits. MD5 is more complex than MD4 and is a bit slower and more secure. MD5 has been shown not to be “strongly crash-resistant”.

  • Secure Hash Algorithm (SHA) is a family of Hash functions. The first Algorithm was published by the National Institute of Standards and Technology (NIST) in 1993. The current version, SHA-1, was introduced in 1995, and its output is a 160-bit hash value, making it more resistant to enumeration. Sha-1 is designed based on the same principles as MD4 and mimics this algorithm. Sha-1 has been shown not to be “highly crash-resistant”.

  • To improve security, NIST also designs sha-224, SHA-256, SHA-384, and SHA-512 algorithms (collectively known as SHA-2), which are similar in principle to SHA-1. Sha-3 correlation algorithms have also been proposed.

1.5 Collision of Hash Algorithms

  • If we take any 9 numbers, we are sure to get at least two identical values, which we call the “Collision” of the hashing algorithm.

This is easy to understand because, as a working hash algorithm, it must have a finite number of bits, meaning that it can record a finite number of files — and with an infinite number of files, the probability of two file fingerprints colliding is never zero. But that doesn’t mean hash algorithms can’t be used, because there’s always a cost to everything, and there’s no point in buying all the tickets to win a single jackpot. The reason for the existence of modern hashing algorithms is that their irreversibility is achieved with a high probability, that is, the probability of finding a collision is low, and the probability of such a collision being exploited is low. It’s possible to find a random set of collisions, just by doing it all. The hash algorithm has a finite number of fingerprint digits, such as MD5’s 128-bit fingerprint, which means that if we do 2^128 of them, we are sure to get a set of collisions — an unimaginable time cost, of course, and more importantly, just finding a set of collisions doesn’t make any sense. What makes more sense is if we already have a set of fingerprints, can we find an original file whose hash is equal to that set of fingerprints? If this is done, we can easily tamper with and forge key information such as network certificates and passwords. You may have heard that MD5 has been cracked — but the truth is, even MD5, an outdated hashing algorithm, is hard to reverse. We now rely more on the volumetric dictionary to try to find out if a file for a fingerprint exists in the database through a large number of file-fingerprint mappings that are already known.

1.6 introduction of MD5

  • The application of MD5
  1. A typical use of MD5 is to produce a message-digest of a Message to prevent tampering. For example, in UNIX, there are many software files with the same file name and the file extension is md5. In this file, there is usually only one line of text, and the general structure is as follows: MD5 (tanajiya.tar.gz) = 0ca175b9c0f726a831d895e269332461
  2. This is the digital signature of the tanajiya.tar.gz file. MD5 takes the entire file as a large text message and uses its irreversible string transformation algorithm to produce a unique digest of the MD5 message.
  3. It is well known that every person on earth has his or her own unique fingerprint, which is often the most reliable way for the police to identify criminals. Similarly, MD5 can create a unique “digital fingerprint” for any file (regardless of size, format, or quantity). If anyone makes any changes to the file name, the MD5 value, or “digital fingerprint”, will change.
  4. We often see the MD5 value in the information of a software in some software download sites. Its function is that we can use special software (such as Windows MD5 Check, etc.) to do an MD5 Check on the downloaded files after downloading the software, so as to ensure that the files we get are the same as those provided by the site. MD5 algorithm is widely used in software download station, forum database, system file security and so on.
  5. A typical use of MD5 is to generate a fingerprint on a piece of Message to prevent it from being “tampered with.” For example, if you write a paragraph in a file called readme.txt and generate an MD5 value for the readme.txt file and record it, then you can spread the file to others, and if they change anything in the file, you will notice when you recalcitate the MD5 of the file. If there is a third party authentication authority, using MD5 can also prevent the author of the file “repudiation”, this is the so-called digital signature application.
  6. MD5 is also widely used in operating system login authentication, such as Unix, various BSD system login password, digital signature and many other aspects. For example, on UNIX systems, passwords are hashed by MD5 (or other similar algorithms) and stored in the file system. When a user logs in, the system hashes the password entered by the user and compares it with the MD5 value saved in the file system to determine whether the entered password is correct. Through such steps, the system can determine the validity of a user’s login without knowing the explicit password of the user. This prevents a user’s password from being known to a user with system administrator privileges. MD5 arbitrary length of the byte string is mapped to a 128 – bit integer, and it is through the 128 – bit push against the original string is difficult, in other words, even if you see the source program and algorithm description, nor will a MD5 value transform back to the original string, says from the mathematical principles, because the original string has an infinite number, This is a bit like a mathematical function without an inverse function. So, if you have md5 password problems, it is a good idea to use the md5() function of this system to reset the password, such as admin, to generate a string of password Hash value overwrite the original Hash value.

1.6.1 MD5 encryption

  • MD5 online encryption website
  • Because MD5 encryption is irreversible, it cannot be cracked normally, but because of the existence of the hash collision mentioned above, so there is a way to crack.

1.6.2 MD5 cracking

  • There is a famous website https://cmd5.com/ which contains many MD5 values. You can check the original MD5 values online.

  • Just md5 encryption 123456 got: 32-bit uppercase md5 value: E10ADC3949BA59ABBE56E057F20F883E

  • Now verify it on the decryption site

Symmetric encryption, asymmetric encryption, HMAC

2.1 HMAC

  • The hash algorithm can be used for encryption in cryptography. For example, when the server authenticates the account information, it does not need to know the password but only needs to verify the MD5 value of the password.
  • Hash encryption is generally used in the following ways:
  1. Use MD5 directly
  2. MD5 salt
  3. HMAC encryption scheme
  • HMAC: HMAC is not an encryption algorithm but an encryption scheme. Encrypted with one key and hashed twice. In real development, the key comes from the server. Each account matches a key.

  • HMAC encryption scheme process:

1. The client fills in an account and sends it to the server for verification. The server returns a random number to the client. 2. This random number is the KEY of the HMAC. The client uses this key to encrypt the password and sends the hash value to the client. The client saves the key. 3. The server saves the hash value sent by the client. The hash value is transmitted only once. Transfer in the case of registration or change of mobile phone login. 4. Each subsequent login authentication will use the hash value plus the server timestamp (accurate to minutes), and then hash again to get the new hash and send it to the server. The server also adds the server time to the hash value it saves, then hashes it again and compares it with the hash sent by the client. Compare this minute with the last minute, as long as there is a successful comparison, success. 5. In one case, the client changed the mobile phone and enabled device authentication, and asked the server for the key. The server sends a request to the authorization device for authorization. The authorization device sends a key, and the authorization device does not send a key.

2.2 Symmetric Encryption

  • What is symmetric encryption?

Symmetric encryption (also known as private key encryption) is an encryption algorithm that uses the same key for encryption and decryption. Sometimes called traditional cryptographic algorithm, the encryption key can be calculated from the decryption key, and the decryption key can also be calculated from the encryption key. In most symmetric algorithms, the encryption key and decryption key are the same, so this encryption algorithm is also called secret key algorithm or single key algorithm. It requires the sender and receiver to agree on a key prior to secure communication. The security of symmetric algorithms depends on the key, and leaking the key means that anyone can decrypt the message they send or receive, so the confidentiality of the key is crucial to communication.

  • Advantages of symmetric encryption

Symmetric encryption algorithm is characterized by open algorithm, small computation, fast encryption speed and high encryption efficiency

  • Disadvantages of symmetric encryption algorithms?
  1. A secure channel is required for both parties to negotiate a common key when communicating for the first time. Direct face-to-face negotiations may be impractical and difficult to implement, so the parties may have to resort to other relatively insecure means such as email and telephone to negotiate.
  2. The number of keys is difficult to manage. Because each partner needs to use a different key, it is difficult to adapt to the large amount of information exchange in an open society;
  3. Symmetric encryption algorithms generally cannot provide information integrity identification. It cannot verify the identity of the sender and receiver;
  4. The management and distribution of symmetric keys is a potentially dangerous and cumbersome process. Symmetric encryption is realized on the basis of keeping secrets together. Both sides of the trade using symmetric encryption technology must ensure that they use the same key, ensure that the exchange of the key is safe and reliable, and at the same time, set up procedures to prevent the leakage of the key and change the key.

2.2.1 Common symmetric encryption algorithms

  • Commonly used symmetric encryption algorithms are: DES algorithm, 3DES algorithm, TDEA algorithm, Blowfish algorithm, RC5 algorithm, IDEA algorithm.
  • Principle of symmetric encryption algorithm

The advantages of symmetric encryption algorithm lie in the high speed of encryption and decryption and the difficulty of cracking when using long keys. Assume that two users need to use symmetric encryption to encrypt and exchange data, users need at least two keys to exchange data. If there are n users in an enterprise, the entire enterprise needs N x (N-1) keys. Generating and distributing keys becomes a nightmare for the enterprise information department. The security of the symmetric encryption algorithm depends on the situation of the preservation of the encryption key, but it requires the enterprise each hold a key person in is impossible to keep a secret, they will usually have intention to not intentional of take the key leaking out – if a user and the key was obtained by invaders, an intruder can read the user key encrypt all the documents, If the entire enterprise shares a single encryption key, the confidentiality of the entire enterprise document is impossible.

  • DES encryption algorithmDES encryption algorithm is the most classical symmetric encryption algorithm. DES encryption uses packet encryption. The 56-bit key is used to encrypt the 64-bit plain text, and finally the 64-bit ciphertext is generated. The basic flow of DES algorithm is as follows:
  1. DES performs operations on the 64-bit plaintext group M, which is replaced by M0 through an initial replacement IP. M0 is divided into the left half and the right half m0= (L0,R0), each 32 bits long. It then performs 16 rounds of exactly the same operations, called function F, in which the data is combined with the key. After 16 rounds of operation, it can be seen that in the 16th round of operation, the result of the 15th round of operation on the right (R15) is taken as the final result of operation on the left (L16), and the final result on the right (R16) is the xOR operation of operation on the 15th round of operation on the left (L15) and operation result of function F. After that, the left and right parts are combined together through an inverse permutation to output ciphertext.
  2. The actual encryption process is divided into two simultaneous processes, namely the encryption process and the key generation process:
  3. In each round of the 16-round cycle, the key bits are shifted, and 48 of the 64 bits of the key are selected. The right half of the data is expanded to 48 bits by an extended permutation, and replaced with the new 32-bit data by an xor operation, which is replaced once more. These four operations form the function f in Figure 6-2. Then, by another xOR operation, the output of the function F is combined with the left half, and the result becomes the new right half, and the original right half becomes the new left half. Repeat this operation 16 times.
  4. The decryption process of DES algorithm is almost exactly the same as the encryption process, but the key is used in the opposite order.
  5. The National Institute of Standards and Technology (NIST) released the new DES encryption standard in 1999. 3DES replaced DES as the new encryption standard. 3DES uses the 168-bit key and triple encryption, but the speed is slow. Later, Advanced Encryption Standard (AES) and other Advanced symmetric secret algorithms emerged.
  • TripleDES encryption algorithm:
  1. Due to the security of DES algorithm, triple-DES algorithm is proposed to improve the anti-attack of DES algorithm.
  2. The basic principle of triple-DES algorithm is to encrypt/decrypt data three times with two keys. That is, the first key is used to encrypt data, the second key is used to decrypt data, and the first key is used to encrypt data. The two keys can be the same or different. They can also be derived from a 128-bit key, which is divided into two 64-bit keys during encryption/decryption. The two 64-bit keys are used alternately for encryption/decryption. Triple-des algorithm retains the fast operation speed of DES algorithm and increases the cracking time by increasing the number of operations and the key length (two 64-bit keys are equivalent to 128-bit keys). However, from the perspective of cryptography itself, its security intensity does not increase.
  • RC series algorithms:
  1. The RC series algorithms we use now include RC2, RC4, RC5 and RC6 algorithms, among which RC4 is a sequential cipher algorithm and the other three are block cipher algorithms.
  2. RC2 algorithm: this algorithm is designed to replace DES algorithm, it uses the variable key length of the plaintext to take 64 bit packet encryption algorithm, belongs to Festel network structure.
  3. RC4 algorithm: this algorithm is a byte stream oriented encryption algorithm with variable key length, based on random permutation. The algorithm is fast and requires only 8~16 bytes of machine instruction for each output byte. The RC4 algorithm is relatively easy to describe. It first initializes a 256-byte state vector S with a key of 8 to 2048 bits variable length. The members of S are marked with S[0],S[1]… S[255], the whole substitution process contains 8 bits from 0 to 255. For encryption and decryption, let byte data be K, which is generated by selecting one of the 256 elements in S in a certain way. For each value of K generated, the data in the element is replaced once.
  • Rijndael algorithm:
  1. Rijndael is an iterative encryption algorithm that allows variable blocks of data and the length of the key. Data blocks and key lengths vary independently.
  2. Two terms are defined in Rijndael algorithm: State: the intermediate value generated during the operation is a 4×Nb matrix, Nb can be obtained by dividing the data length by 32 bits, that is, dividing the data into Nb blocks. Cipher Key: a Key used for encryption, in the form of a 4 x Nk matrix. Nk can be obtained by dividing the length of the Key by 32 bits. That is, the Key is divided into Nk 32 bits of sub-keys.
  3. In Rijndael algorithm, the number of operation turns (Nr) is determined by Nb and Nk

2.3 Asymmetric encryption

  • What is asymmetric encryption?

Asymmetric encryption: encryption algorithms that use different keys for encryption and decryption. Asymmetric encryption algorithms require two keys: a publickey and a privatekey. The public key and private key are a pair. If the public key is used to encrypt data, only the corresponding private key can be used to decrypt data. If data is encrypted with a key, only the corresponding public key can be used to decrypt it. Because encryption and decryption use two different keys, the algorithm is called asymmetric encryption.

  • Asymmetric encryption features:

The characteristics of asymmetric cryptography: the algorithm strength is complex, the security depends on the algorithm and the key, but because of the complexity of the algorithm, the encryption and decryption speed is not as fast as that of symmetric encryption and decryption. In symmetric cryptography, there is only one key, and it is not public. To decrypt it, the other party must know the key. Therefore, to ensure its security is to ensure the security of the key, and asymmetric key system has two kinds of key, one of which is public, so that there is no need to transmit the other party’s key like symmetric cipher. That’s a lot safer.

  • Asymmetric encryption algorithm is a secret key method.

  • The typical asymmetric encryption algorithm is RSA encryption, which is used by most banks. More details on RSA encryption can be found in my previous blog: IOS Reverse Development (I) Asymmetric encryption RSA

  • Contrast symmetric and asymmetric encryption

  1. The characteristics of asymmetric cryptography: the algorithm strength is complex, the security depends on the algorithm and the key, but because of the complexity of the algorithm, the encryption and decryption speed is not as fast as that of symmetric encryption and decryption.
  2. In the symmetric cryptosystem, there is only one kind of key, and it is not public. If you want to decrypt it, you have to let the other party know the key, so ensuring its security is to ensure the security of the key. Asymmetric cryptography, on the other hand, has two keys, one of which is public, thus eliminating the need to transmit the other party’s key as symmetric cryptography does. That’s a lot safer.
  3. Suppose two users want to encrypt and exchange data, and the two parties exchange public keys. One party uses the other party’s public key to encrypt data, and the other party can decrypt data with its own private key.
  4. If an enterprise has n users, it needs to generate N pairs of keys and distribute N public keys. Since public keys can be made public, users only need to keep their private keys, so the distribution of encryption keys becomes very simple. At the same time, since each user’s private key is unique, other users can verify the authenticity of the source of the information through the “sender’s public key”, and ensure that the sender cannot deny sending the information. The disadvantage of asymmetric encryption is that the encryption and decryption speed is much slower than symmetric encryption, in some extreme cases, up to 1000 times slower than symmetric encryption.
  5. Asymmetric encryption system does not require the communication parties to transfer the key in advance or have any agreement to complete the confidential communication, and the key management is convenient to prevent counterfeiting and denial, so it is more suitable for the requirements of the confidential communication in network communication.
  • In general, there are the following points:
  1. Symmetric encryption Encryption and decryption use the same key, so the encryption speed is fast. However, because the key needs to be transmitted over the network, the security is not high.
  2. Asymmetric encryption uses a pair of keys, a public key and a private key, so it has high security but slow encryption and decryption speed.
  3. The common solution is to encrypt the symmetric encryption key with the asymmetric encryption public key, and then send it. The receiver uses the private key to decrypt the symmetric encryption key, and then the two parties can use the symmetric encryption to communicate. This is how it is used in HTTPS.

2.3.1 Asymmetric Encryption Algorithm

  • RSA, Elgamal, knapsack algorithm, Rabin, HD,ECC (Elliptic curve encryption algorithm).
  • The most widely used algorithm is RSA, and Elgamal is another commonly used asymmetric encryption algorithm.
  • Elgamal was invented by Taher Elgamal in 1985. It is based on the DiffieˉHellman key exchange algorithm, which enables the communication parties to deduce the secret key value known only by them through open communication. DiffieˉHellman was invented by Whitfield Diffie and Martin Hellman in 1976, which is regarded as the first asymmetric cryptography algorithm. The difference between DiffieˉHellman and RSA is that DiffieˉHellman is not a cryptography algorithm. It simply generates a secret value that can be used as a symmetric key. In the Process of DiffieˉHellman key exchange, the sender and the receiver generate a secret random number respectively, and deduce the public value according to the random number. Then, the two sides exchange the public value. The basis of the DiffieˉHellman algorithm is the ability of generating shared keys. Once the public value is exchanged, both parties can use their private number and the other party’s public value to generate a symmetric key, called a shared key. The symmetric key is the same for both parties and can be used to encrypt data using a symmetric encryption algorithm.
  • One of the advantages of DiffieˉHellman over RSA is that a new set of values is used every time the key is exchanged, whereas with RSA, if the attacker obtains the private key, he can decrypt not only the previously intercepted message, but all subsequent messages as well. However, RSA can prevent man-in-the-middle attacks through authentication (such as using X.509 digital certificates), but Diff Ie ˉHellman is very vulnerable to man-in-the-middle attacks.

2.3.2 Complete asymmetric encryption process

  • If you now transfer money to Alipay (the term data information), in order to ensure the confidentiality, authenticity, integrity and non-repudiation of information transmission, digital encryption and signature of the transmitted information is required, and the transmission process is as follows:
  1. First of all, you should confirm whether it is the digital certificate of Alipay. If it is confirmed as the identity of Alipay, the other party is authentic and credible. Can send messages to each other;
  2. You are ready to transfer digital information (clear text) to calculate how much money to transfer, the other party alipay account number;
  3. You hash digital information to get a summary of the information (the client’s main responsibility).
  4. You encrypt the message digest with your private key to get your digital signature and attach it to the digital message;
  5. You randomly generate an encryption key and use it to encrypt the message to be sent (ciphertext);
  6. You use alipay’s public key to encrypt the encryption key randomly generated just now, and send the encrypted DES key together with the ciphertext to Alipay.
  7. Alipay received you sent to the ciphertext and encrypted DES key, with their own private key to encrypt the DES key decryption, get you randomly generated encryption key;
  8. Alipay then uses the random key to decrypt the ciphertext received, get the plaintext digital information, and then discard the random key;
  9. Alipay uses your public key to decrypt your digital signature and get a summary of the information.
  10. Alipay uses the same hash algorithm to hash the received plaintext again to get a new message summary.
  11. Alipay compares the received information summary with the newly generated information summary. If it is consistent, the received information has not been modified.
  12. Confirm receipt of the message, then proceed to the payment transaction to the other party, the end of an asymmetric encryption process.

2.3.3 Application mode of symmetric encryption

  • ECB (Electronic Code Book) : Electronic Code Book mode. Each piece of data is encrypted independently.

The most basic encryption mode, that is, commonly understood encryption, the same plaintext will always be encrypted into the same ciphertext, no initial vector, vulnerable to passbook replay attacks, rarely used in general.

  • Cipher Block Chaining (CBC) : Cipher Block Chaining mode. Data is encrypted using a key and an initialization vector [IV].

The plaintext is encrypted after xOR operation with the previous ciphertext. Therefore, the same ciphertext will be encrypted after different initial vectors are selected. This is the most widely used ciphertext mode. CBC encrypted ciphertext is context-dependent, but plaintext errors are not passed to subsequent groups, but if one group is lost, all subsequent groups are invalidated (synchronization errors).

2.3.3.1 Terminal Authentication

  • Terminal input:vi message.txt
  • Edit the text information using vi as follows:
  • Press esc and enter:wqsave
  • Then the terminal enters:openssl enc -des-ecb -K 616263 -nosalt -in message.txt -out msg1.binSend message. TXT to ECB (Electronic Code Book) : Electronic codebook mode. Each piece of data is encrypted independently. The output is saved to msg1.bin.

Note: in the above encryption command 616263 is the encryption key,-nosalt means nosalt.

  • After output, we can see that the msg1.bin file is generated:

  • Then we modify the message.txt file slightly:

  • Run the openssl enc-des-ECB-k 616263-nosalt -in message. TXT -out msg2.bin command to encrypt the msG2. bin file.

  • What is the difference between msg1.bin and msg2.bin

  • We use the XXD msg1.bin command to view:

  • Only one number is changed, but the entire block of 8 bytes is different, indicating that it is encrypted block by block.

  • Openssl enc-des-CBC-iv 0102030405060708 -k 616263 -nosalt -in message. TXT -out msg3.bin to obtain the encrypted file MSg3.bin

  • Then we modify the original message.txt file to change the 2 back to 1

  • Openssl enc-des-cbC-iv 0102030405060708 -k 616263 -nosalt -in message. TXT -out msg4.bin to obtain the encrypted file msg4.bin

  • Bin, XXD msg3.bin, XXD msg4.bin to compare msg3.bin and msg4.bin files.

  • Cipher Block Chaining (CBC) : indicates the Cipher Block Chaining mode. Data is encrypted using a key and an initialization vector [IV]. Encryption is the password chain.

3. Digital signature

  • What is a digital signature?
  1. Digital signature: An abstract message encrypted with the sender’s private key and sent to the receiver along with the original text. The receiver can decrypt the encrypted digest only with the sender’s public key, and then use the HASH function to generate a digest of the received text and compare it with the decrypted digest.
  2. If yes, the received information is complete and has not been modified during transmission. Otherwise, the information has been modified. Therefore, the digital signature can verify the integrity of the information. If the data is corrupted or lost. The digital signature can then be used to identify whether it is from the other party’s first-hand information.
  3. Digital signature is a process of encryption, and digital signature verification is a process of decryption
  4. Digital signature is used to ensure the integrity of information transmission, the identity authentication of the sender, and prevent repudiation in transactions.
  5. The basic process of asymmetric encryption algorithm to realize confidential information exchange is as follows: Party A generates a pair of keys and discloses one of them to other parties as a public key; Party B who has obtained the public key encrypts the confidential information with the public key and then sends it to Party A. Party A then uses another special key saved by itself to decrypt the encrypted information.
  • What is a digital certificate
  1. Digital certificates: is a sign of Internet traffic communication the identity information of a string of Numbers, provides a validation communication entity identity on the Internet, a digital certificate is not a digital id card, but in the digital id authentication institutions cover a chapter or printed on (or add a signature on the digital id).
  2. It is issued by the Authority CA, also known as the Certificate Authority, and people can use it to identify each other online.
  3. Digital certificates bind the public key and its holder’s true identity, it is similar to the resident identity card in real life, the difference is a digital certificate is no longer a paper certificate, but a contain identity information and certificate holder through electronic data issued by the certification center audit, is widely used in e-commerce and mobile Internet.

3.1 Application of Digits in HTTPS

  • Hybrid application of symmetric and asymmetric encryption in browser signature certificate authentication
  1. The browser sends a request to the server for the symmetric and asymmetric encryption algorithms supported by the server. The server responds to the algorithm it supports.
  2. The browser selects an encryption algorithm supported by both parties and requests the server to show its certificate. The server responds with its own certificate.
  3. The browser randomly generates a symmetric encryption key for this session, encrypts the key using the public key attached to the server certificate and passes it to the server. The server holds the symmetric encryption key for this session. Third parties do not know the private key of the server and cannot decrypt the data even if it is intercepted. Asymmetric encryption allows any browser to have an encrypted session with the server.
  4. The browser encrypts the request message with the symmetric encryption key and sends it to the server. The server decrypts the request message with the symmetric encryption key. The server encrypts the response message using the symmetrically encrypted key and sends it to the browser, which decrypts it using the symmetrically encrypted key. Third parties do not know the key to symmetric encryption, and even if they intercept data, they cannot decrypt it. Symmetric encryption improves encryption speed.

3.1.1 SSL Process in HTTPS:

  1. In order to improve security, symmetric encryption is commonly used to encrypt data. With symmetric encryption alone, however, communication always begins with the key being transmitted in clear text. Then the key is compromised from the start. There is no security. Therefore, in the handshake phase, TLS/SSL combines asymmetric encryption to ensure that only the communication parties know the symmetric encryption key. The general process is as follows:

    CA certificate verification process:

  • SSL/TLS handshake process
  • Client Hello: The first step is that the Client sends a Client Hello message to the server. This message contains a random number Random1 generated by the Client, the encryption suite (Support Ciphers) supported by the Client and SSL Version information. The following information can be displayed after the Wireshark is used to capture packets:

  • Server Hello: The second step is that the Server sends a Server Hello message to the Client. This message will determine an encryption suite from the Support Ciphers sent by the Client Hello. This suite determines which algorithm to use in subsequent encryption and digest generation. A random number Random2 is also generated. Note that at this point both the client and the server have two random numbers (Random1+ Random2) that will be used in the subsequent generation of the symmetric secret key.

  • Certificate: In this step, the server sends its Certificate to the client for the client to verify its identity. After the authentication succeeds, the client obtains the public key in the Certificate.

  • Server Key Exchange: If the DH algorithm is used, the DH parameters used by the Server are sent. The RSA algorithm does not require this step.

  • Certificate Request: Indicates that the server requires the client to report the Certificate. This step is optional and is required in scenarios with high security requirements.

  • Server Hello Done: Server Hello Done notifies the client that the Hello process is complete.

  • Certificate Verify: after receiving the Certificate from the server, the client first verifies the validity of the Certificate from the CA. After passing the verification, it takes out the server public key in the Certificate and generates a random number Random3. Then use the server public Key asymmetric encryption Random3 to generate the PreMaster Key.

  • Client Key Exchange: The above Client generates the PreMaster Key according to the public Key from the server. The Client Key Exchange is to pass the Key to the server. The server then uses its own private Key to solve the PreMaster Key to get Random3 generated by the Client. At this point, both the client and the server have Random1 + Random2 + Random3, and both sides can use the same algorithm to generate a secret key. After the handshake, the application layer data is symmetrically encrypted using this secret key. Why use three random numbers? This is because the data in the SSL/TLS handshake is transmitted in clear text, and the multiple random number seeds used to generate the secret key are not easy to brute force cracking. The process of the client transferring the PreMaster Key to the server is shown as follows:

  • Change Cipher Spec(Client): This step indicates that the Client notifies the server that all subsequent messages are encrypted with the previously negotiated secret key, which is an event message:

  • Encrypted Handshake Message(Client): This step corresponds to the Client Finish Message. The Client generates a summary of the previous Handshake Message and encrypts it with the negotiated secret key. This is the first Encrypted Message sent by the Client. After receiving it, the server will decrypt it with the secret key. If the secret key can be solved, it indicates that the secret key negotiated before is consistent.

  • Change Cipher Spec(Server): Indicates that the Server notifies the client that subsequent messages are encrypted, which is also an event message.

  • Encrypted Handshake Message(Server): This step corresponds to the Server Finish Message. The Server also generates a summary of the Message generated during the Handshake process and encrypts it with the secret key. This is the first Encrypted Message sent by the Server. After receiving it, the client will decrypt it with the secret key. If the secret key can be solved, it indicates that the negotiated secret key is consistent.

  • Application Data: At this point, both parties have securely negotiated the same secret key. All application-layer Data will be encrypted with this secret key and then transmitted reliably through TCP.

3.1.2 Bidirectional authentication in HTTPS

  • Two-way verification flow chart:

4. Test symmetric encryption terminals

  • Terminal test instruction

  • DES encryption (ECB)

Terminal input command

 echo -n hello | openssl enc -des-ecb -K 616263 -nosalt | base64
Copy the code

The encrypted result is HQr0Oij2kbo=

  • DES encryption (CBC)

Terminal input command

echo -n hello | openssl enc -des-cbc -iv 0102030405060708 -K 616263 -nosalt | base64
Copy the code

Result after encryption: alvrvb3Gz88=

  • AES encryption (ECB)

Terminal input command

  echo -n hello | openssl enc -aes-128-ecb -K 616263 -nosalt | base64
Copy the code

Result after encryption

  • AES encryption (CBC)

Terminal input command

  echo -n hello | openssl enc -aes-128-cbc -iv 0102030405060708 -K 616263 -nosalt | base64
Copy the code

The result after encryption is as follows

  • DES (ECB)

Terminal input command

  echo -n HQr0Oij2kbo= | base64 -D | openssl enc -des-ecb -K 616263 -nosalt -d
Copy the code

Results after decryption:

  • DES (CBC)

Terminal input command

  echo -n alvrvb3Gz88= | base64 -D | openssl enc -des-cbc -iv 0102030405060708 -K 616263 -nosalt -d
Copy the code

Result after encryption:

  • AES (ECB)

Terminal input command

  echo -n d1QG4T2tivoi0Kiu3NEmZQ== | base64 -D | openssl enc -aes-128-ecb -K 616263 -nosalt -d
Copy the code

Result after encryption:

  • AES (CBC)

Terminal input command

 echo -n u3W/N816uzFpcg6pZ+kbdg== | base64 -D | openssl enc -aes-128-cbc -iv 0102030405060708 -K 616263 -nosalt -d
Copy the code

Result after encryption:

Symmetric encryption actual combat

5.1 Hash Encryption Code

  • This blog involves Demo code address: Hash encryption algorithm Demo

  • Create a new NSString extension class: NSString+Hash

Nsstrings + Hash. H file

//
// NSString+Hash.h
// 001-KEncryDemo
//
// Created by bobbin on 2019/12/14
// Copyright © 2019 Apple. All rights Reserved
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface NSString (HashPragma mark - Hash function/** * Compute MD5 hash results ** Terminal test command: * @code * MD5 -s "string" * @endcode ** 

Tip: With the advent of MD5 collision generators, MD5 algorithms should not be used for any software integrity checking or code signing purposes.

* * @return MD5 hash string of 32 characters */

- (NSString *)md5String; / * * * * * terminal test calculation result SHA1 hash commands: * @ code * echo -n "string" | openssl sha - SHA1 * @ endcode * * @ return 40 characters * / SHA1 hash strings - (NSString *)sha1String; /** * Calculate SHA256 hash result ** terminal test command: * @ code * echo -n "string" | openssl sha - sha256 * @ endcode * * @ return 64 characters * / sha256 hash strings - (NSString *)sha256String; /** * Calculate SHA 512 hash result ** terminal test command: * @ code * echo -n "string" | openssl sha - sha512 * @ endcode * * @ return 128 characters of sha * / 512 hash strings - (NSString *)sha512String; #pragma mark - HMACThe hash function/** * Calculate HMAC MD5 hash result ** Terminal test command: * @ code * echo -n "string" | openssl DGST - md5 - hmac "key" * @ endcode * * @ return 32 characters of hmac md5 hash string * / - (NSString *)hmacMD5StringWithKey:(NSString *)key; /** * Calculate HMAC SHA1 hash result ** Terminal test command: * @ code * echo -n "string" | openssl sha -- sha1 hmac "key" * @ endcode * * @ return 40 characters of hmac sha1 hash string * / - (NSString *)hmacSHA1StringWithKey:(NSString *)key; /** * Calculate HMAC SHA256 hash result ** Terminal test command: * @ code * echo -n "string" | openssl sha - sha256 hmac - "key" * @ endcode * * @ return 64 characters of hmac sha256 hash string * / - (NSString *)hmacSHA256StringWithKey:(NSString *)key; /** * Calculate HMAC SHA512 hash result ** Terminal test command: * @ code * echo -n "string" | openssl sha - sha512 hmac - "key" * @ endcode * * @ return 128 characters of hmac sha512 hash string * / - (NSString *)hmacSHA512StringWithKey:(NSString*)key; Pragma mark - File hash function/** * Calculate the MD5 hash result of the file ** Terminal test command: * @code * MD5 file.dat * @endcode ** @return 32 character MD5 hash string */ - (NSString *)fileMD5Hash; Openssl sha-sha1 file.dat * @endCode ** @return SHA1 hash string of 40 characters */ - (NSString *)fileSHA1Hash; Openssl sha-sha256 file.dat * @endcode ** @return 64 character SHA256 hash string */ - (NSString *)fileSHA256Hash; Openssl sha-sha512 file.dat * @endcode ** @return 128-character SHA512 hash string */ - (NSString *)fileSHA512Hash; @end NS_ASSUME_NONNULL_END Copy the code

Nsstrings + Hash. M file

//
// NSString+Hash.m
// 001-KEncryDemo
//
// Created by bobbin on 2019/12/14
// Copyright © 2019 Apple. All rights Reserved
//

#import "NSString+Hash.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (Hash) #pragma mark - Hash function - (NSString *)md5String {
    const char *str = self.UTF8String;
    uint8_t buffer[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(str, (CC_LONG)strlen(str), buffer);
    
    return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH];
}
    
- (NSString *)sha1String {
    const char *str = self.UTF8String;
    uint8_t buffer[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(str, (CC_LONG)strlen(str), buffer);
    
    return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH];
}
    
- (NSString *)sha256String {
    const char *str = self.UTF8String;
    uint8_t buffer[CC_SHA256_DIGEST_LENGTH];
    
    CC_SHA256(str, (CC_LONG)strlen(str), buffer);
    
    return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH];
}
    
- (NSString *)sha512String {
    const char *str = self.UTF8String;
    uint8_t buffer[CC_SHA512_DIGEST_LENGTH];
    
    CC_SHA512(str, (CC_LONG)strlen(str), buffer);
    
    return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH];
}
    
#pragma mark - HMACHash function - (NSString *)hmacMD5StringWithKey:(NSString *)key {
    const char *keyData = key.UTF8String;
    const char *strData = self.UTF8String;
    uint8_t buffer[CC_MD5_DIGEST_LENGTH];
    
    CCHmac(kCCHmacAlgMD5, keyData, strlen(keyData), strData, strlen(strData), buffer);
    
    return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH];
}
    
- (NSString *)hmacSHA1StringWithKey:(NSString *)key {
    const char *keyData = key.UTF8String;
    const char *strData = self.UTF8String;
    uint8_t buffer[CC_SHA1_DIGEST_LENGTH];
    
    CCHmac(kCCHmacAlgSHA1, keyData, strlen(keyData), strData, strlen(strData), buffer);
    
    return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH];
}
    
- (NSString *)hmacSHA256StringWithKey:(NSString *)key {
    const char *keyData = key.UTF8String;
    const char *strData = self.UTF8String;
    uint8_t buffer[CC_SHA256_DIGEST_LENGTH];
    
    CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer);
    
    return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH];
}
    
- (NSString *)hmacSHA512StringWithKey:(NSString *)key {
    const char *keyData = key.UTF8String;
    const char *strData = self.UTF8String;
    uint8_t buffer[CC_SHA512_DIGEST_LENGTH];
    
    CCHmac(kCCHmacAlgSHA512, keyData, strlen(keyData), strData, strlen(strData), buffer);
    
    return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - file hash function #defineFileHashDefaultChunkSizeForReadingData 4096
    
- (NSString *)fileMD5Hash {
    NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];
    if (fp == nil) {
        return nil;
    }
    
    CC_MD5_CTX hashCtx;
    CC_MD5_Init(&hashCtx);
    
    while (YES) {
        @autoreleasepool {
            NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];
            
            CC_MD5_Update(&hashCtx, data.bytes, (CC_LONG)data.length);
            
            if (data.length == 0) {
                break;
            }
        }
    }
    [fp closeFile];
    
    uint8_t buffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5_Final(buffer, &hashCtx);
    
    return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH];
}
    
- (NSString *)fileSHA1Hash {
    NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];
    if (fp == nil) {
        return nil;
    }
    
    CC_SHA1_CTX hashCtx;
    CC_SHA1_Init(&hashCtx);
    
    while (YES) {
        @autoreleasepool {
            NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];
            
            CC_SHA1_Update(&hashCtx, data.bytes, (CC_LONG)data.length);
            
            if (data.length == 0) {
                break;
            }
        }
    }
    [fp closeFile];
    
    uint8_t buffer[CC_SHA1_DIGEST_LENGTH];
    CC_SHA1_Final(buffer, &hashCtx);
    
    return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH];
}
    
- (NSString *)fileSHA256Hash {
    NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];
    if (fp == nil) {
        return nil;
    }
    
    CC_SHA256_CTX hashCtx;
    CC_SHA256_Init(&hashCtx);
    
    while (YES) {
        @autoreleasepool {
            NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];
            
            CC_SHA256_Update(&hashCtx, data.bytes, (CC_LONG)data.length);
            
            if (data.length == 0) {
                break;
            }
        }
    }
    [fp closeFile];
    
    uint8_t buffer[CC_SHA256_DIGEST_LENGTH];
    CC_SHA256_Final(buffer, &hashCtx);
    
    return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH];
}
    
- (NSString *)fileSHA512Hash {
    NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self];
    if (fp == nil) {
        return nil;
    }
    
    CC_SHA512_CTX hashCtx;
    CC_SHA512_Init(&hashCtx);
    
    while (YES) {
        @autoreleasepool {
            NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData];
            
            CC_SHA512_Update(&hashCtx, data.bytes, (CC_LONG)data.length);
            
            if (data.length == 0) {
                break;
            }
        }
    }
    [fp closeFile];
    
    uint8_t buffer[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512_Final(buffer, &hashCtx);
    
    return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - helper method/** * returns a string representation of the binary Bytes stream ** @param Bytes Binary Bytes array * @param Length Array length ** @return String representation */
- (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length {
    NSMutableString *strM = [NSMutableString string];
    
    for (int i = 0; i < length; i++) {
        [strM appendFormat:@"%02x", bytes[I]];
    }
    
    return [strM copy];
}

@end

Copy the code
  • Create a new encryption tool class:

    KEncryptionTool. H file:

//
// KEncryptionTool.h
// 001-KylAppEncrypt
//
// Created by bobbin on 2019/12/14
// Copyright © 2019 Apple. All rights Reserved
//
/ * * * * * DES terminal test instructions (ECB) encryption * $echo -n hello | openssl enc - DES - the ECB - 616263 - K nosalt | base64 encryption (CBC) * * * DES $echo - n hello | openssl enc - des - 616263-0102030405060708 - K CBC to iv nosalt | base64 AES encryption (ECB) * * * $echo -n hello | Openssl enc - aes - 128 - the ECB - 616263 - K nosalt | base64 aes encryption (CBC) * * * $echo -n hello | openssl enc - aes - 128 - CBC - iv 616263-0102030405060708 - K nosalt | base64 (ECB) decryption * $* * DES echo -n HQr0Oij2kbo = | | base64 - D openssl enc - DES - the ECB - 616263 - K nosalt (CBC) - d * * DES declassified * $echo -n alvrvb3Gz88 = | | base64 - d openssl enc - DES - CBC - 0102030405060708 - K iv 616263 - nosalt - d * * AES (ECB) decryption * $echo -n d1QG4T2tivoi0Kiu3NEmZQ = = | | base64 - d openssl enc - AES - 128 - the ECB - 616263 K - nosalt - d * * AES (CBC) decryption * $echo -n u3W/N816uzFpcg6pZ + KBDG = = | base64 - d | openssl enc - AES - 128 - CBC - iv 0102030405060708 -k 616263 -nosalt -d * * tip: * 1> Encryption is first encrypted, then base64 encoding * 2> decryption is first base64 decoding, then decryption */


#import <Foundation/Foundation.h>


NS_ASSUME_NONNULL_BEGIN

@interface KEncryptionTool : NSObject

    + (instancetype)shared;
    
    /** @constant kCCAlgorithmAES Advanced Encryption standard, 128 bits (default) @constant kCCAlgorithmDES Data encryption standard */
    @property (nonatomic, assign) uint32_t algorithm;
    
    /** * encrypt string and return Base64 encoded string ** @param String String to be encrypted * @param keyString Encryption key * @param IV initialization vector (8 bytes) ** @return Returns the encrypted Base64 encoded string */

- (NSString *)encryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv;
    
    /** * decrypted string ** @param String Encrypted and Base64 encoded string * @param keyString Decryption key * @param IV initialization vector (8 bytes) ** @return Returns the decrypted string */
- (NSString *)decryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv;
@end

NS_ASSUME_NONNULL_END

Copy the code

KEncryptionTool. M file:

//
// KEncryptionTool.m
// 001-KylAppEncrypt
//
// Created by bobbin on 2019/12/14
// Copyright © 2019 Apple. All rights Reserved
//



#import "KEncryptionTool.h"
#import <CommonCrypto/CommonCrypto.h>
@interface KEncryptionTool()
@property (nonatomic, assign) int keySize;
@property (nonatomic, assign) int blockSize;

@end


@implementation KEncryptionTool
+ (instancetype)shared {
    static KEncryptionTool *instance;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
        instance.algorithm = kCCAlgorithmAES;
    });
    
    return instance;
}
    
- (void)setAlgorithm:(uint32_t)algorithm {
    _algorithm = algorithm;
    switch (algorithm) {
        case kCCAlgorithmAES:
        self.keySize = kCCKeySizeAES128;
        self.blockSize = kCCBlockSizeAES128;
        break;
        case kCCAlgorithmDES:
        self.keySize = kCCKeySizeDES;
        self.blockSize = kCCBlockSizeDES;
        break;
        default:
        break; }} - (NSString *)encryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv {
    
    // Set the secret key
    NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t cKey[self.keySize];
    bzero(cKey, sizeof(cKey));
    [keyData getBytes:cKey length:self.keySize];
    
    / / set the iv
    uint8_t cIv[self.blockSize];
    bzero(cIv, self.blockSize);
    int option = 0;
    if (iv) {
        [iv getBytes:cIv length:self.blockSize];
        option = kCCOptionPKCS7Padding;
    } else {
        option = kCCOptionPKCS7Padding | kCCOptionECBMode;
    }
    
    // Set the output buffer
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    size_t bufferSize = [data length] + self.blockSize;
    void *buffer = malloc(bufferSize);
    
    // Start encryption
    size_t encryptedSize = 0;
    // encryption and decryption is it -- CCCrypt
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          self.algorithm,
                                          option,
                                          cKey,
                                          self.keySize,
                                          cIv,
                                          [data bytes],
                                          [data length],
                                          buffer,
                                          bufferSize,
                                          &encryptedSize);
    
    NSData *result = nil;
    if (cryptStatus == kCCSuccess) {
        result = [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
    } else {
        free(buffer);
        NSLog(@"[error] encryption failure | status code: % d", cryptStatus);
    }
    
    return [result base64EncodedStringWithOptions:0];
}
    
- (NSString *)decryptString:(NSString *)string keyString:(NSString *)keyString iv:(NSData *)iv {
    
    // Set the secret key
    NSData *keyData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t cKey[self.keySize];
    bzero(cKey, sizeof(cKey));
    [keyData getBytes:cKey length:self.keySize];
    
    / / set the iv
    uint8_t cIv[self.blockSize];
    bzero(cIv, self.blockSize);
    int option = 0;
    if (iv) {
        [iv getBytes:cIv length:self.blockSize];
        option = kCCOptionPKCS7Padding;/ / CBC encryption!
    } else {
        option = kCCOptionPKCS7Padding | kCCOptionECBMode;/ / the ECB encryption!
    }
    
    // Set the output buffer
    NSData *data = [[NSData alloc] initWithBase64EncodedString:string options:0];
    size_t bufferSize = [data length] + self.blockSize;
    void *buffer = malloc(bufferSize);
    
    // Start decrypting
    size_t decryptedSize = 0;
    /**CCCrypt symmetric encryption algorithm of the core function (encryption/decryption) parameters: 1, 2, kCCEncrypt encryption, decryption/kCCDecrypt encryption algorithm, the default / 3 DES, AES encryption mode options kCCOptionPKCS7Padding | kCCOptionECBMode; / / the ECB encryption! kCCOptionPKCS7Padding; / / CBC encryption! 4, encrypt key 5, key length 6, iv initialize vector, ECB does not need to specify 7, encrypt data 8, encrypt data length 9, buffer (address), store ciphertext 10, buffer size 11, encrypt result size */
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          self.algorithm,
                                          option,
                                          cKey,
                                          self.keySize,
                                          cIv,
                                          [data bytes],
                                          [data length],
                                          buffer,
                                          bufferSize,
                                          &decryptedSize);
    
    NSData *result = nil;
    if (cryptStatus == kCCSuccess) {
        result = [NSData dataWithBytesNoCopy:buffer length:decryptedSize];
    } else {
        free(buffer);
        NSLog(@"[error] decryption failure | status code: % d", cryptStatus);
    }
    
    return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
}
    
@end

Copy the code
  • Test code:
- (void) testEncrpytion {
    /** AES - ECB */
    NSString * key = @"abc";
    NSString * encStr = [[KEncryptionTool shared] encryptString:@"hello" keyString:key iv:nil];
    
    NSLog(@"Result of encryption: %@",encStr);
    
    NSLog(@"Decrypted result: %@"The [[KEncryptionTool shared] decryptString:encStr keyString:key iv:nil]);
    
    /** AES-cbc encryption */
    uint8_t iv[8] = {1.2.3.4.5.6.7.8};
    NSData * ivData = [NSData dataWithBytes:iv length:sizeof(iv)];
    
    
    
    NSLog(@"CBC Encryption: %@"The [[KEncryptionTool shared] encryptString:@"hello" keyString:@"abc" iv:ivData]);
    
    NSLog(@"Decrypt: %@"The [[KEncryptionTool shared] decryptString:@"u3W/N816uzFpcg6pZ+kbdg==" keyString:key iv:ivData]);
}
Copy the code
  • Test results:

Reference: www.jianshu.com/p/a3624d4e2…