diff --git a/README.md b/README.md index bcceed33a..215cc7598 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,7 @@ this functionality might prove useful. - [regexMatch](#regexmatch) - [regexReplaceAll](#regexreplaceall) - [replaceAll](#replaceall) + - [sha256Hex](#sha256hex) - [split](#split) - [timestamp](#timestamp) - [toJSON](#tojson) @@ -1838,6 +1839,14 @@ This function can be chained with other functions as well: {{ service "web" }}{{ .Name | replaceAll ":" "_" }}{{ end }} ``` +##### `sha256Hex` + +Takes the argument as a string and compute the sha256_hex value + +```liquid +{{ "bladibla" | sha256Hex }} +``` + ##### `split` Splits the given string on the provided separator: diff --git a/template/funcs.go b/template/funcs.go index 12e35b888..91afb9e35 100644 --- a/template/funcs.go +++ b/template/funcs.go @@ -2,7 +2,9 @@ package template import ( "bytes" + "crypto/sha256" "encoding/base64" + "encoding/hex" "encoding/json" "fmt" "io/ioutil" @@ -1379,3 +1381,11 @@ func sockaddr(args ...string) (string, error) { } return k, nil } + +// sha256Hex return the sha256 hex of a string +func sha256Hex(item string) (string, error) { + h := sha256.New() + h.Write([]byte(item)) + output := hex.EncodeToString(h.Sum(nil)) + return output, nil +} diff --git a/template/funcs_test.go b/template/funcs_test.go index fa83eee8e..786cf9db5 100644 --- a/template/funcs_test.go +++ b/template/funcs_test.go @@ -234,3 +234,36 @@ func Test_byMeta(t *testing.T) { }) } } + +func Test_sha256Hex(t *testing.T) { + type args struct { + item string + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + name: "Should return the proper string", + args: args{ + item: "bladibla", + }, + want: "54cf4c66bcabb5c20e25331c01dd600b73369e97a947861bd8d3a0e0b8b3d70b", + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := sha256Hex(tt.args.item) + if (err != nil) != tt.wantErr { + t.Errorf("sha256Hex() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("sha256Hex() got = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/template/template.go b/template/template.go index b56a79e2e..2591edb0f 100644 --- a/template/template.go +++ b/template/template.go @@ -277,6 +277,7 @@ func funcMap(i *funcMapInput) template.FuncMap { "regexReplaceAll": regexReplaceAll, "regexMatch": regexMatch, "replaceAll": replaceAll, + "sha256Hex": sha256Hex, "timestamp": timestamp, "toLower": toLower, "toJSON": toJSON,