preface

This article will continue to explain another cryptographic algorithm 👉 HASH algorithm.

I. Encryption policy

Before we look at HASH, let’s look at the encryption strategy. As we all know, there is a principle for network transmission data (private data) and local storage data (private data) 👉 can not be plaintext, must be encrypted data. The most common is the user’s account password. For user passwords, we can use the following policy 👇

  1. RSA

Rsa encryption is relatively secure because it is less likely to leak data. However, the server database stores users’ real passwords (plaintext passwords). If the database is leaked, all user passwords will be leaked. It should be a rule of thumb that the 👉 server should not store the user’s password in plain text, preferably if the developer does not know it. This is a good time to use hash.

  1. HASH

The problem with HASH 👉 is that since the HASH value is the same, the plaintext can be found by saving the HASH value. If you save enough HASH values for common passwords, you can find plaintext by comparison (mapping).

For example, there is a website, CMd5, that can be queried directly at 👇

This is brute force cracking, just look up the table and get the plaintext. And the site supports a lot of methods and data, so direct hash display is still not secure.

  1. HASH+salt
static NSString *kSaltKey = @"LGPerson";
NSString *pwd = @"123456";
pwd = [pwd stringByAppendingString:kSaltKey].md5String;
NSLog(@"%@",pwd);
Copy the code

By adding salt, the server directly saves the salted password hash value in the database during registration. This approach is too dependent on the developer, the developer knows about the salt and can still restore it if it’s leaked.

  1. hmac
NSString *pwd = @"123456";
pwd = [pwd hmacMD5StringWithKey:@"LGPerson"];
NSLog(@"%@",pwd);
Copy the code

What’s the difference between a key and a salt? Essentially no difference (HMAC md5 twice), this key is provided by the server 👉 one key for each account. Current flow 👇

  1. When you register, the client sends a request to the server,The service sidejudgeDoes the account exist.There is nowhenThe service sideTo generate aThe key is bound to the accountAt the same time.
  2. The server willkeyTo the client, the client willPassword and keythroughHmac calculationgetHash valueReturn to the server. The service sidesavethisHash value.
  3. Take this when the client logs inKey (local, usually stored in the keychain)andpasswordTo calculate theHash valueTo log in.

The whole process is shown below 👇

At this point, there are problems to 👉 if the user changed the phone (no key) how to deal with it? After changing the mobile phone, first request the key (RSA encryption) from the server, which generally involves authorization (SMS, face, etc.). Without the key, it is not authentication that the mobile phone does not allow login. A request for a key requires authorization (to ensure that the user is the account owner).

  1. Hmac + timestamp

Although hMAC generally cannot get the plaintext password, it can still get the hamC (password +key) value. What if you use this hash value directly to interact with the server? Is there a risk? So what do we do here? At this point, we can use hash + timestamp to solve 👇

Hmac + timestampwithhmacThe difference between
  • Encryption logicNo change, butThere's an extra time stamp
  • The service sideThe validation logicchanged

Current flow 👇

  1. The client willHash value and timestampMd5 and sent to the server.
  2. The service sidetakeLocal timeAnd in the databaseThe stored hash valueagainDo the hash operation, andThe clientThe value of sendingDo than.
  3. ifValidation failsIs to takeOne minuteVerify again. Here are the1 minuteThe fault tolerance. Hash valueEffective timefor1 minutes and 59 seconds(Time can be customized).

In this case, the hash value is bound to the time, which is relatively secure. The result of each encryption is affected by the time.

Second, the HASH

2.1 an overview of the

A Hash algorithm 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, 👉 is a function that compresses a message of any length into a fixed length message digest (fingerprint).

Common HASH algorithms are 👇

  1. MD5
  2. SHA1, 256, 512

2.2 the characteristics of

  • Algorithm ispublicthe
  • That’s the same dataThe result is the samethe
  • Different data operations, such as MD5The results ofThe defaultIs a 128 - bit.32 characters (hexadecimal identifier).
  • You can’t invert it. (so,Unable to encrypt)
  • Information digest, information fingerprint, used to doData to identify.
Why can’t you invert it?

For example, the result of MD5 operation on the data is 128 bits, that is, 1632 kinds of data can be expressed (limited), so the data (infinite). There must be multiple pieces of data with the same hash value.

2.3 use

  • Encryption of the user’s password, as described above
  • Search engines like:iOS Swift å’Œ Swift iOSThe search results may be the same. This word ishashValue will be multiple wordshashThe values get added up.
  • Copyright Any file will generate onehashValue. After uploading to the platform, the platform saves the original filehashValue. Files downloaded by others are not the original files (platform generated). At this point the platform can pass the original filehashTo distinguish and determine copyright issues.
  • Web disk data identification –hash
  • A digital signature

A digital signature

Let’s focus on digital signatures. Because foreign countries like to use check, the signature on the check can prove the identity. A digital signature, as its name suggests, is a method used to authenticate digital information, confirming that the binary was issued by the original agency.

  1. rightBinary dataTo calculateHash value.
  2. On the issuing partyHash valueforRsa encryption.
  3. The receiving partyDecrypt to obtain the hash value, and theBinary fileTo calculateHash value.The same hash valueIs proved to beThe originalFile.

The rsa encrypted hash value is called the digital signature of the binary file.

2.4 Terminal Demonstration

Against 2.4.1 HASH

md5
// String md5-s "LGPerson" // file md5 message.txtCopy the code

The figure above returns a 32-character MD5 hash string.

sha1
/ / string echo -n "LGPerson" | openssl sha1 / / file openssl sha1 message. TXTCopy the code

The figure above returns a SHA1 hash string of 40 characters.

sha256
/ / string echo -n "LGPerson" | openssl sha256 / / file openssl sha256 message. TXTCopy the code

The SHA256 hash string is 64 characters long.

sha512
/ / string echo -n "LGPerson" | openssl sha512 / / file openssl sha512 message. TXTCopy the code

The SHA512 hash string is 128 characters long.

HMAC 2.4.2

hmac md5

echo -n “LGPerson” | openssl dgst -md5 -hmac “key”

Returns a 32-character HMAC MD5 hash string.

hmac sha1

echo -n “LGPerson” | openssl sha1 -hmac “key”

Returns a 40-character HMAC SHA1 hash string.

hmac sha256

echo -n “LGPerson” | openssl sha256 -hmac “key”

Returns a 64 character HMAC SHA256 hash string.

hmac sha512

echo -n “LGPerson” | openssl sha512 -hmac “key”

Returns a 128-character HMAC SHA256 hash string.

The reader can verify for himself, and will not demonstrate here.

2.5 Code Demo

The iOS HASH encryption and decryption framework is CommonCrypto.

//string NSString *message = @"LGPerson"; NSString *key = @"key"; NSLog(@"string md5: %@",[message md5String]); NSLog(@"string sha1: %@",[message sha1String]); NSLog(@"string sha256: %@",[message sha256String]); NSLog(@"string sha512: %@",[message sha512String]); NSLog(@"string hmac md5: %@",[message hmacMD5StringWithKey:key]); NSLog(@"string hmac sha1: %@",[message hmacSHA1StringWithKey:key]); NSLog(@"string hmac sha256: %@",[message hmacSHA256StringWithKey:key]); NSLog(@"string hmac sha512: %@",[message hmacSHA512StringWithKey:key]); NSString *filePath = [[NSBundle mainBundle] pathForResource:@"message" ofType:@" TXT "]; NSLog(@"file md5: %@",[filePath fileMD5Hash]); NSLog(@"file sha1: %@",[filePath fileSHA1Hash]); NSLog(@"file sha256: %@",[filePath fileSHA256Hash]); NSLog(@"file sha512: %@",[filePath fileSHA512Hash]);Copy the code

Run 👇

The sample code

XFCryptor NSString+Hash classification.

conclusion

  • Encryption strategies

    • RSA👉 low probability of leakage, butDevelopers knowPassword,The databaseThere areLet the cat out of themay
    • HASH👉 may beBrute force(look up table)
    • HASH+salt👉 Salt may leak (here forFixed salt)
    • HMAC👉 is a better solution, the problem is that the encrypted data mayintercepted
    • HASH + timestamp👉 guarantees each encryption resultBy the timeInfluence, relativeTo compare safety
  • HASH

    • Features:
      • Algorithm in public
      • Irreversible operation (many-to-one)
      • The same data encryption results are the same
      • Data encryption of different lengths results in fixed length
      • Generally used for data identification (password, copyright, web disk)
    • USES:
      • Password encryption, seeEncryption strategies
      • Search engine
      • copyright
      • The cloud
      • A digital signature
        • Algorithm:HASH+RSA
        • Purpose: Verify that data integrity is not tampered with
        • Logic:
          1. The raw data is hashed
          2. Using RSA secret HASH values (this part of the data is the digital signature of the original data)
          3. Send and transfer raw data with digital signature (client decrypts and authenticates using public key)