github.com/Ingenico-ePayments/connect-sdk-go@v0.0.0-20240318153750-1f8cd329b9c9/logging/obfuscation/ValueObfuscator.go (about) 1 package obfuscation 2 3 import ( 4 "bytes" 5 "unicode/utf8" 6 ) 7 8 type valueObfuscator struct { 9 maskCharacter rune 10 fixedLength int 11 keepStartCount int 12 keepEndCount int 13 } 14 15 func valueObfuscatorWithAll() valueObfuscator { 16 return newValueObfuscator(0, 0, 0) 17 } 18 19 func valueObfuscatorWithFixedLength(fixedLength int) valueObfuscator { 20 return newValueObfuscator(fixedLength, 0, 0) 21 } 22 23 func valueObfuscatorWithKeepingStartCount(count int) valueObfuscator { 24 return newValueObfuscator(0, count, 0) 25 } 26 27 func valueObfuscatorWithKeepingEndCount(count int) valueObfuscator { 28 return newValueObfuscator(0, 0, count) 29 } 30 31 func (vo valueObfuscator) obfuscateValue(value string) string { 32 valueLength := utf8.RuneCountInString(value) 33 34 if valueLength == 0 { 35 return value 36 } 37 if vo.fixedLength > 0 { 38 return vo.repeatMask(vo.fixedLength) 39 } 40 if valueLength < vo.keepStartCount || valueLength < vo.keepEndCount { 41 return value 42 } 43 44 var chars bytes.Buffer 45 i := 0 46 for _, r := range value { 47 if i < vo.keepStartCount || i >= valueLength - vo.keepEndCount { 48 chars.WriteRune(r) 49 } else { 50 chars.WriteRune(vo.maskCharacter) 51 } 52 i++ 53 } 54 55 return chars.String() 56 } 57 58 func (vo valueObfuscator) repeatMask(count int) string { 59 var buffer bytes.Buffer 60 61 for i := vo.keepStartCount; i < count; i++ { 62 buffer.WriteRune(vo.maskCharacter) 63 } 64 65 return buffer.String() 66 } 67 68 func newValueObfuscator(fixedLength, keepStartCount, keepEndCount int) valueObfuscator { 69 return valueObfuscator{'*', fixedLength, keepStartCount, keepEndCount} 70 }