Function Char2Hash() Foundation

Convert a character string to a hash value

Syntax
Char2Hash( <cString> [, <nBitLen>] ) --> cHash
Parameters
<cString>
<cString> is a character string for which the hash value is calculated
<nBitLen>
The optional parameter <nBitLen> specifies the length of the resulting hash value in number of bits and also implies the algorithm to be used to calculate the hash value. <nBitLen> defaults to the cryptographic hash algorithm specified using the SET HASH command. The default hash algorithm used by the Xbase++ runtime is SHA1.
Return

The hash value of the parameter <cString>. cHash is a character string representing a hexadecimal number.

Description

The Char2Hash() function implements a cryptographic hash function. A cryptographic hash function is a special class of hash function which makes it suitable for use in cryptography. It is an algorithm that maps data of arbitrary size to a bit string of a fixed size (the hash value), and is designed to be a one-way function. The only way to recreate the input data from a cryptographic hash function's output is to attempt a brute-force search of possible inputs to see if they produce a match.

Hash algorithms are designed to have a low collision rate. This means that two similar input parameters produce two completely different results:

Char2Hash( "Xbase++" ) == "A1F3898DAAA63E865A1BBA863A41958B46FB73C0" 
Char2Hash( "XBase++" ) == "7BA498BD8584E8D53D314040127043BCA764FFE7" 

Depending on the optional parameter <nBitLen>, Char2Hash() selects a hash algorithm according to the following table. The length of the return value cHash depends on the selected algorithm.

Algorithm nBitLen Length of cHash
MD5 128 32
SHA1 160 40
SHA2-256 256 64
SHA3-512 512 128

Note that the bit length of the resulting hash value implicitly indicates the level of security. A greater bit length implies a higher effort required in a brute-force attack.

Examples
Char2Hash()
// This example asks for a password and compares its hash 
// with the hash of the expected password. 

PROCEDURE Main() 
  LOCAL cSecret, cHash 

  // Ask for the password 
  cSecret := Space( 10 ) 
  @ 1, 1 SAY "Enter secret:" GET cSecret 
  READ 

  // Compare password with the hash of "Xbase++" 
  cHash := "A1F3898DAAA63E865A1BBA863A41958B46FB73C0" 
  IF Char2Hash( AllTrim(cSecret) ) == cHash 
     @ 2, 1 SAY "Welcome, you are a member of the club!" 
  ELSE 
     @ 2, 1 SAY "Sorry, you are not a club member!" 
  ENDIF 

  WAIT 
RETURN 
Feedback

If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.