Skip to content

Commit fcd234c

Browse files
committed
Use base64.RawURLEncoding to avoid padding
JWT uses a non-padded base64 encoding. Current code uses base64.URLEncoding to generate a padded string and then removes the padding. Likewise, current code adds padding before decoding. Instead, use base64.RawURLEncoding which does not add or require the padding in the first place. In addition to making the code cleaner, this reduces memory allocations as reported by benchmarks. Before: ``` BenchmarkECDSASigning/Basic_ES256-8 191396 6917 ns/op 4121 B/op 61 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 49347 25039 ns/op 3201 B/op 39 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 190668 6586 ns/op 4121 B/op 61 allocs/op BenchmarkHS256Signing-8 1260060 1131 ns/op 1585 B/op 32 allocs/op BenchmarkHS384Signing-8 861378 1387 ns/op 1969 B/op 32 allocs/op BenchmarkHS512Signing-8 896745 1463 ns/op 2065 B/op 32 allocs/op BenchmarkRS256Signing-8 3086 355769 ns/op 32576 B/op 136 allocs/op BenchmarkRS384Signing-8 3414 353570 ns/op 32694 B/op 136 allocs/op BenchmarkRS512Signing-8 3235 349394 ns/op 32706 B/op 136 allocs/op ``` After: ``` BenchmarkECDSASigning/Basic_ES256-8 176617 6827 ns/op 4021 B/op 58 allocs/op BenchmarkECDSASigning/Basic_ES256/sign-only-8 48038 24213 ns/op 3169 B/op 38 allocs/op BenchmarkECDSASigning/basic_ES256_invalid:_foo_=>_bar-8 194352 6928 ns/op 4021 B/op 58 allocs/op BenchmarkHS256Signing-8 1000000 1127 ns/op 1488 B/op 29 allocs/op BenchmarkHS384Signing-8 972552 1369 ns/op 1873 B/op 29 allocs/op BenchmarkHS512Signing-8 780751 1368 ns/op 1969 B/op 29 allocs/op BenchmarkRS256Signing-8 3014 387326 ns/op 32475 B/op 133 allocs/op BenchmarkRS384Signing-8 3044 361411 ns/op 32591 B/op 133 allocs/op BenchmarkRS512Signing-8 3273 355504 ns/op 32607 B/op 133 allocs/op ``` Benchmarks of signing methods ES384 and ES512 are omitted because their allocations are not consistent.
1 parent 76a236e commit fcd234c

File tree

1 file changed

+2
-6
lines changed

1 file changed

+2
-6
lines changed

token.go

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,14 +95,10 @@ func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token
9595

9696
// Encode JWT specific base64url encoding with padding stripped
9797
func EncodeSegment(seg []byte) string {
98-
return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=")
98+
return base64.RawURLEncoding.EncodeToString(seg)
9999
}
100100

101101
// Decode JWT specific base64url encoding with padding stripped
102102
func DecodeSegment(seg string) ([]byte, error) {
103-
if l := len(seg) % 4; l > 0 {
104-
seg += strings.Repeat("=", 4-l)
105-
}
106-
107-
return base64.URLEncoding.DecodeString(seg)
103+
return base64.RawURLEncoding.DecodeString(seg)
108104
}

0 commit comments

Comments
 (0)