Пример #1
0
        public void Compatible(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var writer = new JwtWriter();

            foreach (var encryptionKey in SelectEncryptionKey(enc.Name.ToString(), alg.Name.ToString()))
            {
                var descriptor = new JweDescriptor(encryptionKey, alg, enc)
                {
                    Payload = new JwsDescriptor(_signingKey, SignatureAlgorithm.HS256)
                    {
                        Payload = new JwtPayload
                        {
                            { "sub", "Alice" }
                        }
                    }
                };

                var token = writer.WriteToken(descriptor);

                var policy = new TokenValidationPolicyBuilder()
                             .RequireSignatureByDefault(_signingKey)
                             .WithDecryptionKeys(_keys.Jwks)
                             .Build();

                var result = Jwt.TryParse(token, policy, out var jwt);
                Assert.True(result);
                Assert.True(jwt.Payload.TryGetClaim("sub", out var sub));
                Assert.Equal("Alice", sub.GetString());
                jwt.Dispose();
            }
        }
Пример #2
0
        public void Encode_Decode(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var writer = new JwtWriter();

            var descriptor = new JweDescriptor(_publicRsa2048Key, alg, enc)
            {
                Payload = new JwsDescriptor(_signingKey, SignatureAlgorithm.HS256)
                {
                    Payload = new JwtPayload
                    {
                        { "sub", "Alice" }
                    }
                }
            };

            var token = writer.WriteToken(descriptor);

            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignatureByDefault(_signingKey)
                         .WithDecryptionKey(_privateRsa2048Key)
                         .Build();

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

            Assert.True(result);
            Assert.True(jwt.Payload.TryGetClaim("sub", out var sub));
            Assert.Equal("Alice", sub.GetString());
            jwt.Dispose();
        }
 public JweWrapper(byte[] token, KeyManagementAlgorithm keyManagementAlgorithm, EncryptionAlgorithm encryptionAlgorithm, TokenValidationPolicy policy)
 {
     _token = token;
     _keyManagementAlgorithm = keyManagementAlgorithm;
     _encryptionAlgorithm    = encryptionAlgorithm;
     Policy = policy;
 }
Пример #4
0
        public void Encode_Decode(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var writer        = new JwtWriter();
            var encryptionKey = SelectKey(enc.Name, alg.Name);

            var descriptor = new JweDescriptor
            {
                EncryptionKey       = encryptionKey,
                EncryptionAlgorithm = enc,
                Algorithm           = alg,
                Payload             = new JwsDescriptor
                {
                    SigningKey = _signingKey,
                    Algorithm  = SignatureAlgorithm.HmacSha256,
                    Subject    = "Alice"
                }
            };

            var token = writer.WriteToken(descriptor);

            var reader = new JwtReader(encryptionKey);
            var policy = new TokenValidationPolicyBuilder()
                         .RequireSignature(_signingKey)
                         .Build();

            var result = reader.TryReadToken(token, policy);

            Assert.Equal(TokenValidationStatus.Success, result.Status);
            Assert.Equal("Alice", result.Token.Subject);
        }
Пример #5
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);
        }
Пример #6
0
        public RsaKeyWrapper(RsaJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(encryptionAlgorithm, algorithm)
        {
            Debug.Assert(key.SupportKeyManagement(algorithm));
            Debug.Assert(algorithm.Category == AlgorithmCategory.Rsa);
            _key = key;
#if SUPPORT_SPAN_CRYPTO
            _rsa = RSA.Create(key.ExportParameters());
#else
#if NET461 || NET47
            _rsa = new RSACng();
#else
            _rsa = RSA.Create();
#endif
            _rsa.ImportParameters(key.ExportParameters());
#endif
            _padding = algorithm.Id switch
            {
                AlgorithmId.RsaOaep => RSAEncryptionPadding.OaepSHA1,
                AlgorithmId.Rsa1_5 => RSAEncryptionPadding.Pkcs1,
                AlgorithmId.RsaOaep256 => RSAEncryptionPadding.OaepSHA256,
                AlgorithmId.RsaOaep384 => RSAEncryptionPadding.OaepSHA384,
                AlgorithmId.RsaOaep512 => RSAEncryptionPadding.OaepSHA512,
                _ => throw ThrowHelper.CreateNotSupportedException_AlgorithmForKeyWrap(algorithm)
            };
        }
        private static JweDescriptorWrapper 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" }
                    }
                }
            };

            return(new JweDescriptorWrapper(descriptor));
        }
Пример #8
0
                protected override SymmetricJwk GenerateKey(IConsole console)
                {
                    SymmetricJwk key;
                    var          stopwatch = new Stopwatch();

                    if (_keyLength != 0)
                    {
                        console.Verbose($@"Generating 'oct' JWK of {_keyLength} bits...");
                        stopwatch.Start();
                        key = SymmetricJwk.GenerateKey(_keyLength, computeThumbprint: !_noKid);
                    }
                    else if (SignatureAlgorithm.TryParse(_alg, out var signatureAlgorithm))
                    {
                        console.Verbose($@"Generating 'oct' JWK of {signatureAlgorithm.RequiredKeySizeInBits} bits for algorithm {signatureAlgorithm}...");
                        stopwatch.Start();
                        key = SymmetricJwk.GenerateKey(signatureAlgorithm, computeThumbprint: !_noKid);
                    }
                    else if (KeyManagementAlgorithm.TryParse(_alg, out var keyManagementAlgorithm))
                    {
                        console.Verbose($@"Generating 'oct' JWK of {keyManagementAlgorithm.RequiredKeySizeInBits} bits for algorithm {signatureAlgorithm}...");
                        stopwatch.Start();
                        key = SymmetricJwk.GenerateKey(keyManagementAlgorithm, computeThumbprint: !_noKid);
                    }
                    else
                    {
                        throw new InvalidOperationException("Unable to found the way to generate the key. Please specify a valid key length or a valid algorithm.");
                    }

                    console.Verbose($"JWK generated in {stopwatch.ElapsedMilliseconds} ms.");
                    if (_kid != null)
                    {
                        console.Verbose($"kid: {_kid}");
                        key.Kid = JsonEncodedText.Encode(_kid);
                    }
                    else if (!_noKid)
                    {
                        console.Verbose($"kid: {key.Kid}");
                    }

                    if (_use != null)
                    {
                        console.Verbose($"use: {_use}");
                        key.Use = JsonEncodedText.Encode(_use);
                    }

                    if (_keyOps != null && _keyOps.Count != 0)
                    {
                        console.Verbose($"key_ops: {string.Join(", ", _keyOps)}");
                        foreach (var keyOps in _keyOps)
                        {
                            if (keyOps != null)
                            {
                                key.KeyOps.Add(JsonEncodedText.Encode(keyOps));
                            }
                        }
                    }

                    return(key);
                }
Пример #9
0
        public void TryWrapKey_WithStaticKey_Success(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var contentEncryptionKey = ECJwk.GeneratePrivateKey(EllipticalCurve.P256);
            Jwk cek = TryWrapKey_Success(contentEncryptionKey, enc, alg);

            Assert.NotNull(cek);
            Assert.IsType <SymmetricJwk>(cek);
        }
Пример #10
0
        /// <summary>Initializes a new instance of the <see cref="KeyWrapper"/> class.</summary>
        protected KeyWrapper(EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
        {
            Debug.Assert(algorithm != null);
            Debug.Assert(encryptionAlgorithm != null);

            Algorithm           = algorithm;
            EncryptionAlgorithm = encryptionAlgorithm;
        }
Пример #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsymmetricJwk"/> class.
        /// </summary>
        protected AsymmetricJwk(string d, KeyManagementAlgorithm alg)
            : base(alg)
        {
            if (d is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.d);
            }

            D = Base64Url.Decode(d);
        }
Пример #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AsymmetricJwk"/> class.
        /// </summary>
        protected AsymmetricJwk(byte[] d, KeyManagementAlgorithm alg)
            : base(alg)
        {
            if (d is null)
            {
                ThrowHelper.ThrowArgumentNullException(ExceptionArgument.d);
            }

            D = d;
        }
Пример #13
0
        private Jwk TryWrapKey_Success(ECJwk keyToWrap, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            var keyEncryptionKey = ECJwk.GeneratePrivateKey(EllipticalCurve.P256);
            var wrapper          = new EcdhKeyWrapper(keyEncryptionKey, enc, alg);
            var cek = WrapKey(wrapper, keyToWrap, out var header);

            Assert.Equal(1, header.Count);
            Assert.True(header.ContainsKey("epk"));

            return(cek);
        }
Пример #14
0
        public void TryWrapKey_WithoutStaticKey_Success(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return;
            }

            Jwk cek = TryWrapKey_Success(null, enc, alg);

            Assert.NotNull(cek);
        }
Пример #15
0
        public void TryWrapKey_WithStaticKey_Success(EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
            {
                return;
            }

            var contentEncryptionKey = SymmetricJwk.GenerateKey(enc.RequiredKeySizeInBits);
            Jwk cek = TryWrapKey_Success(contentEncryptionKey, enc, alg);

            Assert.Equal(contentEncryptionKey, cek);
        }
Пример #16
0
        internal Pbes2KeyUnwrapper(PasswordBasedJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(encryptionAlgorithm, algorithm)
        {
            Debug.Assert(key.SupportKeyManagement(algorithm));
            Debug.Assert(algorithm.Category == AlgorithmCategory.Pbkdf2);
            Debug.Assert(algorithm.WrappedAlgorithm != null);
            Debug.Assert(algorithm.HashAlgorithm != null);

            _algorithm              = algorithm.Name;
            _keySizeInBytes         = algorithm.WrappedAlgorithm.RequiredKeySizeInBits >> 3;
            _algorithmNameLength    = _algorithm.EncodedUtf8Bytes.Length;
            _hashAlgorithm          = algorithm.HashAlgorithm;
            _keyManagementAlgorithm = algorithm.WrappedAlgorithm;
            _password = key.ToArray();
        }
Пример #17
0
        public EcdhKeyWrapper(ECJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm contentEncryptionAlgorithm)
            : base(key, encryptionAlgorithm, contentEncryptionAlgorithm)
        {
            if (contentEncryptionAlgorithm.WrappedAlgorithm is null)
            {
                _algorithmName  = encryptionAlgorithm.Utf8Name;
                _keySizeInBytes = encryptionAlgorithm.RequiredKeySizeInBytes;
            }
            else
            {
                _algorithmName  = contentEncryptionAlgorithm.Utf8Name;
                _keySizeInBytes = contentEncryptionAlgorithm.WrappedAlgorithm.RequiredKeySizeInBits >> 3;
            }

            _algorithmNameLength = _algorithmName.Length;
            _hashAlgorithm       = GetHashAlgorithm(encryptionAlgorithm);
        }
Пример #18
0
        public RsaKeyUnwrapper(RsaJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(encryptionAlgorithm, algorithm)
        {
            Debug.Assert(key.SupportKeyManagement(algorithm));
            Debug.Assert(algorithm.Category == AlgorithmCategory.Rsa);
#if SUPPORT_SPAN_CRYPTO
            _rsa = RSA.Create(key.ExportParameters());
#else
#if NET461 || NET47
            _rsa = new RSACng();
#else
            _rsa = RSA.Create();
#endif
            _rsa.ImportParameters(key.ExportParameters());
#endif
            _padding = RsaHelper.GetEncryptionPadding(algorithm.Id);
        }
Пример #19
0
        public Pbes2KeyWrapper(PasswordBasedJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm, uint iterationCount, uint saltSizeInBytes, ISaltGenerator saltGenerator)
            : base(encryptionAlgorithm, algorithm)
        {
            Debug.Assert(key.SupportKeyManagement(algorithm));
            Debug.Assert(algorithm.Category == AlgorithmCategory.Pbkdf2);
            Debug.Assert(algorithm.WrappedAlgorithm != null);
            Debug.Assert(algorithm.HashAlgorithm != null);

            _algorithm              = algorithm.Name;
            _keySizeInBytes         = algorithm.WrappedAlgorithm.RequiredKeySizeInBits >> 3;
            _algorithmNameLength    = _algorithm.EncodedUtf8Bytes.Length;
            _hashAlgorithm          = algorithm.HashAlgorithm;
            _keyManagementAlgorithm = algorithm.WrappedAlgorithm;
            _password        = key.ToArray();
            _iterationCount  = iterationCount;
            _saltSizeInBytes = (int)saltSizeInBytes;
            _saltGenerator   = saltGenerator;
        }
Пример #20
0
        public EcdhKeyWrapper(ECJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(encryptionAlgorithm, algorithm)
        {
            Debug.Assert(key.SupportKeyManagement(algorithm));
            Debug.Assert(algorithm.Category == AlgorithmCategory.EllipticCurve);
            _key = key;
            if (algorithm.WrappedAlgorithm is null)
            {
                _algorithm      = encryptionAlgorithm.Name;
                _keySizeInBytes = encryptionAlgorithm.RequiredKeySizeInBytes;
            }
            else
            {
                _algorithm              = algorithm.Name;
                _keySizeInBytes         = algorithm.WrappedAlgorithm.RequiredKeySizeInBits >> 3;
                _keyManagementAlgorithm = algorithm.WrappedAlgorithm;
            }

            _algorithmNameLength = _algorithm.EncodedUtf8Bytes.Length;
            _hashAlgorithm       = GetHashAlgorithm(encryptionAlgorithm);
        }
Пример #21
0
        public RsaKeyUnwrapper(RsaJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm contentEncryptionAlgorithm)
            : base(key, encryptionAlgorithm, contentEncryptionAlgorithm)
        {
#if SUPPORT_SPAN_CRYPTO
            _rsa = RSA.Create(key.ExportParameters());
#else
            _rsa = RSA.Create();
            _rsa.ImportParameters(key.ExportParameters());
#endif

            if (contentEncryptionAlgorithm == KeyManagementAlgorithm.RsaOaep)
            {
                _padding = RSAEncryptionPadding.OaepSHA1;
            }
            else if (contentEncryptionAlgorithm == KeyManagementAlgorithm.RsaPkcs1)
            {
                _padding = RSAEncryptionPadding.Pkcs1;
            }
            else if (contentEncryptionAlgorithm == KeyManagementAlgorithm.RsaOaep256)
            {
                _padding = RSAEncryptionPadding.OaepSHA256;
            }
            else if (contentEncryptionAlgorithm == KeyManagementAlgorithm.RsaOaep384)
            {
                _padding = RSAEncryptionPadding.OaepSHA384;
            }
            else if (contentEncryptionAlgorithm == KeyManagementAlgorithm.RsaOaep512)
            {
                _padding = RSAEncryptionPadding.OaepSHA512;
            }
            else
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(contentEncryptionAlgorithm);
                _padding = RSAEncryptionPadding.CreateOaep(new HashAlgorithmName()); // will never occur
            }
        }
Пример #22
0
 public AesGcmKeyUnwrapper(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
     : base(key, encryptionAlgorithm, algorithm)
 {
     ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
 }
Пример #23
0
        public AesKeyUnwrapper(SymmetricJwk key, EncryptionAlgorithm encryptionAlgorithm, KeyManagementAlgorithm algorithm)
            : base(key, encryptionAlgorithm, algorithm)
        {
            if (algorithm.Category != AlgorithmCategory.Aes)
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
            }

#if !NETSTANDARD2_0 && !NET461 && !NETCOREAPP2_1
            if (algorithm == KeyManagementAlgorithm.Aes128KW)
            {
                _decryptor = new Aes128NiCbcDecryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes256KW)
            {
                _decryptor = new Aes256NiCbcDecryptor(key.K);
            }
            else if (algorithm == KeyManagementAlgorithm.Aes192KW)
            {
                _decryptor = new Aes192NiCbcDecryptor(key.K);
            }
            else
            {
                ThrowHelper.ThrowNotSupportedException_AlgorithmForKeyWrap(algorithm);
                _decryptor = new Aes128NiCbcDecryptor(default);
Пример #24
0
 /// <summary>Initializes a new instance of the <see cref="JweDescriptor"/> class.</summary>
 public JweDescriptor(Jwk encryptionKey, KeyManagementAlgorithm alg, EncryptionAlgorithm enc, CompressionAlgorithm?zip = null, string?typ = null, string?cty = Constants.Jwt)
     : base(encryptionKey, alg, enc, zip, typ, cty)
 {
 }
Пример #25
0
 public virtual void IsSupportedKeyWrapping_Success(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     Assert.True(key.SupportKeyManagement(alg));
 }
Пример #26
0
        public virtual KeyWrapper CreateKeyWrapper_Failed(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
        {
            bool created = key.TryGetKeyWrapper(enc, alg, out var keyWrapper);

            _disposables.Add(keyWrapper);
            Assert.False(created);
            Assert.Null(keyWrapper);
            return(keyWrapper);
        }
Пример #27
0
 public override void IsSupportedKeyWrapping_Success(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     base.IsSupportedKeyWrapping_Success(key, enc, alg);
 }
Пример #28
0
 public EncryptedIdTokenDescriptor(Jwk encryptionKey, KeyManagementAlgorithm alg, EncryptionAlgorithm enc, CompressionAlgorithm?zip = null, string?typ = null, string?cty = null)
     : base(encryptionKey, alg, enc, zip, typ, cty)
 {
 }
Пример #29
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);
Пример #30
0
 public override KeyWrapper CreateKeyWrapper_Succeed(Jwk key, EncryptionAlgorithm enc, KeyManagementAlgorithm alg)
 {
     return(base.CreateKeyWrapper_Succeed(key, enc, alg));
 }