Fundamental difference between Hashing and Encryption algorithms

前端 未结 13 2050
日久生厌
日久生厌 2020-11-21 06:35

I see a lot of confusion between hashes and encryption algorithms and I would like to hear some more expert advice about:

  1. When to use hashes vs encryptions<

13条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 07:05

    Use hashes when you don't want to be able to get back the original input, use encryption when you do.

    Hashes take some input and turn it into some bits (usually thought of as a number, like a 32 bit integer, 64 bit integer, etc). The same input will always produce the same hash, but you PRINCIPALLY lose information in the process so you can't reliably reproduce the original input (there are a few caveats to that however).

    Encryption principally preserves all of the information you put into the encryption function, just makes it hard (ideally impossible) for anyone to reverse back to the original input without possessing a specific key.

    Simple Example of Hashing

    Here's a trivial example to help you understand why hashing can't (in the general case) get back the original input. Say I'm creating a 1-bit hash. My hash function takes a bit string as input and sets the hash to 1 if there are an even number of bits set in the input string, else 0 if there were an odd number.

    Example:

    Input    Hash
    0010     0
    0011     1
    0110     1
    1000     0
    

    Note that there are many input values that result in a hash of 0, and many that result in a hash of 1. If you know the hash is 0, you can't know for sure what the original input was.

    By the way, this 1-bit hash isn't exactly contrived... have a look at parity bit.

    Simple Example of Encryption

    You might encrypt text by using a simple letter substitution, say if the input is A, you write B. If the input is B, you write C. All the way to the end of the alphabet, where if the input is Z, you write A again.

    Input   Encrypted
    CAT     DBU
    ZOO     APP
    

    Just like the simple hash example, this type of encryption has been used historically.

提交回复
热议问题