2

我正在尝试从 ASP.NET Core API 调用 Apple DeviceCheck API。为此,我需要创建一个 JWT。我为此使用 Jose 和 BouncyCastle 库。我尝试了 2 次不同的密钥创建,每次都从 DeviceCheck 开发 v1 API 返回 401(无法验证授权令牌)HTTP 状态。

private const string MembershipTeamId = "QWERTYUIOP";
private const string P8KeyId = "QWERTYUIOP";

public static string CreateJwt()
{
    var extraHeaders = new Dictionary<string, object>()
    {
        { "kid", P8KeyId },
        { "typ", "JWT" }
    };

    var payload = new Dictionary<string, object>()
    {
        { "iss", MembershipTeamId },
        { "iat", DateTimeOffset.UtcNow.ToUnixTimeSeconds() }
    };

    var key = GetCngKey();

    return JWT.Encode(payload, key, JwsAlgorithm.ES256, extraHeaders);
}

下面 2 种不同的方法,我尝试创建 CngKey

// using BouncyCastle
private static CngKey GetCngKey()
{
    using (var reader = System.IO.File.OpenText(@"C:\pathto\key.p8"))
    {
        var param = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
        return EccKey.New(
            param.Parameters.G.AffineXCoord.GetEncoded(),
            param.Parameters.G.AffineYCoord.GetEncoded(),
            param.D.ToByteArrayUnsigned());
    }
}

// using CngKey
private static CngKey GetCngKey2()
{
    var keyBytes = Convert.FromBase64String("inline .p8 content without -----BEGIN/END PRIVATE KEY-----");
    return CngKey.Import(keyBytes, CngKeyBlobFormat.Pkcs8PrivateBlob);
}
4

0 回答 0