Created
August 7, 2022 01:57
-
-
Save quackduck/0da5d2ed7807e3ef22dc2e0cdadbf90a to your computer and use it in GitHub Desktop.
Stupid hash function made on a plane without WiFi
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// go build | |
// ./main "random string" | |
// 2f4563a971944e00 | |
package main | |
import ( | |
"fmt" | |
"os" | |
) | |
func main() { | |
fmt.Println(hexprint(hash([]byte(os.Args[1])))) | |
} | |
func hexprint(a uint64) string { | |
return fmt.Sprintf("%016x", a) | |
} | |
func hash(input []byte) uint64 { | |
pad := Padding(input, 64) | |
msgblocks := Split(pad, 8) | |
nums := make([]uint64, 0) | |
for _, blk := range msgblocks { | |
num := uint64(0) | |
multip := uint64(1) | |
for _, b := range blk { | |
num += uint64(b) * multip | |
multip *= 1 << 8 | |
} | |
nums = append(nums, num) | |
} | |
result := uint64(0) | |
for i := uint64(0); i < 63; i++ { | |
for _, num := range nums { | |
result ^= Rotr(num, i) * Rotr(num, i) * num * num * 0x428a2f98 // overflow is essentially mod 2^64 | |
} | |
} | |
return result | |
} | |
func Padding(input []byte, length int) []byte { | |
mod := len(input) % length | |
padcount := length - mod | |
if mod > length-8 { | |
padcount += 64 | |
} | |
for i := 0; i < padcount; i++ { | |
input = append(input, 0x0) | |
} | |
return input | |
} | |
func Split(input []byte, length int) [][]byte { | |
var barr [][]byte | |
n := len(input) / length | |
for i := 0; i < n; i++ { | |
barr = append(barr, input[i*length:(i+1)*length]) | |
} | |
return barr | |
} | |
func Rotr(x, n uint64) uint64 { | |
return x<<(64-n) | x>>n | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment