public static string GenerateAppleToken(string secret, string keyId, string sub, string iss, string aud, DateTime expires) { ReadOnlySpan <byte> keyAsSpan = Convert.FromBase64String(secret); var prvKey = ECDsa.Create(); prvKey.ImportPkcs8PrivateKey(keyAsSpan, out var read); IJwtAlgorithm algorithm = new ES256Algorithm(ECDsa.Create(), prvKey); var tokenHandler = new JwtSecurityTokenHandler(); var securityKey = new ECDsaSecurityKey(prvKey); var tokenDescriptor = new SecurityTokenDescriptor { Expires = expires, Issuer = iss, Audience = aud, SigningCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.EcdsaSha256), Subject = new ClaimsIdentity(new[] { new Claim("sub", sub) }), }; var header = new Dictionary <string, object>() { { "kid", keyId } }; var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor); token.Header.Add("kid", keyId); return(tokenHandler.WriteToken(token)); }
public void HashAlgorithm_Should_Be_SHA256() { var publicKey = ECDsa.Create(); var alg = new ES256Algorithm(publicKey); alg.HashAlgorithm.Should() .Be("SHA256"); }
public void Name_Should_Be_ES256() { var publicKey = ECDsa.Create(); var alg = new ES256Algorithm(publicKey); alg.Name.Should() .Be(JwtAlgorithmName.ES256.ToString()); }
public void Ctor_Should_Not_Throw_Exception_When_Certificate_Has_No_PrivateKey(string publicKey) { var bytes = Encoding.ASCII.GetBytes(publicKey); var certificate = new X509Certificate2(bytes); var algorithm = new ES256Algorithm(certificate); algorithm.Should() .NotBeNull(); }
public void Sign_Should_Throw_Exception_When_PrivateKey_Is_Null() { var publicKey = ECDsa.Create(); var alg = new ES256Algorithm(publicKey); var bytesToSign = Array.Empty <byte>(); Action action = () => alg.Sign(null, bytesToSign); action.Should() .Throw <InvalidOperationException>("because asymmetric algorithm cannot sign data without private key"); }