gpt4 book ai didi

c# - 解码 Base64urlUInt 编码值

转载 作者:太空狗 更新时间:2023-10-30 01:16:43 30 4
gpt4 key购买 nike

我通常尝试做的是验证从 OpenID Connect 提供商(例如 Google)获得的 id_token 值。 token 使用 RSA 算法签名,公钥从 Discovery 中读取。文档(jwks_uri 参数)。例如,Google key 可用 here JWK 格式:

{
kty: "RSA",
alg: "RS256",
use: "sig",
kid: "38d516cbe31d4345819b786d4d227e3075df02fc",
n: "4fQxF6dFabDqsz9a9-XgVhDaadTBO4yBZkpUyUKrS98ZtpKIQRMLoph3bK9Cua828wwDZ9HHhUxOcbcUiNDUbubtsDz1AirWpCVRRauxRdRInejbGSqHMbg1bxWYfquKKQwF7WnrrSbgdInUZPv5xcHEjQ6q_Kbcsts1Nnc__8YRdmIGrtdTAcm1Ga8LfwroeyiF-2xn0mtWDnU7rblQI4qaXCwM8Zm-lUrpSUkO6E1RTJ1L0vRx8ieyLLOBzJNwxpIBNFolMK8-DYXDSX0SdR7gslInKCn8Ihd9mpI2QBuT-KFUi88t8TW4LsoWHAwlgXCRGP5cYB4r30NQ1wMiuQ",
e: "AQAB"
}

我将使用 RSACryptoServiceProvider用于解码签名的类。要初始化它,我必须提供 RSAParameters与模数和指数值。这些值是从上面的 JWK 中读取的,对应的是 ne。根据specification ,这些值是 Base64urlUInt 编码值:

The representation of a positive or zero integer value as thebase64url encoding of the value's unsigned big-endian representationas an octet sequence. The octet sequence MUST utilize the minimumnumber of octets needed to represent the value. Zero is representedas BASE64URL(single zero-valued octet), which is "AA".

所以,我的问题是如何解码这些值以将它们放入 RSAParameters?我尝试将它们解码为常见的 Base64url 字符串 (Convert.FromBase64String(modulusRaw)),但这显然不起作用并生成此错误:

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

最佳答案

RFC 7515像这样定义 base64url 编码:

Base64 encoding using the URL- and filename-safe character set defined in Section 5 of RFC 4648, with all trailing '=' characters omitted (as permitted by Section 3.2) and without the inclusion of any line breaks, whitespace, or other additional characters. Note that the base64url encoding of the empty octet sequence is the empty string. (See Appendix C for notes on implementing base64url encoding without padding.)

RFC 4648 将“使用 URL 和文件名安全字母表的 Base 64 编码”定义为常规 base64,但是:

  • 可以省略填充(就像这里一样)
  • 使用-代替+,使用_代替/

因此,要使用常规 Convert.FromBase64String,您只需反转该过程:

static byte[] FromBase64Url(string base64Url)
{
string padded = base64Url.Length % 4 == 0
? base64Url : base64Url + "====".Substring(base64Url.Length % 4);
string base64 = padded.Replace("_", "/")
.Replace("-", "+");
return Convert.FromBase64String(base64);
}

可能这段代码已经存在于框架中的某处,但我不知道。

关于c# - 解码 Base64urlUInt 编码值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34284810/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com