public void Ctor_Should_Not_Throw_Exception_When_PublicKeyHasNoPrivateKey() { var publicKey = _fixture.Create <RSACryptoServiceProvider>(); var algorithm = new RS256Algorithm(publicKey); algorithm.Should().NotBeNull(); }
public void HashAlgorithm_Should_Be_SHA256() { var publicKey = _fixture.Create <RSACryptoServiceProvider>(); var alg = new RS256Algorithm(publicKey); alg.HashAlgorithm.Should() .Be("SHA256"); }
public void Name_Should_Be_RS256() { var publicKey = _fixture.Create <RSACryptoServiceProvider>(); var alg = new RS256Algorithm(publicKey); alg.Name.Should() .Be(JwtAlgorithmName.RS256.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 RS256Algorithm(certificate); algorithm.Should().NotBeNull(); }
private static IJwtEncoder GetRS256JWTEncoder(RSACryptoServiceProvider csp) { var algorithm = new RS256Algorithm(publicKey: csp, privateKey: csp); // sending public key is not nesseccary but we have to to pass it. var serializer = new JsonNetSerializer(); var urlEncoder = new JwtBase64UrlEncoder(); var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder); }
public void Sign_Should_Throw_Exception_When_PrivateKey_Is_Null() { var publicKey = _fixture.Create <RSACryptoServiceProvider>(); var alg = new RS256Algorithm(publicKey); var bytesToSign = Array.Empty <byte>(); Action signWithoutPrivateKey = () => alg.Sign(null, bytesToSign); signWithoutPrivateKey.Should() .Throw <InvalidOperationException>("because asymmetric algorithm cannot sign data without private key"); }
private static IJwtEncoder GetRS256JWTEncoder(RSAParameters rsaParams) { var csp = new RSACryptoServiceProvider(); csp.ImportParameters(rsaParams); var algorithm = new RS256Algorithm(csp, csp); var serializer = new JsonNetSerializer(); var urlEncoder = new JwtBase64UrlEncoder(); var encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder); }
public void Initialize(Stream keyStream, string issuer) { using var reader = new PemReader(keyStream); var key = reader.ReadRsaKey(); var algorithm = new RS256Algorithm(RSA.Create(key), RSA.Create(key)); var serializer = new JsonNetSerializer(); var urlEncoder = new JwtBase64UrlEncoder(); _encoder = new JwtEncoder(algorithm, serializer, urlEncoder); _issuer = issuer; _initialized = true; }
public void Encode_and_Decode_With_Certificate() { using var rsa = RSA.Create(); rsa.FromXmlString(TestData.ServerRsaPrivateKey); using var certPub = new X509Certificate2(Encoding.ASCII.GetBytes(TestData.ServerRsaPublicKey2)); using var certPubPriv = new X509Certificate2(certPub.CopyWithPrivateKey(rsa).Export(X509ContentType.Pfx)); var builder = new JwtBuilder(); var algorithm = new RS256Algorithm(certPubPriv); const string iss = "test"; var exp = new DateTimeOffset(2038, 1, 19, 3, 14, 8, 0, TimeSpan.Zero).ToUnixTimeSeconds(); var token = builder.WithAlgorithm(algorithm) .AddHeader(HeaderName.KeyId, certPub.Thumbprint) .AddHeader(HeaderName.X5c, new[] { Convert.ToBase64String(certPub.Export(X509ContentType.Cert)) }) .AddClaim("iss", iss) .AddClaim("exp", exp) .AddClaim(nameof(Customer.FirstName), TestData.Customer.FirstName) .AddClaim(nameof(Customer.Age), TestData.Customer.Age) .Encode(); token.Should() .NotBeNullOrEmpty("because the token should contains some data"); token.Split('.') .Should() .HaveCount(3, "because the token should consist of three parts"); var header = builder.DecodeHeader <JwtHeader>(token); header.Type .Should() .Be("JWT"); header.Algorithm .Should() .Be("RS256"); header.KeyId .Should() .Be(TestData.ServerRsaPublicThumbprint1); var jwt = builder.WithAlgorithm(algorithm) .MustVerifySignature() .Decode <Dictionary <string, object> >(token); jwt["iss"].Should().Be(iss); jwt["exp"].Should().Be(exp); jwt[nameof(Customer.FirstName)].Should().Be(TestData.Customer.FirstName); jwt[nameof(Customer.Age)].Should().Be(TestData.Customer.Age); }
/// <summary> /// Generate custom signature verified Auth Token /// </summary> public string GenerateCustomToken() { var privateKey = TestConfiguration.FakeTokenPrivateKey; var header = new Dictionary <string, object> { { "x5t", "kg2LYs2T0CTjIfj4rt6JIynen38" }, { "kid", "kg2LYs2T0CTjIfj4rt6JIynen38" } }; var provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var tokenIssued = UnixEpoch.GetSecondsSince(now); var expiry = tokenIssued + 3600; var payload = new Dictionary <string, object> { { "aud", $"{EssauthConfig.EssClientId}" }, { "iss", $"https://sts.windows.net/{EssauthConfig.TenantId}/" }, { "iat", tokenIssued }, { "nbf", tokenIssued }, { "exp", expiry }, { "aio", "E2RgYPisIWqdtDHp72InvliZoLuf+m/cOdbklLQrIXRDxgPb23MB" }, { "appid", $"{EssauthConfig.AutoTestClientId}" }, { "appidacr", "1" }, { "idp", $"https://sts.windows.net/{EssauthConfig.TenantId}/" }, { "oid", "da599026-93fc-4d2a-92c8-94b724e26176" }, { "rh", "0.AAAASMo0kT1mBUqWijGkLwrtPjtAyT6ZgpBKjswH7mZCEJ8CAP0." }, { "roles", new string [] { "BatchCreate" } }, { "sub", "uftNZPaOJaWSYJqHrMIkFhg3rgQ97G9Km9fDl48WQPk" }, { "tid", "9134ca48-663d-4a05-968a-31a42f0aed3e" }, { "uti", "KOT0iQPMzESCe4R_Ce94AA" }, { "ver", "1.0" } }; var privateKeyBytes = Convert.FromBase64String(privateKey); using var rsa = RSA.Create(); rsa.ImportRSAPrivateKey(privateKeyBytes, out _); IJwtAlgorithm algorithm = new RS256Algorithm(rsa, rsa); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder.Encode(header, payload, "")); }
/// <summary> /// Generate custom B2C Token /// </summary> public string GenerateCustomToken() { var privateKey = TestConfiguration.FakeTokenPrivateKey; var header = new Dictionary <string, object> { { "typ", "JWT" }, { "kid", "GvnPApfWMdLRi8PDmisFn7bprKu" } }; var provider = new UtcDateTimeProvider(); var now = provider.GetNow(); var tokenIssued = UnixEpoch.GetSecondsSince(now); var expiry = tokenIssued + 3600; var payload = new Dictionary <string, object> { { "aud", $"{B2cConfig.TenantId}" }, { "iss", $"{B2cConfig.MicrosoftOnlineLoginUrl}{B2cConfig.TenantId}/v2.0/" }, { "iat", tokenIssued }, { "nbf", tokenIssued }, { "exp", expiry }, { "aio", "E2ZgYOD/bNfNzDaJjWGlunhesLAUAA==" }, { "azp", $"{B2cConfig.ClientId}" }, { "azpacr", "1" }, { "oid", "da599026-93fc-4d2a-92c8-94b724e26176" }, { "rh", "0.AT8A2Ihb28pF7EqgbHH88S3oGvAwypvZIDhLmevHr_a38FFAAAA." }, { "sub", "da599026-93fc-4d2a-92c8-94b724e26176" }, { "tid", $"{B2cConfig.TenantId}" }, { "uti", "C6oLcfz8e0mzZbv-6pRwAQ" }, { "ver", "2.0" } }; var privateKeyBytes = Convert.FromBase64String(privateKey); using var rsa = RSA.Create(); rsa.ImportRSAPrivateKey(privateKeyBytes, out _); IJwtAlgorithm algorithm = new RS256Algorithm(rsa, rsa); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); return(encoder.Encode(header, payload, "")); }
public void Test() { OutputHelper.WriteLine("this is xunit - OutputHelper"); RSA rsa = RSA.Create(); rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(publicKey), out _); RS256Algorithm algorithm = new RS256Algorithm(rsa); IDictionary <string, object> dictionary = JwtBuilder.Create() .WithAlgorithm(algorithm) // asymmetric .MustVerifySignature() .Decode <IDictionary <string, object> >(token); foreach (var key in dictionary.Keys) { object value = null; dictionary.TryGetValue(key, out value); OutputHelper.WriteLine("key=>{0}, value=>{1}", key, value); } //OutputHelper.WriteLine("dictionary=>{0}", dictionary); //new RS256Algorithm(); }
public string TesteJwt() { var header = new Header(); var paylod = new Payload() { uuid = "2", srcDateTime = DateTime.Now.ToString("yyyy-MM-dd'T'HH:mm:ssZ"), srcId = 123, srcAgencyNumber = "2568", srcAccountNumber = "5005565", srcClientName = "Ryoji", srcCpfCnpj = "885588999555", amount = 5058, urlConfirm = "http://google.com.br", withdrawStatus = "aprovado" }; var privateKey = new X509Certificate2("my-key.p12", "password", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet); var extraHeaders = new Dictionary <string, object> { { "partner", 0000 }, { "versionKey", 1 } }; IJwtAlgorithm algorithm = new RS256Algorithm(privateKey); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); var jsonWebToken = encoder.Encode(extraHeaders, paylod, privateKey.PrivateKey.ToString()); return(jsonWebToken); }
public static void Run() { var payload = new Dictionary <string, object> { { "claim1", 0 }, { "claim2", "claim2-value" } }; const string secret = "GQDstcKsx0NHjPOuXOYg5MbeJ1XT0uFiwDVvVBrk"; //Open the stream and read it back. byte[] message = System.Text.Encoding.Default.GetBytes("Hello!"); var token = ""; using (FileStream fs = File.OpenRead("C:/Users/Administrator/Desktop/rsatest/flw_srv_prv.pfx")) { byte[] blob = new byte[fs.Length]; fs.Read(blob, 0, blob.Length); X509Certificate2 certificate = new X509Certificate2(blob); var algorithm = new RS256Algorithm(certificate); //certificate.GetRSAPrivateKey().SignData(blob, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); IJsonSerializer serializer = new JsonNetSerializer(); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder); token = encoder.Encode(payload, secret); } //token = token + "dvcasvs"; using (FileStream fs = File.OpenRead("C:/Users/Administrator/Desktop/rsatest/flw_srv_prv_no_prvkey.pfx")) { byte[] blob = new byte[fs.Length]; fs.Read(blob, 0, blob.Length); X509Certificate2 certificate = new X509Certificate2(blob); var publicKey = certificate.GetRSAPublicKey(); var privateKey = certificate.GetRSAPrivateKey();// null var algorithm = new RS256Algorithm(publicKey); try { IJsonSerializer serializer = new JsonNetSerializer(); IDateTimeProvider provider = new UtcDateTimeProvider(); IJwtValidator validator = new JwtValidator(serializer, provider); IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder(); IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, new RSAlgorithmFactory(publicKey)); var json = decoder.Decode(token, secret, verify: false); JwtParts jwt = new JwtParts(token); var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(jwt.Header, ".", jwt.Payload)); byte[] signature = (new JwtBase64UrlEncoder()).Decode(jwt.Signature); var ttt = publicKey.VerifyData(bytesToSign, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); Console.WriteLine(json); } catch (TokenExpiredException) { Console.WriteLine("Token has expired"); } catch (SignatureVerificationException) { Console.WriteLine("Token has invalid signature"); } } }