obfuscate

package module
v0.0.0-...-2c94ed6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2025 License: Apache-2.0 Imports: 7 Imported by: 0

README

go-obfuscate

Build Status Quality Gate Status Coverage Known Vulnerabilities

Provides functionality for obfuscating text. This can be useful for logging information that contains sensitive information.

Obfuscating strings

Pre-defined functions

The following pre-defined functions are provided that all return an immutable obfuscator.

obfuscate.All / obfuscate.AllWithMask

Replaces all characters with a mask character.

obfuscator := obfuscate.All()
obfuscated := obfuscator.ObfuscateString("Hello World")
// obfuscated is "***********"

Note: using these obfuscators still leak out information about the length of the original text. Using a fixed length or fixed value (see below) is more secure.

obfuscate.WithFixedLength / obfuscate.WithFixedLengthWithMask

Replaces the entire text with a fixed number of mask characters.

obfuscator := obfuscate.WithFixedLength(5)
obfuscated := obfuscator.ObfuscateString("Hello World")
// obfuscated is "*****"
obfuscate.WithFixedValue

Replaces the entire text with a fixed value.

obfuscator := obfuscate.WithFixedValue("foo")
obfuscated := obfuscator.ObfuscateString("Hello World")
// obfuscated is "foo"
obfuscate.Portion

While the above examples are simple, they are not very flexible. Using obfuscate.Portion you can build obfuscators that obfuscate only specific portions of text. Some examples:

Obfuscating all but the last 4 characters

Useful for obfuscating values like credit card numbers.

obfuscator := obfuscate.Portion().KeepAtEnd(4).Build()
obfuscated := obfuscator.ObfuscateString("1234567890123456")
// obfuscated is "************3456"

It’s advised to use AtLeastFromStart, to make sure that values of fewer than 16 characters are still obfuscated properly:

obfuscator := obfuscate.Portion().KeepAtEnd(4).AtLeastFromStart(12).Build()
obfuscated := obfuscator.ObfuscateString("1234567890")
// obfuscated is "**********" and not "******7890"
Obfuscating only the last 2 characters

Useful for obfuscating values like zip codes, where the first part is not as sensitive as the full zip code:

obfuscator := obfuscate.Portion().KeepAtStart(math.MaxInt).AtLeastFromEnd(2).Build()
obfuscated := obfuscator.ObfuscateString("SW1A 2AA")
// obfuscated is "SW1A 2**"

Here, the KeepAtStart instructs the obfuscator to keep everything; however, AtLeastFromEnd overrides that partly to ensure that the last two characters are obfuscated regardless of the value specified by KeepAtStart.

Using a fixed length

Similar to using obfuscate.All, by default an obfuscator built using obfuscate.Portion leaks out the length of the original text. If your text has a variable length, you should consider specifying a fixed total length for the result. The length of the result will then be the same no matter how long the input is:

obfuscator := obfuscate.Portion().KeepAtStart(2).KeepAtEnd(2).FixedTotalLength(6).Build()
obfuscated := obfuscator.ObfuscateString("Hello World")
// obfuscated is "He**ld"
obfuscated = obfuscator.ObfuscateString("foo")
// obfuscated is "fo**oo"

Note that if KeepAtStart and KeepAtEnd are both specified, parts of the input may be repeated in the result if the input’s length is less than the combined number of characters to keep. This makes it harder to find the original input. For example, if in the example foo would be obfuscated into fo***o instead, it would be clear that the input was foo. Instead, it can now be anything that starts with fo and ends with oo.

obfuscate.NewObfuscator

Converts any function that takes a string as input and returns a string into an obfuscator.

obfuscator := obfuscate.NewObfuscator(strings.ToUpper)
obfuscated := obfuscator.ObfuscateString("Hello World")
// obfuscated is "HELLO WORLD"
obfuscate.None

Returns the input as-is. It can be used as default to prevent checks. For instance:

obfuscator := somePossiblyNilObfuscator
if obfuscator == nil {
    obfuscator = obfuscate.None()
}

obfuscated := obfuscator.ObfuscateString("Hello World")
// obfuscated is "Hello World" if somePossiblyNilObfuscator was nil
Combining obfuscators

Sometimes the obfucators in this module alone cannot perform the obfuscation you need. For instance, if you want to obfuscate credit cards, but keep the first and last 4 characters. If the credit cards are all fixed length, obfuscate.Portion can do just that:

obfuscator := obfuscate.Portion().KeepAtStart(4).KeepAtEnd(4).Build()
obfuscated := obfuscator.ObfuscateString("1234567890123456")
// obfuscated is "1234********3456"

However, if you attempt to use such an obfuscator on only a part of a credit card, you could end up leaking parts of the credit card that you wanted to obfuscate:

incorrectlyObfuscated := obfuscator.ObfuscateString("12345678901234")
// incorrectlyObfuscated is "1234******1234" where "1234********34" would probably be preferred

To overcome this issue, it’s possible to combine obfuscators. The form is as follows:

  • Specify the first obfuscator, and the input length to which it should be used.
  • Specify any other obfuscators, and the input lengths to which they should be used. Note that each input length should be larger than the previous input length.
  • Specify the obfuscator that will be used for the remainder.

For instance, for credit card numbers of exactly 16 characters, the above can also be written like this:

obfuscator := obfuscate.None().UntilLength(4).Then(obfuscate.All()).UntilLength(12).Then(obfuscate.None())

With this chaining, it’s now possible to keep the first and last 4 characters, but with at least 8 characters in between:

obfuscator := obfuscate.None().UntilLength(4).Then(obfuscate.Portion().KeepAtEnd(4).AtLeastFromStart(8).Build())
obfuscated := obfuscator.ObfuscateString("12345678901234")
// obfuscated is "1234********34"
Splitting text during obfuscation

To make it easier to create obfuscators for structured text like email addresses, use an obfuscate.SplitPoint. Three implementations are provided :

  • obfuscate.AtFirst(s) splits at the first occurrence of string s.
  • obfuscate.AtLast(s) splits at the last occurrence of string s.
  • obfuscate.AtNth(s, occurrence) splits at the zero-based specified occurrence of string s.

For instance:

// Keep the domain as-is
localPartObfuscator := obfuscate.Portion().KeepAtStart(1).KeepAtEnd(1).FixedTotalLength(8).Build()
domainObfuscator := obfuscate.None()
obfuscator := obfuscate.AtFirst("@").SplitTo(localPartObfuscator, domainObfuscator)
obfuscated := obfuscator.ObfuscateString("[email protected]")
// obfuscated is "t******[email protected]"

To obfuscate the domain except for the TLD, use a nested obfuscate.SplitPoint:

// Keep only the TLD of the domain
localPartObfuscator := obfuscate.Portion().KeepAtStart(1).KeepAtEnd(1).FixedTotalLength(8).Build()
domainObfuscator := obfuscate.AtLast(".").SplitTo(obfuscate.All(), obfuscate.None())
obfuscator := obfuscate.AtFirst("@").SplitTo(localPartObfuscator, domainObfuscator)
obfuscated := obfuscator.ObfuscateString("[email protected]")
// obfuscated is "t******t@*******.org"

Obfuscating HTTP headers

Use obfuscate.HTTPHeaders to create an object that can obfuscate single HTTP headers (as strings or string slices) and maps of HTTP headers (with values as strings or string slices). It will always use case insensitive matching.

headerObfuscator := obfuscate.HTTPHeaders(map[string]obfuscate.Obfuscator{
    "Authorization": obfuscate.WithFixedLength(3),
})
obfuscatedAuthorization := headerObfuscator.ObfuscateHeaderValue("authorization", "Bearer someToken")
// obfuscatedAuthorization is "***"
obfuscatedAuthorizations := headerObfuscator.ObfuscateHeaderValues("authorization", []string{"Bearer someToken"})
// obfuscatedAuthorization is ["***"]
obfuscatedContentType := headerObfuscator.ObfuscateHeaderValue("Content-Type", "application/json")
// obfuscatedContentType is "application/json"
obfuscatedHeaders := headerObfuscator.ObfuscateHeaderMap(map[string]string{
    "authorization": "Bearer someToken",
    "content-type": "application/json",
})
// obfuscatedHeaders is map["authorization":"***", "content-type":"application/json"]

Obfuscating HTTP parameters

Use obfuscate.HTTPParameters to create an object that can obfuscate HTTP query and form parameter strings, as well as separate parameter values.

paramsObfuscator := obfuscate.HTTPParameters().
    WithParameter("password", obfuscate.WithFixedLength(3)).
    Build()
obfuscatedPassword := paramsObfuscator.ObfuscateParameter("password", "admin1234")
// obfuscatedPassword is "***"
obfuscatedUsername := paramsObfuscator.ObfuscateParameter("username", "admin")
// obfuscatedUsername is "admin"
obfuscatedParamString, err := paramsObfuscator.ParseAndObfuscateString("username=admin&password=admin1234")
// obfuscatedParamString is "username=admin&password=***"

Objects created by calling Build() on the result of obfuscate.HTTPParameters implement obfuscate.Obfuscator. Calling ObfuscateString works almost the same as calling ParseAndObfuscateString. Because parsing parameter strings can fail with an error, the builder returned by obfuscate.HTTPParameters can be configured to specify how to handle errors:

  • OnErrorLog(logger) (default) will cause the error to be logged. If a non-nil log.Logger is given its Printf method will be used, otherwise fmt.Printf will be used.
  • OnErrorInclude() will cause the error to be included in the return value.
  • OnErrorDiscard() wil cause the return value to not contain any data following the error. For security purposes parameter names and values will either be included fully or not at all.
paramsObfuscator := obfuscate.HTTPParameters().
    WithParameter("password", obfuscate.WithFixedLength(3)).
    OnErrorInclude().
    Build()
obfuscatedParamString := paramsObfuscator.ObfuscateString("username=admin&password=admin1234%A")
// obfuscatedParamString is something like "username=admin&password=<error: invalid URL escape \"%A\">"

Obfuscating JSON

Use obfuscate.JSON to create an object that can obfuscate JSON strings.

jsonObfuscator := obfuscate.JSON().
    WithProperty("password", obfuscate.WithFixedLength(3), nil).
    Build()
obfuscatedJsonString, err := jsonObfuscator.ParseAndObfuscateString(`{"username": "admin", "password": "admin1234"}`)
// obfuscatedJsonString is equivalent to `{"username": "admin", "password": "***"}`

If a matched property is not a string or other scalar value but instead an object or array, it will by default be ignored. This behaviour can be changed in two ways:

  1. Per property. Instead of providing nil for the third argument, pass property-specific options:
    jsonObfuscator := obfuscate.JSON().
        WithProperty("password", obfuscate.WithFixedLength(3), &obfuscate.JSONPropertyObfuscationOptions{
            ForObjects: obfuscate.Inherit,
            ForArrays:  obfuscate.Inherit,
        }).
        Build()
    
  2. Setting global settings on the builder:
    jsonObfuscator := obfuscate.JSON().
        WithProperty("password", obfuscate.WithFixedLength(3), nil).
        ForObjects(obfuscate.Inherit).
        ForArrays(obfuscate.Inherit).
        Build()
    

In both cases, ForObjects and ForArrays can take the following values:

  • obfuscate.Exclude to not match properties with object or array values; nested properties will be matched separately.
  • obfuscate.ExcludeAll to not match properties with object or array values; obfuscation will exclude all nested properties as well.
  • obfuscate.Inherit to obfuscate each nested scalar property value or array element using the given obfuscator.
  • obfuscate.InheritOverridable to obfuscate each nested scalar property value or array element using the given obfuscator; however, if a nested property has its own obfuscator defined this will be used instead.

Objects created by calling Build() on the result of obfuscate.JSON implement obfuscate.Obfuscator. Calling ObfuscateString works almost the same as calling ParseAndObfuscateString. Because parsing JSON strings can fail with an error, the builder returned by obfuscate.JSON can be configured to specify how to handle errors:

  • OnErrorLog(logger) (default) will cause the error to be logged. If a non-nil log.Logger is given its Printf method will be used, otherwise fmt.Printf will be used.
  • OnErrorInclude() will cause the error to be included in the return value.
  • OnErrorDiscard() wil cause the return value to not contain any data following the error. For security purposes parameter names and values will either be included fully or not at all.
jsonObfuscator := obfuscate.JSON().
    WithProperty("password", obfuscate.WithFixedLength(3), nil).
    OnErrorInclude().
    Build()
obfuscatedJsonString := jsonObfuscator.ObfuscateString(`{"username": admin, "password": "admin1234"}`)
// obfuscatedJsonString ends with "<error: invalid character 'a' looking for beginning of value>"
// It may or may not include any part of the JSON before the parse error

Obfuscating maps

Use obfuscate.Maps to create an object that can obfuscate string values in maps. The key type can be anything that is comparable, but usually string is used.

mapObfuscator := obfuscate.Maps(map[string]obfuscate.Obfuscator{
    "password": obfuscate.WithFixedLength(3),
})
obfuscatedMap := mapObfuscator.ObfuscateMap(map[string]string{
    "username": "admin",
    "password": "admin1234",
})
// obfuscatedMap is map["username":"admin", "password":"***"]

Obfuscating slices

Use obfuscate.Slice to obfuscate all elements of a slice.

input := []int{1, 2, 3}
obfuscated := obfuscate.Slice(input, obfuscate.WithFixedLength(3))
// obfuscated is ["***", "***", "***"]

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Slice

func Slice[T any](s []T, obfuscator Obfuscator) []string

Slice obfuscates all elements of a slice using the given obfuscator. Values are converted to string using fmt.Sprintf("%v", value). This allows this function to be used not just for string slices but also other scalar types.

Types

type ErrorStrategy

type ErrorStrategy int

ErrorStrategy represents the strategy to follow when an error occurs while obfuscating a string.

const (
	// OnErrorLog will cause obfuscation to stop when an error occurs. The error will be logged.
	OnErrorLog ErrorStrategy = iota
	// OnErrorInclude will cause obfuscation to stop when an error occurs. The error will be included in the obfuscation result.
	OnErrorInclude
	// OnErrorDiscard will cause obfuscation to stop when an error occurs. The error will not be visible in any way.
	OnErrorDiscard
)

func (ErrorStrategy) String

func (es ErrorStrategy) String() string

String implements the fmt.Stringer interface.

type HTTPHeaderObfuscator

type HTTPHeaderObfuscator struct {
	// contains filtered or unexported fields
}

HTTPHeaderObfuscator represents an object that can obfuscate HTTP header values.

func HTTPHeaders

func HTTPHeaders(obfuscators map[string]Obfuscator) HTTPHeaderObfuscator

HTTPHeaders creates a new HTTP header obfuscator.

func (HTTPHeaderObfuscator) ObfuscateHeaderMap

func (o HTTPHeaderObfuscator) ObfuscateHeaderMap(headerMap map[string]string) map[string]string

ObfuscateHeaderMap obfuscates all values in a map where the keys are HTTP header names and the values are the matching HTTP header values.

func (HTTPHeaderObfuscator) ObfuscateHeaderMultiMap

func (o HTTPHeaderObfuscator) ObfuscateHeaderMultiMap(headerMap map[string][]string) map[string][]string

ObfuscateHeaderMultiMap obfuscates all values in a map where the keys are HTTP header names and the values are the matching HTTP header values.

func (HTTPHeaderObfuscator) ObfuscateHeaderValue

func (o HTTPHeaderObfuscator) ObfuscateHeaderValue(headerName, headerValue string) string

ObfuscateHeaderValue obfuscates the value for a single header.

func (HTTPHeaderObfuscator) ObfuscateHeaderValues

func (o HTTPHeaderObfuscator) ObfuscateHeaderValues(headerName string, headerValues []string) []string

ObfuscateHeaderValues obfuscates multiple values for a single header.

type HTTPParameterObfuscator

type HTTPParameterObfuscator struct {
	// contains filtered or unexported fields
}

HTTPParameterObfuscator represents an object that can obfuscate HTTP query and form parameter strings, as well as separate parameter values.

func (HTTPParameterObfuscator) ObfuscateParameter

func (o HTTPParameterObfuscator) ObfuscateParameter(name, value string) string

ObfuscateParameter obfuscates the given value for a parameter with the given name.

func (HTTPParameterObfuscator) ObfuscateString

func (o HTTPParameterObfuscator) ObfuscateString(s string) string

ObfuscateString implements the Obfuscator interface.

It is like HTTPParameterObfuscator.ParseAndObfuscateString, but it handles any error internally according to the ErrorStrategy provided when the HTTPParameterObfuscator instance was created.

func (HTTPParameterObfuscator) ParseAndObfuscateString

func (o HTTPParameterObfuscator) ParseAndObfuscateString(s string) (string, error)

ParseAndObfuscateString implements the Obfuscator interface.

func (HTTPParameterObfuscator) UntilLength

func (o HTTPParameterObfuscator) UntilLength(prefixLength int) ObfuscatorPrefix

UntilLength implements the Obfuscator interface.

type HTTPParameterObfuscatorBuilder

type HTTPParameterObfuscatorBuilder struct {
	// contains filtered or unexported fields
}

HTTPParameterObfuscatorBuilder is a builder for HTTPParameterObfuscator instances.

func HTTPParameters

func HTTPParameters() *HTTPParameterObfuscatorBuilder

HTTPParameters creates a new builder for HTTP parameter obfuscators.

func (*HTTPParameterObfuscatorBuilder) Build

Build creates a new HTTP parameter obfuscator using the contents of the builder.

func (*HTTPParameterObfuscatorBuilder) OnErrorDiscard

OnErrorDiscard sets the strategy to follow when an error occurs while obfuscating a string to OnErrorDiscard.

func (*HTTPParameterObfuscatorBuilder) OnErrorInclude

OnErrorInclude sets the strategy to follow when an error occurs while obfuscating a string to OnErrorInclude.

func (*HTTPParameterObfuscatorBuilder) OnErrorLog

OnErrorLog sets the strategy to follow when an error occurs while obfuscating a string to OnErrorLog. If the given logger is nil, fmt.Printf will be used instead.

func (*HTTPParameterObfuscatorBuilder) WithParameter

func (b *HTTPParameterObfuscatorBuilder) WithParameter(parameterName string, obfuscator Obfuscator) *HTTPParameterObfuscatorBuilder

WithParameter registers a parameter to obfuscate. It uses the given obfuscator for obfuscating any occurrence of a parameter with the given name.

type JSONObfuscator

type JSONObfuscator struct {
	// contains filtered or unexported fields
}

JSONObfuscator represents an object that can obfuscate JSON strings.

func (JSONObfuscator) ObfuscateString

func (o JSONObfuscator) ObfuscateString(s string) string

ObfuscateString implements the Obfuscator interface.

It is like JSONObfuscator.ParseAndObfuscateString, but it handles any error internally according to the ErrorStrategy provided when the JSONObfuscator instance was created.

func (JSONObfuscator) ParseAndObfuscateString

func (o JSONObfuscator) ParseAndObfuscateString(s string) (string, error)

ParseAndObfuscateString implements the Obfuscator interface.

func (JSONObfuscator) UntilLength

func (o JSONObfuscator) UntilLength(prefixLength int) ObfuscatorPrefix

UntilLength implements the Obfuscator interface.

type JSONObfuscatorBuilder

type JSONObfuscatorBuilder struct {
	// contains filtered or unexported fields
}

JSONObfuscatorBuilder is a builder for JSONObfuscator instances.

func JSON

func JSON() *JSONObfuscatorBuilder

JSON creates a new builder for JSON obfuscators.

func (*JSONObfuscatorBuilder) Build

Build creates a new JSON obfuscator using the contents of the builder.

func (*JSONObfuscatorBuilder) ForArrays

ForArrays sets the default obfuscation mode for arrays. This is used for any property for which no explicit obfuscation mode has been given.

func (*JSONObfuscatorBuilder) ForObjects

ForObjects sets the default obfuscation mode for objects. This is used for any property for which no explicit obfuscation mode has been given.

func (*JSONObfuscatorBuilder) OnErrorDiscard

func (b *JSONObfuscatorBuilder) OnErrorDiscard() *JSONObfuscatorBuilder

OnErrorDiscard sets the strategy to follow when an error occurs while obfuscating a string to OnErrorDiscard.

func (*JSONObfuscatorBuilder) OnErrorInclude

func (b *JSONObfuscatorBuilder) OnErrorInclude() *JSONObfuscatorBuilder

OnErrorInclude sets the strategy to follow when an error occurs while obfuscating a string to OnErrorInclude.

func (*JSONObfuscatorBuilder) OnErrorLog

func (b *JSONObfuscatorBuilder) OnErrorLog(logger *log.Logger) *JSONObfuscatorBuilder

OnErrorLog sets the strategy to follow when an error occurs while obfuscating a string to OnErrorLog. If the given logger is nil, fmt.Printf will be used instead.

func (*JSONObfuscatorBuilder) WithProperty

func (b *JSONObfuscatorBuilder) WithProperty(propertyName string, obfuscator Obfuscator, options *JSONPropertyObfuscationOptions) *JSONObfuscatorBuilder

WithProperty registers a property to obfuscate. It uses the given obfuscator for obfuscating any occurrence of a property with the given name.

When the value of a property with the given name is an object or array, by default it will be ignored. Additional options can be given that determine how to handle these. See ObfuscationMode for more information.

type JSONPropertyObfuscationOptions

type JSONPropertyObfuscationOptions struct {
	// ForObjects defines how to handle matched object properties.
	ForObjects ObfuscationMode
	// ForArrays defines how to handle matched array properties.
	ForArrays ObfuscationMode
}

JSONPropertyObfuscationOptions represents obfuscation options for a single property.

type MapObfuscator

type MapObfuscator[K comparable] struct {
	// contains filtered or unexported fields
}

MapObfuscator represents an object that can obfuscate map values.

func Maps

func Maps[K comparable](obfuscators map[K]Obfuscator) MapObfuscator[K]

Maps creates a new map obfuscator.

func (MapObfuscator[K]) ObfuscateMap

func (o MapObfuscator[K]) ObfuscateMap(m map[K]string) map[K]string

ObfuscateMap obfuscates all values in a map.

func (MapObfuscator[K]) ObfuscateMultiMap

func (o MapObfuscator[K]) ObfuscateMultiMap(m map[K][]string) map[K][]string

ObfuscateMultiMap obfuscates all values in a map.

type ObfuscationMode

type ObfuscationMode int
const (
	// Exclude means obfuscators will not be used for complex structures like JSON objects or arrays.
	// Obfuscation will instead traverse in them, and for any nested properties their own obfuscation rules will be applied.
	Exclude ObfuscationMode = iota
	// ExcludeAll means obfuscators will not be used for complex structures like JSON objects or arrays.
	// Obfuscation will not traverse in them, so any nested properties will not be obfuscated.
	ExcludeAll
	// Inherit means obfuscators will be used for any nested property of complex structures like JSON objects or arrays.
	// Any obfuscation rules for nested properties will be ignored.
	Inherit
	// InheritOverridable means obfuscators will be used for any nested property of complex structures like JSON objects or arrays.
	// For any nested properties their own obfuscation rules will be applied.
	InheritOverridable
)

func (ObfuscationMode) String

func (om ObfuscationMode) String() string

String implements the fmt.Stringer interface.

type Obfuscator

type Obfuscator interface {
	// ObfuscateString obfuscates the given string.
	//
	// If the parser needs to do any parsing that can result in an error, this should be handled according to one of the possible [ErrorStrategy] constants.
	ObfuscateString(s string) string

	// ParseAndObfuscateString parses the given string and obfuscates the parsed result.
	//
	// If the obfuscator does not need any parsing, this method will do the same as [ObfuscateString], and the error will be nil.
	ParseAndObfuscateString(s string) (string, error)

	// UntilLength creates a prefix that can be used to chain another obfuscator to this obfuscator.
	// For the part up to the given prefix length, this obfuscator will be used; for any remaining content another obfuscator will be used.
	// This makes it possible to easily create complex obfuscators that would otherwise be impossible using any of the other obfuscators provided by this module.
	//
	// The prefix length needs to be at least 1, and larger than all previous lengths in a method chain.
	// In other words, each prefix length must be larger than its direct predecessor.
	// This method panics if this pre-condition is not met.
	UntilLength(prefixLength int) ObfuscatorPrefix
}

Obfuscator represents an object that can obfuscate strings, making them partly or completely unreadable.

func All

func All() Obfuscator

All returns an obfuscator that replaces all characters in strings with an asterisk (*).

func AllWithMask

func AllWithMask(mask string) Obfuscator

AllWithMask returns an obfuscator that replaces all characters in strings with the given mask.

func NewObfuscator

func NewObfuscator(obfuscate func(s string) string) Obfuscator

NewObfuscator creates a new obfuscator that delegates to the given function.

Calling [Obfuscator.ParseAndObfuscateString] on the result will always return a nil error.

func NewObfuscatorOnErrorDiscard

func NewObfuscatorOnErrorDiscard(parseAndObfuscate func(s string) (string, error)) Obfuscator

NewObfuscatorOnErrorDiscard creates a new obfuscator that delegates to the given function.

When calling [Obfuscator.ObfuscateString] on the result with a string that would cause the given function to return an error, this error is discarded.

func NewObfuscatorOnErrorInclude

func NewObfuscatorOnErrorInclude(parseAndObfuscate func(s string) (string, error)) Obfuscator

NewObfuscatorOnErrorInclude creates a new obfuscator that delegates to the given function.

When calling [Obfuscator.ObfuscateString] on the result with a string that would cause the given function to return an error, this error is appended to the result.

func NewObfuscatorOnErrorLog

func NewObfuscatorOnErrorLog(parseAndObfuscate func(s string) (string, error), logger *log.Logger) Obfuscator

NewObfuscatorOnErrorLog creates a new obfuscator that delegates to the given function.

When calling [Obfuscator.ObfuscateString] on the result with a string that would cause the given function to return an error, this error is logged. If the given logger is nil, fmt.Printf will be used instead.

func None

func None() Obfuscator

None returns an obfuscator that does not obfuscate anything. It can be used as default value.

func WithFixedLength

func WithFixedLength(fixedLength int) Obfuscator

WithFixedLength returns an obfuscator that replaces strings with the given fixed length occurrences of a single asterisk (*).

It panics if the fixed length is negative.

func WithFixedLengthWithMask

func WithFixedLengthWithMask(fixedLength int, mask string) Obfuscator

WithFixedLengthWithMask returns an obfuscator that replaces strings with the given fixed length occurrences of the given mask.

It panics if the fixed length is negative or if the result of (len(mask) * fixedLength) overflows.

func WithFixedValue

func WithFixedValue(fixedValue string) Obfuscator

WithFixedValue returns an obfuscator that replaces strings with the given fixed value.

type ObfuscatorPrefix

type ObfuscatorPrefix struct {
	// contains filtered or unexported fields
}

ObfuscatorPrefix represents a prefix of a specific length that uses a specific obfuscator. It can be used to create combined obfuscators that obfuscate strings for the part up to the length of this prefix using the prefix' obfuscator, then the rest with another.

func NewObfuscatorPrefix

func NewObfuscatorPrefix(o Obfuscator, prefixLength int) ObfuscatorPrefix

NewObfuscatorPrefix creates a new ObfuscatorPrefix.

This function is intended only for implementing custom obfuscators. It should not be used directly.

func (ObfuscatorPrefix) Then

func (op ObfuscatorPrefix) Then(other Obfuscator) Obfuscator

Then returns an obfuscator that first uses the obfuscator that was used to create the receiver for the length of the receiver, then another obfuscator.

type PortionBuilder

type PortionBuilder struct {
	// contains filtered or unexported fields
}

PortionBuilder represents a builder for obfuscators that obfuscates a specific portion of their input.

func Portion

func Portion() *PortionBuilder

Portion returns a builder for obfuscators that obfuscates a specific portion of their input.

func (*PortionBuilder) AtLeastFromEnd

func (pb *PortionBuilder) AtLeastFromEnd(value int) *PortionBuilder

AtLeastFromEnd sets the minimum number of characters from the end that need to be obfuscated. This will overrule any value for PortionBuilder.KeepAtStart or PortionBuilder.KeepAtEnd. Defaults to 0.

It panics if the given value is negative.

func (*PortionBuilder) AtLeastFromStart

func (pb *PortionBuilder) AtLeastFromStart(value int) *PortionBuilder

AtLeastFromStart sets the minimum number of characters from the start that need to be obfuscated. This will overrule any value for PortionBuilder.KeepAtStart or PortionBuilder.KeepAtEnd. Defaults to 0.

It panics if the given value is negative.

func (*PortionBuilder) Build

func (pb *PortionBuilder) Build() Obfuscator

Build returns an obfuscator that obfuscates a specific portion of their input, using the values configured in this builder.

It panics if a PortionBuilder.FixedTotalLength is set that is smaller than the sum of the (default) values for PortionBuilder.KeepAtStart and PortionBuilder.KeepAtEnd.

func (*PortionBuilder) FixedTotalLength

func (pb *PortionBuilder) FixedTotalLength(value int) *PortionBuilder

FixedTotalLength sets the fixed total length to use for obfuscated contents. When obfuscating, the result will have the mask added until this total length has been reached.

Note: when used in combination with PortionBuilder.KeepAtStart and/or PortionBuilder.KeepAtEnd, this total length must be at least the sum of both other values. When used in combination with both, parts of the input may be repeated in the obfuscated content if the input's length is less than the combined number of characters to keep.

It panics if the given value is negative.

func (*PortionBuilder) KeepAtEnd

func (pb *PortionBuilder) KeepAtEnd(value int) *PortionBuilder

KeepAtEnd sets the number of characters at the end that created obfuscators will skip when obfuscating. Defaults to 0.

It panics if the given value is negative.

func (*PortionBuilder) KeepAtStart

func (pb *PortionBuilder) KeepAtStart(value int) *PortionBuilder

KeepAtStart sets the number of characters at the start that created obfuscators will skip when obfuscating. Defaults to 0.

It panics if the given value is negative.

func (*PortionBuilder) Mask

func (pb *PortionBuilder) Mask(mask string) *PortionBuilder

Mask sets the string to use for masking. Defaults to a single asterisk (*).

It panics if the given mask is empty.

type SplitPoint

type SplitPoint struct {
	// contains filtered or unexported fields
}

SplitPoint represents a point in a string to split obfuscation. Like Obfuscator.UntilLength it can be used to combine obfuscators. For instance, to obfuscate email addresses:

localPartObfuscator := obfuscate.Portion()
    .KeepAtStart(1)
    .KeepAtEnd(1)
    .FixedTotalLength(8)
    .Build()
domainObfuscator := obfuscate.None()
obfuscator := obfuscate.AtFirst("@").SplitTo(localPrtObfuscator, domainObfuscator)
// Everything before @ will be obfuscated using localPartObfuscator, everything after @ will not be obfuscated.
// Example input: [email protected]
// Example output: t******[email protected]

Unlike Obfuscator.UntilLength it's not possible to chain splitting, but it's possible to nest it:

localPartObfuscator := obfuscate.Portion()
    .KeepAtStart(1)
    .KeepAtEnd(1)
    .FixedTotalLength(8)
    .Build()
domainObfuscator := obfuscate.AtLast(".").SplitTo(obfuscate.All(), obfuscate.None())
obfuscator := obfuscate.AtFirst("@").SplitTo(localPartObfuscator, domainObfuscator)
// Everything before @ will be obfuscated using localPartObfuscator, everything after @ will be obfuscated until the last dot
// Example input: [email protected]
// Example output: t******t@*******.org

func AtFirst

func AtFirst(s string) SplitPoint

AtFirst creates a new split point that splits at the first occurrence of a string. This split point is exclusive; the string itself will not be obfuscated.

func AtLast

func AtLast(s string) SplitPoint

AtLast creates a new split point that splits at the last occurrence of a string. This split point is exclusive; the string itself will not be obfuscated.

func AtNth

func AtNth(s string, occurrence int) SplitPoint

AtNth creates a new split point that splits at a specific occurrence of a string. This split point is exclusive; the string itself will not be obfuscated.

AtNth panics if the given zero-based occurrence is negative.

func NewSplitPoint

func NewSplitPoint(splitStart func(s string) int, splitLength int) SplitPoint

NewSplitPoint creates a new split point.

splitStart is a function that takes a string and returns the 0-based index where to split, or a negative value if obfuscation should not be split. This could for example be caused by a string to split on not being found.

splitLength is the length of the split point. If not 0, the substring with this length starting at the calculated split start will not be obfuscated. This function panics if splitLength is negative.

func (SplitPoint) SplitTo

func (sp SplitPoint) SplitTo(beforeSplitPoint, afterSplitPoint Obfuscator) Obfuscator

SplitTo creates an obfuscator that splits obfuscation at this split point. The part of the string before the split point will be obfuscated by the first obfuscator, the part after the split point by the second.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL