Skip to content

Commit 5640558

Browse files
authored
Merge pull request GoogleCloudPlatform#179 from alvarowolfx/base64url-inline-sha256
fix: Use Base64url instead of Base64 and inline SHAS256 hash
2 parents 98fe430 + fb3d31d commit 5640558

File tree

1 file changed

+6
-20
lines changed

1 file changed

+6
-20
lines changed

src/jwt.cpp

Lines changed: 6 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
static const String base64_chars =
2525
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2626
"abcdefghijklmnopqrstuvwxyz"
27-
"0123456789+/";
27+
"0123456789-_";
2828

2929
String base64_encode(const unsigned char *bytes_to_encode,
3030
unsigned int in_len) {
@@ -66,10 +66,6 @@ String base64_encode(const unsigned char *bytes_to_encode,
6666
for (j = 0; (j < i + 1); j++) {
6767
ret += base64_chars[char_array_4[j]];
6868
}
69-
70-
while ((i++ < 3)) {
71-
ret += '=';
72-
}
7369
}
7470

7571
return ret;
@@ -79,19 +75,6 @@ String base64_encode(String str) {
7975
return base64_encode((const unsigned char *)str.c_str(), str.length());
8076
}
8177

82-
// Get's sha256 of str.
83-
String get_sha(const String& str) {
84-
Sha256 sha256Instance;
85-
86-
sha256Instance.update((const unsigned char *)str.c_str(), str.length());
87-
88-
unsigned char sha256[SHA256_DIGEST_LENGTH];
89-
90-
sha256Instance.final(sha256);
91-
92-
return String((const char*)sha256);
93-
}
94-
9578
// Get base64 signature string from the signature_r and signature_s ecdsa
9679
// signature.
9780
String MakeBase64Signature(NN_DIGIT *signature_r, NN_DIGIT *signature_s) {
@@ -122,7 +105,10 @@ String CreateJwt(String project_id, long long int time, NN_DIGIT *priv_key, int
122105
String header_payload_base64 =
123106
base64_encode(header) + "." + base64_encode(payload);
124107

125-
String sha256 = get_sha(header_payload_base64);
108+
Sha256 sha256Instance;
109+
sha256Instance.update((const unsigned char *)header_payload_base64.c_str(), header_payload_base64.length());
110+
unsigned char sha256[SHA256_DIGEST_LENGTH];
111+
sha256Instance.final(sha256);
126112

127113
// Signing sha with ec key. Bellow is the ec private key.
128114
point_t pub_key;
@@ -131,7 +117,7 @@ String CreateJwt(String project_id, long long int time, NN_DIGIT *priv_key, int
131117
ecdsa_init(&pub_key);
132118

133119
NN_DIGIT signature_r[NUMWORDS], signature_s[NUMWORDS];
134-
ecdsa_sign((uint8_t *)sha256.c_str(), signature_r, signature_s, priv_key);
120+
ecdsa_sign((uint8_t *)sha256, signature_r, signature_s, priv_key);
135121

136122
return header_payload_base64 + "." +
137123
MakeBase64Signature(signature_r, signature_s);

0 commit comments

Comments
 (0)