-
-
Save msdundar/f88aee1a89d603b3d81f9087e3dc1012 to your computer and use it in GitHub Desktop.
A primitive hashing function in Go
This file contains 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
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func main(){ | |
binaryStringSlc := splitToBlocks( | |
stringToBinary("Hello world! This is Serhat! This post is all about implementing a primitive hashing function in Go"), | |
) | |
for i := 0; i < len(binaryStringSlc); i++{ | |
if !(i+1 == len(binaryStringSlc)) { | |
comparisonStr := xorMachine(binaryStringSlc[i], binaryStringSlc[i+1]) | |
binaryStringSlc[i+1] = comparisonStr | |
} | |
} | |
fmt.Println(binaryStringSlc[len(binaryStringSlc)-1]) | |
} | |
// stringToBinary converts strings to binary | |
func stringToBinary(s string) (binaryString string) { | |
for _, c := range s { | |
binaryString = fmt.Sprintf("%s%.8b", binaryString, c) | |
} | |
return | |
} | |
// splitToBlocks takes a binary string and splits it into blocks | |
func splitToBlocks(msg string) []string{ | |
desiredBlockSize := 128 | |
numberOfBits := len(msg) | |
requiredSliceCap := int(math.Ceil( | |
float64(numberOfBits)/float64(desiredBlockSize)), | |
) | |
fourByteSlice := make([]string, requiredSliceCap) | |
byteIndex := 0 | |
for i := 0; i < len(msg); i++ { | |
if i != 0 && i % desiredBlockSize == 0 { | |
byteIndex += 1 | |
} | |
fourByteSlice[byteIndex] = fourByteSlice[byteIndex] + string(msg[i]) | |
} | |
// Pad with 0s to ensure all blocks are the same size | |
for ; len(fourByteSlice[byteIndex]) < desiredBlockSize; { | |
fourByteSlice[byteIndex] = fourByteSlice[byteIndex] + "0" | |
} | |
return fourByteSlice | |
} | |
// xorMachine runs longitudinal parity checks on given blocks | |
func xorMachine(item1 string, item2 string) string{ | |
var xorOutput string | |
for i, _ := range item1 { | |
if item1[i] == item2[i] { | |
xorOutput += "0" | |
} else { | |
xorOutput += "1" | |
} | |
} | |
return xorOutput | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment