Skip to content

Commit

Permalink
Encode accented letters as well
Browse files Browse the repository at this point in the history
  • Loading branch information
reinkrul committed Dec 17, 2024
1 parent dcc0eed commit 9ad3579
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
17 changes: 11 additions & 6 deletions did_x509/did_x509.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,11 @@ import (
"encoding/base64"
"errors"
"fmt"
"github.com/nuts-foundation/go-did/did"
"github.com/nuts-foundation/uzi-did-x509-issuer/x509_cert"
"net/url"
"regexp"
"strings"
"unicode"

"github.com/nuts-foundation/go-did/did"
"github.com/nuts-foundation/uzi-did-x509-issuer/x509_cert"
)

type X509Did struct {
Expand Down Expand Up @@ -60,8 +58,15 @@ func CreateDid(signingCert, caCert *x509.Certificate, subjectAttributes []x509_c
// See https://github.com/golang/go/issues/27559#issuecomment-449652574
func PercentEncode(input string) string {
var encoded strings.Builder
for _, r := range input {
if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '-' || r == '_' || r == '.' {
// Unicode characters might consist of multiple bytes, so first we encode the string using url.PathEscape (which supports multi-byte characters),
// then we encode the characters that weren't encoded by url.PathEscape, but need to be encoded according to the DID specification.
preEscaped := url.PathEscape(input)
encoded.Grow(len(preEscaped))
for _, r := range preEscaped {
if r == '%' ||
(r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') ||
(r >= '0' && r <= '9') ||
r == '-' || r == '.' || r == '_' {
encoded.WriteRune(r)
} else {
encoded.WriteString(fmt.Sprintf("%%%02X", r))
Expand Down
11 changes: 7 additions & 4 deletions did_x509/did_x509_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@ func TestPercentEncode(t *testing.T) {
{"a+b=c", "a%2Bb%3Dc"},
{"~!@#$%^&*()_+", "%7E%21%40%23%24%25%5E%26%2A%28%29_%2B"},
{"FauxCare & Co", "FauxCare%20%26%20Co"},
{"FåúxCaré & Có", "F%C3%A5%C3%BAxCar%C3%A9%20%26%20C%C3%B3"},
}

for _, test := range tests {
result := PercentEncode(test.input)
if result != test.expected {
t.Errorf("PercentEncode(%q) = %q; want %q", test.input, result, test.expected)
}
t.Run(test.input, func(t *testing.T) {
result := PercentEncode(test.input)
if result != test.expected {
t.Errorf("PercentEncode(%q) = %q; want %q", test.input, result, test.expected)
}
})
}
}

Expand Down

0 comments on commit 9ad3579

Please sign in to comment.