github.com/status-im/status-go@v1.1.0/protocol/identity/identicon/identicon.go (about) 1 package identicon 2 3 import ( 4 "crypto/md5" // nolint: gosec 5 "image/color" 6 7 "github.com/lucasb-eyer/go-colorful" 8 ) 9 10 const ( 11 defaultSaturation = 0.5 12 defaultLightness = 0.7 13 ) 14 15 type Identicon struct { 16 bitmap []byte 17 color color.Color 18 } 19 20 func generate(key string) Identicon { 21 hash := md5.Sum([]byte(key)) // nolint: gosec 22 return Identicon{ 23 convertPatternToBinarySwitch(generatePatternFromHash(hash)), 24 getColorFromHash(hash), 25 } 26 } 27 28 func getColorFromHash(h [16]byte) color.Color { 29 // Take the last 3 relevant bytes, and convert to a float between [0..360] 30 sum := float64(h[13]) + float64(h[14]) + float64(h[15]) 31 t := (sum / 765) * 360 32 return colorful.Hsl(t, defaultSaturation, defaultLightness) 33 } 34 35 func generatePatternFromHash(sum [16]byte) []byte { 36 p := make([]byte, 25) 37 for i := 0; i < 5; i++ { 38 for j := 0; j < 5; j++ { 39 jCount := j 40 41 if j > 2 { 42 jCount = 4 - j 43 } 44 45 p[5*i+j] = sum[3*i+jCount] 46 } 47 } 48 return p 49 } 50 51 func convertPatternToBinarySwitch(pattern []byte) []byte { 52 b := make([]byte, 25) 53 for i, v := range pattern { 54 if v%2 == 0 { 55 b[i] = 1 56 } else { 57 b[i] = 0 58 } 59 } 60 return b 61 }