Skip to content

Commit

Permalink
Adds an md5sum function
Browse files Browse the repository at this point in the history
Useful for computing md5sums of strings to be used in places
where sha256 is not supported.
  • Loading branch information
geofffranks committed Apr 23, 2021
1 parent dfd1b0e commit 08d355e
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/templating-language.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ provides the following functions:
- [regexReplaceAll](#regexreplaceall)
- [replaceAll](#replaceall)
- [sha256Hex](#sha256hex)
- [md5sum](#md5sum)
- [split](#split)
- [timestamp](#timestamp)
- [toJSON](#tojson)
Expand Down Expand Up @@ -1304,6 +1305,14 @@ Takes the argument as a string and compute the sha256_hex value
{{ "bladibla" | sha256Hex }}
```

### `md5sum`

Takes a string input as an argument, and returns the hex-encoded md5 hash of the input.

```liquid
{{ "myString" | md5 }}
```

### `split`

Splits the given string on the provided separator:
Expand Down
6 changes: 6 additions & 0 deletions template/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package template

import (
"bytes"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
Expand Down Expand Up @@ -1542,3 +1543,8 @@ func sha256Hex(item string) (string, error) {
output := hex.EncodeToString(h.Sum(nil))
return output, nil
}

// md5sum returns the md5 hash of a string
func md5sum(item string) (string, error) {
return fmt.Sprintf("%x", md5.Sum([]byte(item))), nil
}
33 changes: 33 additions & 0 deletions template/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,3 +234,36 @@ func Test_sha256Hex(t *testing.T) {
})
}
}

func Test_md5sum(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: "c6886abd136f7daece35aebb01f1b713",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := md5sum(tt.args.item)
if (err != nil) != tt.wantErr {
t.Errorf("md5sum() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("md5sum() got = %v, want %v", got, tt.want)
}
})
}
}
1 change: 1 addition & 0 deletions template/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ func funcMap(i *funcMapInput) template.FuncMap {
"regexMatch": regexMatch,
"replaceAll": replaceAll,
"sha256Hex": sha256Hex,
"md5sum": md5sum,
"timestamp": timestamp,
"toLower": toLower,
"toJSON": toJSON,
Expand Down

0 comments on commit 08d355e

Please sign in to comment.