Golang Examples
Hash Function Implementation Patterns
1. Basic SHA-256 Hash Generation
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
)
func generateHash(data string) string {
hash := sha256.Sum256([]byte(data))
return hex.EncodeToString(hash[:])
}
func main() {
input := "LabEx Tutorial"
hashResult := generateHash(input)
fmt.Println("Hash:", hashResult)
}
Hash Comparison Techniques
2. Secure Hash Comparison
func secureCompare(hash1, hash2 []byte) bool {
return subtle.ConstantTimeCompare(hash1, hash2) == 1
}
Multiple Encoding Strategies
func hashMultiFormat(data string) map[string]string {
hash := sha256.Sum256([]byte(data))
return map[string]string{
"hex": hex.EncodeToString(hash[:]),
"base64": base64.StdEncoding.EncodeToString(hash[:]),
}
}
Hash Processing Workflow
graph TD
A[Input Data] --> B[Hash Generation]
B --> C{Encoding Method}
C --> |Hex| D[Hexadecimal Output]
C --> |Base64| E[Base64 Output]
C --> |Binary| F[Binary Output]
Hash Method |
Speed |
Memory Usage |
Security Level |
MD5 |
Fast |
Low |
Low |
SHA-256 |
Moderate |
Medium |
High |
SHA-3 |
Slower |
High |
Very High |
Advanced Hash Handling
4. File Hash Verification
func calculateFileHash(filepath string) (string, error) {
file, err := os.Open(filepath)
if err != nil {
return "", err
}
defer file.Close()
hash := sha256.New()
if _, err := io.Copy(hash, file); err != nil {
return "", err
}
return hex.EncodeToString(hash.Sum(nil)), nil
}
Error Handling and Best Practices
- Always validate input before hashing
- Use cryptographically secure hash functions
- Implement constant-time comparison
- Choose appropriate encoding based on requirements