Why is this hash, created from a permanent list, "in a different order" every time the program starts?

Below is a small script in Perl. Every time I run this code, I get a different result.

Can someone help me understand the basics of storing hash variables, i.e. how indexing is done for Perl hash variable key value pairs.

#!/usr/bin/perl %data = ('John Paul' => 45, 'Lisa' => 30, 'Kumar' => 40); @names = keys %data; print "$names[0]\n"; print "$names[1]\n"; print "$names[2]\n"; 
+5
source share
2 answers

The behavior is documented in perlsec Algorithmic attacks of complexity .


A hash is an array of linked lists. The hash function converts the key into a number, which is used as the index of the array element ("bucket") into which the value will be stored. More than one key can hash to the same index (โ€œcollisionโ€), a situation with which linked lists are associated.

If the attacker knew the hashing algorithm, he could develop values โ€‹โ€‹that will hash with the same index, as a result of which the hash will degenerate in the linked list. This can lead to a huge performance hit in some applications and, therefore, can be used as part of a DoS (denial of service) attack.

Two measures are being taken to avoid this. One of them is to combine the hashing algorithm with randomization of the order in which the elements are stored, and the other complicates the detection of salt, disrupting the order in which the iterator visits the hash elements.

 $ perl -E' my @k = "a".."z"; for (1..3) { my %h = map { $_ => 1 } @k; say keys %h; } ' iocmbygdkranwxfejuqpzvltsh bmcoigdywrankujfxezpqlvths juexfwarnkgdybmcoihstlvzpq 
+11
source

This behavior is described in perldoc -f keys

Hash entries are returned in a random order. Actual random order is specific to this hash; the exact same series of operations on two hashes can lead to a different order for each hash. Any insertion in the hash can change the order, just like any deletion, except that the last key returned by each or the keys can be deleted without changing the order. As long as this hash is not changed, you can rely on keys, values, and each to repeatedly return the same order to each other.

.. to prevent Algorithmic Complexity Attacks

+3
source

Source: https://habr.com/ru/post/1213642/


All Articles