示例#1
0
        public void Build_BinaryJwt()
        {
            var builder = new JwtDescriptorBuilder();

            builder
            .EncryptWith(SymmetricJwk.GenerateKey(128), EncryptionAlgorithm.Aes128CbcHmacSha256, KeyManagementAlgorithm.Direct)
            .BinaryPayload(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });

            var descriptor = builder.Build();

            Assert.IsType <BinaryJweDescriptor>(descriptor);
            var binary = (BinaryJweDescriptor)descriptor;

            Assert.Equal(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, binary.Payload);

            Assert.Equal(KeyManagementAlgorithm.Direct, binary.Algorithm);
            Assert.Equal(EncryptionAlgorithm.Aes128CbcHmacSha256, binary.EncryptionAlgorithm);
        }
示例#2
0
        public void EncryptFast_Decrypt()
        {
            var data              = Encoding.UTF8.GetBytes("This is a test string for encryption.");
            var ciphertext        = new Span <byte>(new byte[data.Length]);
            var authenticationTag = new Span <byte>(new byte[16]);
            var plaintext         = new Span <byte>(new byte[data.Length]);
            var key       = SymmetricJwk.GenerateKey(EncryptionAlgorithm.A128Gcm);
            var nonce     = new byte[] { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
            var encryptor = new AesGcmEncryptor(EncryptionAlgorithm.A128Gcm);

            encryptor.Encrypt(key.AsSpan(), data, nonce, nonce, ciphertext, authenticationTag, out int tagSize);
            var  decryptor = new AesGcmDecryptor(EncryptionAlgorithm.A128Gcm);
            bool decrypted = decryptor.TryDecrypt(key.K, ciphertext, nonce, nonce, authenticationTag.Slice(0, tagSize), plaintext, out int bytesWritten);

            Assert.True(decrypted);
            Assert.Equal(16, tagSize);
            Assert.Equal(plaintext.Length, bytesWritten);
        }
示例#3
0
        public void Build_TextJwt()
        {
            var builder = new JwtDescriptorBuilder();

            builder
            .PlaintextPayload("Live long and prosper.")
            .EncryptWith(SymmetricJwk.GenerateKey(128), EncryptionAlgorithm.Aes128CbcHmacSha256, KeyManagementAlgorithm.Direct);

            var descriptor = builder.Build();

            Assert.IsType <PlaintextJweDescriptor>(descriptor);
            var plaintext = (PlaintextJweDescriptor)descriptor;

            Assert.Equal("Live long and prosper.", plaintext.Payload);

            Assert.Equal(KeyManagementAlgorithm.Direct, plaintext.Algorithm);
            Assert.Equal(EncryptionAlgorithm.Aes128CbcHmacSha256, plaintext.EncryptionAlgorithm);
        }
示例#4
0
        public void Contains()
        {
            var key128 = SymmetricJwk.GenerateKey(128);
            var key192 = SymmetricJwk.GenerateKey(192);
            var key256 = SymmetricJwk.GenerateKey(256);
            var key512 = SymmetricJwk.GenerateKey(512);

            var jwks = new Jwks("issuer1")
            {
                key128,
                key192,
                key256
            };

            Assert.Contains(key128, jwks);
            Assert.Contains(key192, jwks);
            Assert.Contains(key256, jwks);
            Assert.DoesNotContain(key512, jwks);
            Assert.DoesNotContain(null, jwks);
        }
示例#5
0
        public void JwsDescriptor_Ctor()
        {
            SymmetricJwk signingKey = SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256);

            Assert.Throws <ArgumentNullException>(() => new JwsDescriptor(null, SignatureAlgorithm.HS256));
            Assert.Throws <ArgumentNullException>(() => new JwsDescriptor(signingKey, null));

            var descriptor = new JwsDescriptor(signingKey, SignatureAlgorithm.HS256, "typ_value", "cty_value");

            Assert.Equal(signingKey, descriptor.SigningKey);
            Assert.Equal(SignatureAlgorithm.HS256, descriptor.Alg);
            Assert.True(descriptor.Header.TryGetValue("typ", out var typ));
            Assert.Equal("typ_value", (string)typ.Value);
            Assert.True(descriptor.Header.TryGetValue("cty", out var cty));
            Assert.Equal("cty_value", (string)cty.Value);

            var defaultDescriptor = new JwsDescriptor(signingKey, SignatureAlgorithm.HS256);

            Assert.False(defaultDescriptor.Header.TryGetValue("typ", out _));
            Assert.False(defaultDescriptor.Header.TryGetValue("cty", out _));
        }
示例#6
0
        public void Equal()
        {
            var key = SymmetricJwk.GenerateKey(128);

            Assert.True(key.Equals(key));
            Assert.Equal(key, key);
            var copiedKey = Jwk.FromJson(key.ToString());

            Assert.Equal(key, copiedKey);

            // 'kid' is not a discriminant, excepted if the value is different.
            copiedKey.Kid = default;
            Assert.Equal(key, copiedKey);
            Assert.Equal(copiedKey, key);
            key.Kid = default;
            Assert.Equal(key, copiedKey);
            key.Kid       = JsonEncodedText.Encode("X");
            copiedKey.Kid = JsonEncodedText.Encode("Y");
            Assert.NotEqual(key, copiedKey);

            Assert.NotEqual(key, Jwk.None);
        }
示例#7
0
        public void Remove()
        {
            var key128 = SymmetricJwk.GenerateKey(128);
            var key192 = SymmetricJwk.GenerateKey(192);
            var key256 = SymmetricJwk.GenerateKey(256);
            var key512 = SymmetricJwk.GenerateKey(512);

            var jwks = new Jwks("issuer1")
            {
                key128,
                key192,
                key256
            };

            Assert.Equal(3, jwks.Count);
            jwks.Remove(key192);
            Assert.Equal(2, jwks.Count);
            jwks.Remove(key512);
            Assert.Equal(2, jwks.Count);

            Assert.Throws <ArgumentNullException>(() => jwks.Remove(null));
        }
        private static JweWrapper CreateDescriptor(KeyManagementAlgorithm algorithm, EncryptionAlgorithm encryptionAlgorithm)
        {
            var jwk = algorithm.Category switch
            {
                Cryptography.AlgorithmCategory.None => Jwk.None,
                Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(EllipticalCurve.P256, algorithm),
                Cryptography.AlgorithmCategory.Rsa => RsaJwk.GeneratePrivateKey(4096, algorithm),
                Cryptography.AlgorithmCategory.Aes => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.AesGcm => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.Hmac => SymmetricJwk.GenerateKey(algorithm),
                Cryptography.AlgorithmCategory.Direct => SymmetricJwk.GenerateKey(encryptionAlgorithm),
                Cryptography.AlgorithmCategory.Direct | Cryptography.AlgorithmCategory.EllipticCurve => ECJwk.GeneratePrivateKey(EllipticalCurve.P256),
                _ => throw new InvalidOperationException(algorithm.Category.ToString())
            };

            var descriptor = new JweDescriptor(jwk, algorithm, encryptionAlgorithm)
            {
                Payload = new JwsDescriptor(Jwk.None, SignatureAlgorithm.None)
                {
                    Payload = new JwtPayload
                    {
                        { JwtClaimNames.Iat, EpochTime.UtcNow },
                        { JwtClaimNames.Exp, EpochTime.UtcNow + EpochTime.OneHour },
                        { JwtClaimNames.Iss, "https://idp.example.com/" },
                        { JwtClaimNames.Aud, "636C69656E745F6964" }
                    }
                }
            };
            var policy = new TokenValidationPolicyBuilder()
                         .AcceptUnsecureToken("https://idp.example.com/")
                         .WithDecryptionKey(jwk)
                         .Build();

            var writer = new JwtWriter();

            return(new JweWrapper(writer.WriteToken(descriptor), algorithm, encryptionAlgorithm, policy));
        }
    }
示例#9
0
        public void Build_Jwe()
        {
            var builder = new JwtDescriptorBuilder();

            var now = EpochTime.ToDateTime(EpochTime.UtcNow);

            builder
            .SignWith(RsaJwk.GenerateKey(2048, true, SignatureAlgorithm.RsaSsaPssSha256))
            .EncryptWith(SymmetricJwk.GenerateKey(128), EncryptionAlgorithm.Aes128CbcHmacSha256, KeyManagementAlgorithm.Direct)
            .IssuedBy("https://issuer.example.com")
            .ExpiresAt(now);

            var descriptor = builder.Build();

            Assert.IsType <JweDescriptor>(descriptor);
            var jwe = (JweDescriptor)descriptor;

            Assert.Equal("https://issuer.example.com", jwe.Payload.Issuer);
            Assert.Equal(now, jwe.Payload.ExpirationTime);
            Assert.Equal(SignatureAlgorithm.RsaSsaPssSha256, jwe.Payload.Algorithm);
            Assert.Equal(KeyManagementAlgorithm.Direct, jwe.Algorithm);
            Assert.Equal(EncryptionAlgorithm.Aes128CbcHmacSha256, jwe.EncryptionAlgorithm);
        }
示例#10
0
        static void Main()
        {
            // Generates the symmetric key for AES encryption with the algorithm 'A256GCMKW'
            var sharedEncryptionKey = SymmetricJwk.GenerateKey(KeyManagementAlgorithm.A256GcmKW);

            // Creates the symmetric key defined for the 'HS256' signature algorithm
            var signatureKey = SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256);

            // Creates the JWE descriptor
            // The descriptor sets the 'alg' with value 'A256GCMKW' and 'enc' with value 'A128CBC-HS256'
            var descriptor = new JweDescriptor(sharedEncryptionKey, KeyManagementAlgorithm.A256GcmKW, EncryptionAlgorithm.A256CbcHS512)
            {
                // Creates the JWS payload
                Payload = new JwsDescriptor(signatureKey, SignatureAlgorithm.HS256)
                {
                    Payload = new JwtPayload
                    {
                        // Defines the JWS claims
                        { JwtClaimNames.Iat, EpochTime.UtcNow },
                        { JwtClaimNames.Exp, EpochTime.UtcNow + EpochTime.OneHour },
                        { JwtClaimNames.Iss, "https://idp.example.com/" },
                        { JwtClaimNames.Aud, "636C69656E745F6964" }
                    }
                }
            };

            // Generates the UTF-8 string representation of the JWT
            var writer = new JwtWriter();
            var token  = writer.WriteTokenString(descriptor);

            Console.WriteLine("The JWT is:");
            Console.WriteLine(descriptor);
            Console.WriteLine();
            Console.WriteLine("Its compact form is:");
            Console.WriteLine(token);
        }
示例#11
0
文件: Tokens.cs 项目: watfordgnf/Jwt
 private static SymmetricJwk CreateSigningKey()
 {
     return(SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256));
 }
示例#12
0
 internal static SymmetricJwk CreateSymmetricKey(EncryptionAlgorithm encryptionAlgorithm, SymmetricJwk?staticKey)
 => staticKey ?? SymmetricJwk.GenerateKey(encryptionAlgorithm.RequiredKeySizeInBits, computeThumbprint: false);
        public void BuildPolicy()
        {
            const int ValidateSignature = 0x01;
            const int ValidateAudience  = 0x02;
            var       registry          = new AuditTrailHubRegistry();

            var reg1 = new AuditTrailHubRegistration("client1", SignatureAlgorithm.HS256, SymmetricJwk.GenerateKey(128));

            registry.Add(reg1);
            var policy = registry.BuildPolicy("uruk.example.com");

            Assert.Equal(ValidateSignature | ValidateAudience, policy.Control);
            Assert.Single(policy.RequiredAudiences, "uruk.example.com");

            var reg2 = new AuditTrailHubRegistration("client2", SignatureAlgorithm.RS256, "https://demo.identityserver.io/.well-known/openid-configuration/jwks");

            registry.Add(reg2);
            policy = registry.BuildPolicy("uruk.example.com");
            Assert.Equal(ValidateSignature | ValidateAudience, policy.Control);
            Assert.Single(policy.RequiredAudiences, "uruk.example.com");
        }
示例#14
0
        public void TryWrapKey_WithStaticKey_Throws(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var contentEncryptionKey = SymmetricJwk.GenerateKey(enc.RequiredKeySizeInBits);

            Assert.Throws <ArgumentException>(() => TryWrapKey_Success(contentEncryptionKey, enc, alg));
        }
示例#15
0
文件: Tokens.cs 项目: watfordgnf/Jwt
 private static SymmetricJwk CreateEncryptionKey()
 {
     return(SymmetricJwk.GenerateKey(KeyManagementAlgorithm.A128KW));
 }
        public void Ctor_ThrowException()
        {
            Assert.Throws <ArgumentNullException>(() => new AuditTrailHubRegistration(null !, SignatureAlgorithm.HS256, SymmetricJwk.GenerateKey(128)));
            Assert.Throws <ArgumentNullException>(() => new AuditTrailHubRegistration("client1", null !, SymmetricJwk.GenerateKey(128)));
            Assert.Throws <ArgumentNullException>(() => new AuditTrailHubRegistration("client1", SignatureAlgorithm.HS256, (Jwk)null !));

            Assert.Throws <ArgumentNullException>(() => new AuditTrailHubRegistration(null !, SignatureAlgorithm.HS256, "https://demo.identityserver.io/.well-known/openid-configuration/jwks"));
            Assert.Throws <ArgumentNullException>(() => new AuditTrailHubRegistration("client1", null !, "https://demo.identityserver.io/.well-known/openid-configuration/jwks"));
            Assert.Throws <ArgumentNullException>(() => new AuditTrailHubRegistration("client1", SignatureAlgorithm.HS256, (string)null !));
        }
示例#17
0
 public void TryWrapKey_WithStaticKey_Success(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     var contentEncryptionKey = SymmetricJwk.GenerateKey(enc.RequiredKeySizeInBits);
     Jwk cek = TryWrapKey_Success(contentEncryptionKey, enc, alg);
     Assert.Equal(contentEncryptionKey, cek);
 }
示例#18
0
        public void Descriptor_AllKindOfObject()
        {
            var descriptor = new JweDescriptor(SymmetricJwk.GenerateKey(256), KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = new JwsDescriptor(SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256), SignatureAlgorithm.HS256)
                {
                    Header = new JwtHeader
                    {
                        { "H1", "value1" },
                        { "H2", new Dictionary <string, object> {
                              { "prop1", "value2" }
                          } },
                        { "H3", 123L },
                        { "H4", new Fake {
                              Inner = new Fake {
                                  Value = "Inner1", Inner = new Fake {
                                      Value = "Inner2"
                                  }
                              }, Value = "Inner0"
                          } },
                        { "H5", new [] { "a", "b", "c" } },
                        { "H6", new [] { new object(), new object(), "abc", 123 } },
                        { "H7", true },
                        { "H8", false },
                    },
                    Payload = new JwtPayload
                    {
                        { "P1", "value1" },
                        { "P2", new Dictionary <string, object> {
                              { "prop1", "value2" }
                          } },
                        { "P3", 123L },
                        { "P4", new Fake {
                              Inner = new Fake {
                                  Value = "Inner1", Inner = new Fake {
                                      Value = "Inner2"
                                  }
                              }, Value = "Inner0"
                          } },
                        { "P5", new [] { "a", "b", "c" } },
                        { "P6", new [] { new object(), new object(), "abc", 123 } },
                        { "P7", true },
                        { "P8", false },
                    }
                }
            };

            Assert.True(descriptor.Payload.TryGetClaim("P1", out var claim));
            Assert.Equal(JwtValueKind.String, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P2", out claim));
            Assert.Equal(JwtValueKind.Object, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P3", out claim));
            Assert.Equal(JwtValueKind.Int64, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P4", out claim));
            Assert.Equal(JwtValueKind.Object, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P5", out claim));
            Assert.Equal(JwtValueKind.Array, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P6", out claim));
            Assert.Equal(JwtValueKind.Array, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P7", out claim));
            Assert.Equal(JwtValueKind.True, claim.Type);
            Assert.True(descriptor.Payload.TryGetClaim("P8", out claim));
            Assert.Equal(JwtValueKind.False, claim.Type);

            Assert.True(descriptor.Payload.Header.TryGetValue("alg", out var jwsHeaderParameter));
            Assert.Equal(JwtValueKind.JsonEncodedString, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("kid", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.JsonEncodedString, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H1", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.String, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H2", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Object, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H3", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Int64, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H4", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Object, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H5", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Array, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H6", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.Array, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H7", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.True, jwsHeaderParameter.Type);
            Assert.True(descriptor.Payload.Header.TryGetValue("H8", out jwsHeaderParameter));
            Assert.Equal(JwtValueKind.False, jwsHeaderParameter.Type);

            Assert.True(descriptor.Header.TryGetValue("kid", out var jweHeaderParameter));
            Assert.True(descriptor.Header.TryGetValue("alg", out jweHeaderParameter));
            Assert.Equal(KeyManagementAlgorithm.Dir.Name, ((JsonEncodedText)jweHeaderParameter.Value));
            Assert.True(descriptor.Header.TryGetValue("enc", out jweHeaderParameter));
            Assert.Equal(EncryptionAlgorithm.A128CbcHS256.Name, ((JsonEncodedText)jweHeaderParameter.Value));
            Assert.True(descriptor.Header.TryGetValue("zip", out jweHeaderParameter));
            Assert.Equal(CompressionAlgorithm.Def.Name, (JsonEncodedText)jweHeaderParameter.Value);

            PooledByteBufferWriter writer = new PooledByteBufferWriter();
            var context = new EncodingContext(writer, null, 0, false);

            descriptor.Encode(context);
        }
        public void BuilderFails()
        {
            var builder = new TokenValidationPolicyBuilder();

            Assert.Throws <ArgumentNullException>(() => builder.AddValidator(null));
            Assert.Throws <ArgumentOutOfRangeException>(() => builder.MaximumTokenSizeInBytes(-1));
            Assert.Throws <InvalidOperationException>(() => builder.RequireMetadataConfiguration("jwks_uri", SignatureAlgorithm.HS256));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignature("issuer", (Jwk)null, SignatureAlgorithm.HS256));
            Assert.Throws <InvalidOperationException>(() => builder.RequireSignature("issuer", SymmetricJwk.GenerateKey(128), (SignatureAlgorithm)null));

            Assert.Throws <ArgumentNullException>(() => builder.RequireSignature("issuer", (Jwks)null, SignatureAlgorithm.HS256));
            Assert.Throws <ArgumentException>(() => builder.RequireSignature("issuer", new StaticKeyProvider(new Jwks(SymmetricJwk.GenerateKey(128))), SignatureAlgorithm.None));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignature("issuer", new StaticKeyProvider(new Jwks(SymmetricJwk.GenerateKey(128))), (SignatureAlgorithm)null));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignature("issuer", (StaticKeyProvider)null, SignatureAlgorithm.HS256));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignature(null, new StaticKeyProvider(new Jwks(SymmetricJwk.GenerateKey(128))), SignatureAlgorithm.HS256));
            Assert.Throws <ArgumentNullException>(() => builder.IgnoreSignature(null));
            Assert.Throws <ArgumentNullException>(() => builder.AcceptUnsecureToken(null));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignatureByDefault((IKeyProvider)null));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignatureByDefault((Jwk)null));
            Assert.Throws <InvalidOperationException>(() => builder.RequireSignatureByDefault(SymmetricJwk.GenerateKey(128)));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignatureByDefault(SymmetricJwk.GenerateKey(128), (string)null));
            Assert.Throws <NotSupportedException>(() => builder.RequireSignatureByDefault(SymmetricJwk.GenerateKey(128), ""));
            Assert.Throws <NotSupportedException>(() => builder.RequireSignatureByDefault((Jwk)null, ""));
            Assert.Throws <ArgumentNullException>(() => builder.RequireSignatureByDefault((IList <Jwk>)null));
            Assert.Throws <ArgumentOutOfRangeException>(() => builder.EnableLifetimeValidation(clockSkew: -1));
            Assert.Throws <ArgumentNullException>(() => builder.RequireAudience((string)null));
            Assert.Throws <ArgumentNullException>(() => builder.RequireAudience((IEnumerable <string>)null));
            Assert.Throws <ArgumentNullException>(() => builder.DefaultIssuer(null));
            Assert.Throws <ArgumentNullException>(() => builder.EnableTokenReplayValidation(null));
            Assert.Throws <ArgumentNullException>(() => builder.RequireAlgorithm(null));
            Assert.Throws <ArgumentNullException>(() => builder.WithDecryptionKeys((ICollection <IKeyProvider>)null));
        }