5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Convert.FromBase64Stringがエラーになる

Last updated at Posted at 2020-08-12

状況

サーバ側で作成したJWTをGETパラメータとしてくっつけたURLをメール送信。
そのメールのURL叩いて取得したGETパラメータのJWTから[.]で分割した真ん中(Claims)の文字列をBase64デコードするとエラー。

string jwt = "jwt文字列"
Encoding enc = Encoding.GetEncoding("UTF-8");
var splits = jwt.Split('.');
return enc.GetString(Convert.FromBase64String(splits[1])); // FromBase64Stringでエラー

エラー内容

どうやら指定されている文字列が不正だと言われている。

Error in base64DecodeThe input is not a valid Base-64 string as it contains a non-base 64 character, 
more than two padding characters, or an illegal character among the padding characters.

ただ、生成されたJWTを見ても禁止文字は入っていないし、
そのまま文字列コピーでいろんなサイトでBase64デコードしてみたけどエラーでない。。。

原因

FromBase64Stringでは、4の倍数の文字数しか受け付けないらしい。。。(内部でやってくれよ。。。)
なので、文字数が4の倍数になるようにPaddingしてやったら上手くいきました。

string jwt = "jwt文字列"

Encoding enc = Encoding.GetEncoding("UTF-8");

var splits = jwt.Split('.');
for(int i = 0;i < (splits[1].Length % 4);i++) splits[1] += "=";

return enc.GetString(Convert.FromBase64String(splits[1]));
5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?