Beispiel #1
0
        private static void ReadSymmetricKeyFromByteArray()
        {
            // The SymmetricJwk.FromBase64Url method accept a Base64-URL encoded string as input
            var binaryKey = new byte[32] {
                71, 211, 50, 89, 161, 40, 202, 35, 24, 86, 37, 86, 163, 193, 100, 225, 53, 6, 90, 36, 168, 105, 110, 148, 214, 115, 170, 94, 184, 188, 253, 117
            };
            var binarySymmetricKey = SymmetricJwk.FromByteArray(binaryKey);

            binarySymmetricKey.Kid = JsonEncodedText.Encode("binary");
            Console.WriteLine("JWK from byte array:");
            Console.WriteLine(binarySymmetricKey);
            Console.WriteLine();
        }
        public async Task TryStoreToken_ValidToken_SinkDown_ReturnsErrorResponse()
        {
            var key = SymmetricJwk.FromBase64Url("YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWE", false);

            key.Kid = JsonEncodedText.Encode("key1");
            var options = CreateOptions(key);
            var service = new AuditTrailHubService(new TestEventSink(response: false), options);

            var response = await service.TryStoreAuditTrail(new ReadOnlySequence <byte>(ValidToken), out var error);

            Assert.False(response);
            Assert.False(error !.Code.EncodedUtf8Bytes.IsEmpty);
            Assert.Null(error.Description);
        }
Beispiel #3
0
        private static void InterceptKeyRefreshedEvent()
        {
            Jwks.OnJwksRefreshed += OnKeysRefreshed;

            var jwks = new Jwks
            {
                SymmetricJwk.GenerateKey(128),
                SymmetricJwk.GenerateKey(128),
                SymmetricJwk.GenerateKey(128),
                SymmetricJwk.GenerateKey(128)
            };


            Jwks.PublishJwksRefreshed(new Jwks(), jwks);
        }
Beispiel #4
0
        public void Vakidate()
        {
            var key128 = SymmetricJwk.GenerateKey(128);
            var key192 = SymmetricJwk.GenerateKey(192);
            var key256 = SymmetricJwk.GenerateKey(256);

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

            jwks.Validate();
        }
Beispiel #5
0
        public void Build_Jws_NoneWithSigningKey()
        {
            var builder = new JwtDescriptorBuilder();

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

            builder
            .IssuedBy("https://issuer.example.com")
            .ExpiresAt(now)
            .SignWith(SymmetricJwk.GenerateKey(128), SignatureAlgorithm.None);

            var exception = Assert.Throws <InvalidOperationException>(() => builder.Build());

            Assert.Contains("The algorithm 'none' defined with a signing key.", exception.Message);
        }
Beispiel #6
0
        public void Build_Jws_MissingSigningAlgorithm()
        {
            var builder = new JwtDescriptorBuilder();

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

            builder
            .IssuedBy("https://issuer.example.com")
            .ExpiresAt(now)
            .SignWith(SymmetricJwk.GenerateKey(128));

            var exception = Assert.Throws <InvalidOperationException>(() => builder.Build());

            Assert.Contains("No algorithm is defined for the signature.", exception.Message);
        }
        public void Decrypt_Empty()
        {
            Span <byte> data = default;
            Span <byte> authenticationTag = default;
            var         plaintext         = new byte[0];
            var         key            = SymmetricJwk.FromByteArray(Encoding.UTF8.GetBytes("ThisIsA128bitKey" + "ThisIsA128bitKey"));
            Span <byte> nonce          = default;
            Span <byte> associatedData = default;
            var         decryptor      = new AesCbcHmacDecryptor(EncryptionAlgorithm.A128CbcHS256);

            bool decrypted = decryptor.TryDecrypt(key.K, data, nonce, associatedData, authenticationTag, plaintext, out int bytesWritten);

            Assert.False(decrypted);
            Assert.Equal(0, bytesWritten);
        }
Beispiel #8
0
        public void Descriptor_SetPayloadNull_ThrowsArgumentNullException()
        {
            var payload = new JwtPayload();

            for (int i = 0; i < 16; i++)
            {
                payload.Add(i.ToString(), i);
            }

            SymmetricJwk encryptionKey = SymmetricJwk.GenerateKey(EncryptionAlgorithm.A128CbcHS256);
            SymmetricJwk signatureKey  = SymmetricJwk.GenerateKey(SignatureAlgorithm.HS256);

            Assert.Throws <ArgumentNullException>(() =>
                                                  new JweDescriptor(encryptionKey, KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = null
            });

            Assert.Throws <ArgumentNullException>(() =>
                                                  new PlaintextJweDescriptor(encryptionKey, KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = null
            });

            Assert.Throws <ArgumentNullException>(() =>
                                                  new BinaryJweDescriptor(encryptionKey, KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = null
            });

            Assert.Throws <ArgumentNullException>(() =>
                                                  new JwkJweDescriptor(encryptionKey, KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = null
            });

            Assert.Throws <ArgumentNullException>(() =>
                                                  new JwksJweDescriptor(encryptionKey, KeyManagementAlgorithm.Dir, EncryptionAlgorithm.A128CbcHS256, CompressionAlgorithm.Def)
            {
                Payload = null
            });

            Assert.Throws <ArgumentNullException>(() =>
                                                  new JwsDescriptor(signatureKey, SignatureAlgorithm.HS256)
            {
                Payload = null
            });
        }
        public void Setup()
        {
            var key    = SymmetricJwk.GenerateKey(256);
            var rsaKey = RsaJwk.GeneratePrivateKey(2048);
            var ecKey  = ECJwk.GeneratePrivateKey(EllipticalCurve.P256);

            for (int i = 0; i < Count; i++)
            {
                key.TryGetSigner(SignatureAlgorithm.HS256, out var signer);
                id = i;
                _dictionary.Add(id, signer);
                _concurrentDictionary.TryAdd(id, signer);
                _cryptoStore.TryAdd(id, signer);
                _cryptoStore2.TryAdd(id, signer);
            }
        }
        public void Rfc7516_Decrypt()
        {
            Jwk    encryptionKey = SymmetricJwk.FromBase64Url("GawgguFyGrWKav7AX4VKUg");
            string token         = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.U0m_YmjN04DJvceFICbCVQ";

            var policy = new TokenValidationPolicyBuilder()
                         .WithDecryptionKey(encryptionKey)
                         .IgnoreSignatureByDefault()
                         .Build();

            var result = Jwt.TryParse(token, policy, out var jwt);

            Assert.True(result);
            Assert.Equal("Live long and prosper.", jwt.Plaintext);
            jwt.Dispose();
        }
Beispiel #11
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 + 16) & ~15]);
            var authenticationTag = new Span <byte>(new byte[64]);
            var plaintext         = new Span <byte>(new byte[data.Length]);
            var key       = SymmetricJwk.GenerateKey(512);
            var nonce     = new byte[] { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
            var encryptor = new AesCbcHmacEncryptor(key, EncryptionAlgorithm.Aes256CbcHmacSha512);

            encryptor.Encrypt(data, nonce, nonce, ciphertext, authenticationTag);
            var  decryptor = new AesCbcHmacDecryptor(key, EncryptionAlgorithm.Aes256CbcHmacSha512);
            bool decrypted = decryptor.TryDecrypt(ciphertext, nonce, nonce, authenticationTag, plaintext, out int bytesWritten);

            Assert.True(decrypted);
        }
Beispiel #12
0
        public void Build_JweMissingKeyManagementAlgorithm()
        {
            var builder = new JwtDescriptorBuilder();

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

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

            var exception = Assert.Throws <InvalidOperationException>(() => builder.Build());

            Assert.Contains("No algorithm is defined for the key management encryption.", exception.Message);
        }
 public static IHostBuilder CreateHostBuilder(string[] args)
 {
     return(Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
     {
         services
         .AddHostedService <Worker>()
         .AddAuditTrailClient(options =>
         {
             options.DeliveryEndpoint = "https://localhost:5001/events";
             options.TemporaryStorageEncryptionKey = SymmetricJwk.FromByteArray(new byte[32]);
             options.TokenClientOptions.Address = "https://demo.identityserver.io/connect/token";
             options.TokenClientOptions.ClientId = "m2m";
             options.TokenClientOptions.ClientSecret = "secret";
         });
     }));
 }
        public void Ctor_InitializeProperties()
        {
            var key  = SymmetricJwk.GenerateKey(128);
            var reg1 = new AuditTrailHubRegistration("client1", SignatureAlgorithm.HS256, key);

            Assert.Equal("client1", reg1.Issuer);
            Assert.Equal(key, reg1.Jwk);
            Assert.Null(reg1.JwksUri);
            Assert.Equal(SignatureAlgorithm.HS256, reg1.SignatureAlgorithm);

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

            Assert.Equal("client2", reg2.Issuer);
            Assert.Null(reg2.Jwk);
            Assert.Equal("https://demo.identityserver.io/.well-known/openid-configuration/jwks", reg2.JwksUri);
            Assert.Equal(SignatureAlgorithm.ES256, reg2.SignatureAlgorithm);
        }
Beispiel #15
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 + 16) & ~15]);
            var authenticationTag = new Span <byte>(new byte[48]);
            var plaintext         = new Span <byte>(new byte[data.Length]);
            var key       = SymmetricJwk.GenerateKey(386);
            var nonce     = new byte[] { 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1 };
            var encryptor = new AesCbcHmacEncryptor(EncryptionAlgorithm.A192CbcHS384);

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

            Assert.True(decrypted);
            Assert.Equal(24, tagSize);
        }
Beispiel #16
0
        public void WrapKey_Failure()
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return;
            }

            var keyEncryptionKey     = SymmetricJwk.GenerateKey(256);
            var contentEncryptionKey = SymmetricJwk.GenerateKey(256);
            var wrapper     = new AesGcmKeyWrapper(keyEncryptionKey, EncryptionAlgorithm.A256Gcm, KeyManagementAlgorithm.A256GcmKW);
            var destination = Array.Empty <byte>();
            var header      = new JwtHeader();

            Assert.Throws <ArgumentException>(() => wrapper.WrapKey(contentEncryptionKey, header, destination));

            Assert.Equal(0, header.Count);
        }
Beispiel #17
0
        /// <inheritsdoc />
        public override bool TryUnwrapKey(ReadOnlySpan <byte> keyBytes, Span <byte> destination, JwtHeader header, out int bytesWritten)
        {
            if (_disposed)
            {
                ThrowHelper.ThrowObjectDisposedException(GetType());
            }

            var epk = header.Epk;

            if (epk is null)
            {
                ThrowHelper.ThrowJwtDescriptorException_HeaderIsRequired(HeaderParameters.EpkUtf8);
            }

            byte[] secretAppend = BuildSecretAppend(header.Apu, header.Apv);
            byte[] exchangeHash;
            using (var ephemeralKey = ECDiffieHellman.Create(epk.ExportParameters()))
                using (var privateKey = ECDiffieHellman.Create(((ECJwk)Key).ExportParameters(true)))
                {
                    if (ephemeralKey.KeySize != privateKey.KeySize)
                    {
                        return(ThrowHelper.TryWriteError(out bytesWritten));
                    }

                    exchangeHash = privateKey.DeriveKeyFromHash(ephemeralKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend);
                }

            if (Algorithm.ProduceEncryptionKey)
            {
                using var key = SymmetricJwk.FromSpan(new ReadOnlySpan <byte>(exchangeHash, 0, _keySizeInBytes), false);
                if (key.TryGetKeyUnwrapper(EncryptionAlgorithm, Algorithm.WrappedAlgorithm, out var keyUnwrapper))
                {
                    return(keyUnwrapper.TryUnwrapKey(keyBytes, destination, header, out bytesWritten));
                }
                else
                {
                    return(ThrowHelper.TryWriteError(out bytesWritten));
                }
            }
            else
            {
                new ReadOnlySpan <byte>(exchangeHash, 0, _keySizeInBytes).CopyTo(destination);
                bytesWritten = destination.Length;
                return(true);
            }
        }
Beispiel #18
0
        static void Main()
        {
            // This sample demonstrates how to validate a token that may come form different issuers.
            // This is common if you have to support multiple Authorization Servers.
            var keyIssuer1    = new SymmetricJwk("R9MyWaEoyiMYViVWo8Fk4TUGWiSoaW6U1nOqXri8_XU");
            var policyIssuer1 = new TokenValidationPolicyBuilder()
                                .RequireSignature(keyIssuer1, SignatureAlgorithm.HmacSha256)
                                .RequireAudience("636C69656E745F6964")
                                .RequireIssuer("https://idp1.example.com/")
                                .Build();

            var keyIssuer2    = new SymmetricJwk("9dobXhxMWH9PoLsKRdv1qp0bEqJm4YNd8JRaTxes8i4");
            var policyIssuer2 = new TokenValidationPolicyBuilder()
                                .RequireSignature(keyIssuer2, SignatureAlgorithm.HmacSha256)
                                .RequireAudience("9656E745F6964636C6")
                                .RequireIssuer("https://idp2.example.com/")
                                .Build();

            var keyIssuer3    = new SymmetricJwk("lh2TJcMdPyNLhfNp0nYLAFM_R0UEXVoZ9N7ife4ZT-A");
            var policyIssuer3 = new TokenValidationPolicyBuilder()
                                .RequireSignature(keyIssuer3, SignatureAlgorithm.HmacSha256)
                                .RequireAudience("F6964636C69656E745")
                                .RequireIssuer("https://idp3.example.com/")
                                .Build();

            var policies = new[] { policyIssuer1, policyIssuer2, policyIssuer3 };

            var reader = new JwtReader();
            var token  = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDAwMDcyMDAsImlhdCI6MjAwMDAwNzIwMCwiaXNzIjoiaHR0cHM6Ly9pZHAzLmV4YW1wbGUuY29tLyIsImF1ZCI6IkY2OTY0NjM2QzY5NjU2RTc0NSJ9.a6RiTht8kyTDL9SZVX9kUye7dJL9YSZxJPbAyaaw3QE";

            for (int i = 0; i < policies.Length; i++)
            {
                // Try to read the token with the different policies
                var result = reader.TryReadToken(token, policies[i]);
                if (result.Succedeed)
                {
                    Console.WriteLine($"The token is issued by '{result.Token.Issuer}':");
                    Console.WriteLine(result.Token);
                    break;
                }

                Console.WriteLine($"Failed to read the token for the issuer '{policies[i].RequiredIssuer}'.");
                Console.WriteLine("  Reason: " + result.Status);
            }
        }
        public void Encrypt_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);
        }
Beispiel #20
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);
        }
Beispiel #21
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);
        }
Beispiel #22
0
 private static IHostBuilder CreateHostBuilder(TestHttpMessageHandler handler)
 {
     return(Host.CreateDefaultBuilder()
            .ConfigureServices((hostContext, services) =>
     {
         services
         .AddAuditTrailClient(o =>
         {
             o.DeliveryEndpoint = "https://example.com/events/";
             o.TemporaryStorageEncryptionKey = SymmetricJwk.FromByteArray(new byte[32]);
         })
         .ConfigurePrimaryHttpMessageHandler(() => handler)
         .ConfigureHttpClient(builder =>
         {
         });
         services.Replace(new ServiceDescriptor(typeof(IAccessTokenAcquirer), typeof(NullTokenAcquirer), ServiceLifetime.Singleton));
     }));
 }
 public void EncryptSimd_Decrypt(string value)
 {
     if (System.Runtime.Intrinsics.X86.Aes.IsSupported)
     {
         var data              = Encoding.UTF8.GetBytes(value);
         var ciphertext        = new Span <byte>(new byte[(data.Length + 16) & ~15]);
         var authenticationTag = new Span <byte>(new byte[32]);
         var plaintext         = new Span <byte>(new byte[ciphertext.Length]);
         var key         = SymmetricJwk.FromByteArray(Encoding.UTF8.GetBytes("ThisIsA128bitKey" + "ThisIsA128bitKey"));
         var nonce       = Encoding.UTF8.GetBytes("ThisIsAnInitVect");
         var encryptorNi = new AesCbcHmacEncryptor(EncryptionAlgorithm.A128CbcHS256, new Aes128CbcEncryptor());
         encryptorNi.Encrypt(key.K, data, nonce, nonce, ciphertext, authenticationTag, out int tagSize);
         var  decryptor = new AesCbcHmacDecryptor(EncryptionAlgorithm.A128CbcHS256);
         bool decrypted = decryptor.TryDecrypt(key.K, ciphertext, nonce, nonce, authenticationTag.Slice(0, tagSize), plaintext, out int bytesWritten);
         Assert.True(decrypted, "decrypted");
         Assert.Equal(data, plaintext.Slice(0, bytesWritten).ToArray());
         Assert.Equal(16, tagSize);
     }
 }
Beispiel #24
0
        public AesKeyWrapper(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(key, encryptionAlgorithm, algorithm)
        {
#if SUPPORT_SIMD
            if (algorithm == KeyManagementAlgorithm.Aes128KW)
            {
                _encryptor = new Aes128NiCbcEncryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes256KW)
            {
                _encryptor = new Aes256NiCbcEncryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes192KW)
            {
                _encryptor = new Aes192NiCbcEncryptor(key.K);
            }
            else
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
                _encryptor = new Aes128NiCbcEncryptor(default);
Beispiel #25
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);
        }
Beispiel #26
0
        /// <inheritsdoc />
        public override SymmetricJwk WrapKey(Jwk?staticKey, JwtHeader header, Span <byte> destination)
        {
            Debug.Assert(header != null);

            var partyUInfo   = GetPartyInfo(header, JwtHeaderParameterNames.Apu);
            var partyVInfo   = GetPartyInfo(header, JwtHeaderParameterNames.Apv);
            var secretAppend = BuildSecretAppend(partyUInfo, partyVInfo);
            ReadOnlySpan <byte> exchangeHash;
            var             ecKey         = _key;
            var             otherPartyKey = ecKey.CreateEcdhKey();
            ECDiffieHellman ephemeralKey  = (staticKey is null) ? ECDiffieHellman.Create(ecKey.Crv.CurveParameters) : ((ECJwk)staticKey).CreateEcdhKey();

            try
            {
                exchangeHash = new ReadOnlySpan <byte>(ephemeralKey.DeriveKeyFromHash(otherPartyKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend), 0, _keySizeInBytes);
                var epk = ECJwk.FromParameters(ephemeralKey.ExportParameters(false));
                header.Add(JwtHeaderParameterNames.Epk, epk);
            }
            finally
            {
                if (staticKey is null)
                {
                    ephemeralKey.Dispose();
                }
            }

            SymmetricJwk contentEncryptionKey;

            if (Algorithm.ProduceEncryptionKey)
            {
                using var keyWrapper = new AesKeyWrapper(exchangeHash, EncryptionAlgorithm, _keyManagementAlgorithm !);
                contentEncryptionKey = keyWrapper.WrapKey(null, header, destination);
            }
            else
            {
                exchangeHash.CopyTo(destination);
                contentEncryptionKey = SymmetricJwk.FromSpan(exchangeHash, false);
            }

            return(contentEncryptionKey);
        }
Beispiel #27
0
        private async Task <Jwk[]> GetKeysAsync()
        {
            var keys = new List <Jwk>();

            await foreach (var keyProperties in _client.GetPropertiesOfKeysAsync())
            {
                var kvKey = await _client.GetKeyAsync(keyProperties.Name);

                Jwk?key = null;
                if (kvKey.Value.KeyType == KeyType.Oct)
                {
                    key = SymmetricJwk.FromByteArray(kvKey.Value.Key.K, false);
                }
                else if (kvKey.Value.KeyType == KeyType.Rsa || kvKey.Value.KeyType == KeyType.RsaHsm)
                {
                    key = RsaJwk.FromParameters(kvKey.Value.Key.ToRSA(true).ExportParameters(true), false);
                }
#if !NETFRAMEWORK
                else if (kvKey.Value.KeyType == KeyType.Ec || kvKey.Value.KeyType == KeyType.EcHsm)
                {
                    ECJwk.FromParameters(ConvertToECParameters(kvKey.Value), computeThumbprint: false);
                }
#endif

                if (!(key is null))
                {
                    key.Kid = JsonEncodedText.Encode(kvKey.Value.Key.Id);
                    if (kvKey.Value.Key.KeyOps != null)
                    {
                        foreach (var operation in kvKey.Value.Key.KeyOps)
                        {
                            key.KeyOps.Add(JsonEncodedText.Encode(operation.ToString()));
                        }
                    }

                    keys.Add(key);
                }
            }

            return(keys.ToArray());
        }
Beispiel #28
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 _));
        }
Beispiel #29
0
        static void Main()
        {
            var key    = new SymmetricJwk("R9MyWaEoyiMYViVWo8Fk4TUGWiSoaW6U1nOqXri8_XU");
            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignature(key, SignatureAlgorithm.HmacSha256)
                         .RequireAudience("636C69656E745F6964")
                         .RequireIssuer("https://idp.example.com/")
                         .Build();

            var reader = new JwtReader();
            var result = reader.TryReadToken("eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDAwMDcyMDAsImlhdCI6MjAwMDAwNzIwMCwiaXNzIjoiaHR0cHM6Ly9pZHAuZXhhbXBsZS5jb20vIiwiYXVkIjoiNjM2QzY5NjU2RTc0NUY2OTY0In0.YrrT1Ddp1ampsDd2GwYZoTz_bUnLt_h--f16wsWBedk", policy);

            if (result.Succedeed)
            {
                Console.WriteLine("The token is " + result.Token);
            }
            else
            {
                Console.WriteLine("Failed to read the token. Reason: " + Environment.NewLine + result.Status);
            }
        }
Beispiel #30
0
        static void Main()
        {
            // Creates a symmetric key for encryption
            var encryptionKey = SymmetricJwk.FromBase64Url("R9MyWaEoyiMYViVWo8Fk4T");

            // Creates a JWE descriptor with all its properties
            var descriptor = new PlaintextJweDescriptor(encryptionKey, KeyManagementAlgorithm.A128KW, EncryptionAlgorithm.A128CbcHS256)
            {
                Payload = "Life long and prosper."
            };

            // 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);
        }