2

I have been tasked with getting a string to encrypted to a certain length. Ideally....the function should take as parameters...

  1. String to be encrypted of variable size
  2. the length of the resulting encrypted string

It does not need to be decrypted. I've been looking at SHA384, but I've been unable to understand the samples online to the point of modifying it to make it hash to a specified length.

1615903
  • 32,635
  • 12
  • 70
  • 99
TheFootClan
  • 165
  • 1
  • 3
  • 12
  • SHA always output a hash of a fixed length. If you want it longer, append random bytes to it and remove them if you need to compare. – Alex K. Jul 20 '17 at 17:30
  • How would you actually make it less. The hashed string always comes out much longer than a requested length. – TheFootClan Jul 20 '17 at 17:50
  • 1
    Building on what @AlexK. said, hashes generally have fixed-length output, so you can't just pick a different length. However, you could do something similar to what git does, where you store the the entire hash but only display the first seven characters, or a different number based on your needs. Source: https://stackoverflow.com/questions/18134627/how-much-of-a-git-sha-is-generally-considered-necessary-to-uniquely-identify-a – Andrew Zick Jul 20 '17 at 17:53

3 Answers3

3

You can't request the length, that is part of the method.

If you want a shorter output just remove the extra bytes, each byte (and bit) is individually random, it makes no difference which bytes are removed.


Hashing is not encryption, it is a one-way non-reversavble function that takes a variable amount of input and generates a fixed amount of output.

Do you need encryption of a hash?

Duc Filan
  • 6,769
  • 3
  • 21
  • 26
zaph
  • 111,848
  • 21
  • 189
  • 228
2

You do not say if you want a cryptographically secure hash or not. The cryptographic hashes: SHA-1, SHA-2, SHA-3 and others come with a fixed range of output sizes, usually relatively limited.

Non-cryptographic hashes usually have a wider range of sizes available. For a non-crypto hash I often suggest the FNV hash, which is easy to implement and offers a wide range of output sizes: 32 bits to 1024 bits.

rossum
  • 15,344
  • 1
  • 24
  • 38
  • Saying cryptographic hashes have limited set of output sizes is misleading. The SHA-3 algorithm (Keccak) has a closely related cousin SHAKE which is an extensible output, allowing you to select an arbitrary size. – Thomas M. DuBuisson Jul 23 '17 at 20:00
  • I said "usually relatively limited". As you point out, there are some exceptions. – rossum Jul 26 '17 at 16:56
0

A hash is a one way function meaning it cannot be reversed. If you want to generate a license key (for example), you can simply substring the hashed string.

Patrick
  • 165
  • 2
  • 2
  • 8