Esempio n. 1
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }

            var jwtHeader = new Dictionary <string, object> {
                { "alg", JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[] headerBytes = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));

            byte[] signature = HashAlgorithms[algorithm].Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payload, signature));
        }
Esempio n. 2
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }

            var jwtHeader = new Dictionary <string, object> {
                { "alg", JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[] headerBytes = Encoding.UTF8.GetBytes(GetSettings(settings).JsonMapper.Serialize(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));

            var jwsAlgorithm = GetSettings(settings).Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payload, signature));
        }
Esempio n. 3
0
        /// <summary>
        /// Encodes given binary data to JWT token and applies requested encryption/compression algorithms.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for encryption, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, encrypted and/or compressed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            IKeyManagement keys = KeyAlgorithms[alg];
            IJweAlgorithm  _enc = EncAlgorithms[enc];

            IDictionary <string, object> jwtHeader = new Dictionary <string, object> {
                { "alg", JweAlgorithms[alg] }, { "enc", JweEncryptionMethods[enc] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[][] contentKeys  = keys.WrapNewKey(_enc.KeySize, key, jwtHeader);
            byte[]   cek          = contentKeys[0];
            byte[]   encryptedCek = contentKeys[1];

            if (compression.HasValue)
            {
                jwtHeader["zip"] = JweCompressionMethods[compression.Value];
                payload          = CompressionAlgorithms[compression.Value].Compress(payload);
            }

            byte[]   header   = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));
            byte[]   aad      = Encoding.UTF8.GetBytes(Compact.Serialize(header));
            byte[][] encParts = _enc.Encrypt(aad, payload, cek);

            return(Compact.Serialize(header, encryptedCek, encParts[0], encParts[1], encParts[2]));
        }
Esempio n. 4
0
        /// <summary>
        /// Encodes given json string to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">json string to encode (not null or whitespace)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string Encode(string payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null.");

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }

            var jwtHeader = new Dictionary <string, object> {
                { "alg", JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[] headerBytes  = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));
            byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payloadBytes));

            byte[] signature = HashAlgorithms[algorithm].Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payloadBytes, signature));
        }
Esempio n. 5
0
        /// <summary>
        /// Encodes given json string to JWT token and applies requested encryption/compression algorithms.
        /// Json string to encode will be obtained via configured IJsonMapper implementation.
        /// </summary>
        /// <param name="payload">json string to encode (not null or whitespace)</param>
        /// <param name="key">key for encryption, suitable for provided JWS algorithm, can be null.</param>
        /// <returns>JWT in compact serialization form, encrypted and/or compressed.</returns>
        public static string Encode(string payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null)
        {
            Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null.");

            IKeyManagement keys = KeyAlgorithms[alg];
            IJweAlgorithm  _enc = EncAlgorithms[enc];

            IDictionary <string, object> jwtHeader = new Dictionary <string, object> {
                { "alg", JweAlgorithms[alg] }, { "enc", JweEncryptionMethods[enc] }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[][] contentKeys  = keys.WrapNewKey(_enc.KeySize, key, jwtHeader);
            byte[]   cek          = contentKeys[0];
            byte[]   encryptedCek = contentKeys[1];

            byte[] plainText = Encoding.UTF8.GetBytes(payload);

            if (compression.HasValue)
            {
                jwtHeader["zip"] = JweCompressionMethods[compression.Value];
                plainText        = CompressionAlgorithms[compression.Value].Compress(plainText);
            }

            byte[]   header   = Encoding.UTF8.GetBytes(jsMapper.Serialize(jwtHeader));
            byte[]   aad      = Encoding.UTF8.GetBytes(Compact.Serialize(header));
            byte[][] encParts = _enc.Encrypt(aad, plainText, cek);

            return(Compact.Serialize(header, encryptedCek, encParts[0], encParts[1], encParts[2]));
        }
Esempio n. 6
0
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }
            if (extraHeaders == null)
            {
                extraHeaders = new Dictionary <string, object>()
                {
                    { "typ", "JWT" }
                };
            }
            Dictionary <string, object> strs = new Dictionary <string, object>()
            {
                { "alg", JWT.JwsAlgorithms[algorithm] }
            };

            Dictionaries.Append <string, object>(strs, extraHeaders);
            byte[] bytes    = Encoding.UTF8.GetBytes(JWT.jsMapper.Serialize(strs));
            byte[] numArray = Encoding.UTF8.GetBytes(Compact.Serialize(new byte[][] { bytes, payload }));
            //SHA256 sha = SHA256.Create();
            //byte[] numArray1 = sha.ComputeHash(numArray);
            byte[] numArray1 = JWT.HashAlgorithms[algorithm].Sign(numArray, key);
            return(Compact.Serialize(new byte[][] { bytes, payload, numArray1 }));
        }
Esempio n. 7
0
        public static string EncodeBytes(byte[] payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException("payload");
            }
            IKeyManagement item               = JWT.KeyAlgorithms[alg];
            IJweAlgorithm  jweAlgorithm       = JWT.EncAlgorithms[enc];
            IDictionary <string, object> strs = new Dictionary <string, object>()
            {
                { "alg", JWT.JweAlgorithms[alg] },
                { "enc", JWT.JweEncryptionMethods[enc] }
            };

            Dictionaries.Append <string, object>(strs, extraHeaders);
            byte[][] numArray  = item.WrapNewKey(jweAlgorithm.KeySize, key, strs);
            byte[]   numArray1 = numArray[0];
            byte[]   numArray2 = numArray[1];
            if (compression.HasValue)
            {
                strs["zip"] = JWT.JweCompressionMethods[compression.Value];
                payload     = JWT.CompressionAlgorithms[compression.Value].Compress(payload);
            }
            byte[]   bytes     = Encoding.UTF8.GetBytes(JWT.jsMapper.Serialize(strs));
            byte[]   bytes1    = Encoding.UTF8.GetBytes(Compact.Serialize(new byte[][] { bytes }));
            byte[][] numArray3 = jweAlgorithm.Encrypt(bytes1, payload, numArray1);
            return(Compact.Serialize(new byte[][] { bytes, numArray2, numArray3[0], numArray3[1], numArray3[2] }));
        }
Esempio n. 8
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <param name="options">additional encoding options</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null, JwtOptions options = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            var jwtSettings = GetSettings(settings);
            var jwtOptions  = options ?? JwtOptions.Default;

            var jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwsHeaderValue(algorithm) }
            };

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }


            if (!jwtOptions.EncodePayload)
            {
                jwtHeader["b64"]  = false;
                jwtHeader["crit"] = Collections.Union(new[] { "b64" }, Dictionaries.Get <object>(extraHeaders, "crit"));
            }

            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));

            var jwsAlgorithm = jwtSettings.Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(securedInput(headerBytes, payload, jwtOptions.EncodePayload), key);


            byte[] payloadBytes = jwtOptions.DetachPayload ? new byte[0] : payload;


            return(jwtOptions.EncodePayload
                ? Compact.Serialize(headerBytes, payloadBytes, signature)
                : Compact.Serialize(headerBytes, Encoding.UTF8.GetString(payloadBytes), signature));
        }
Esempio n. 9
0
        /// <summary>
        /// Encodes given binary data to JWT token and applies requested encryption/compression algorithms.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for encryption, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="alg">JWT algorithm to be used.</param>
        /// <param name="enc">encryption algorithm to be used.</param>
        /// <param name="compression">optional compression type to use.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, encrypted and/or compressed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
                // nameof is not defined prior to c# 6.0 spec
                // throw new ArgumentNullException(nameof(payload));
                throw new ArgumentNullException("payload is null");
            }
            JwtSettings    jwtSettings = GetSettings(settings);
            IKeyManagement keys        = jwtSettings.Jwa(alg);
            IJweAlgorithm  _enc        = jwtSettings.Jwe(enc);

            if (keys == null)
            {
                throw new JoseException(string.Format("Unsupported JWA algorithm requested: {0}", alg));
            }

            if (_enc == null)
            {
                throw new JoseException(string.Format("Unsupported JWE algorithm requested: {0}", enc));
            }

            IDictionary <string, object> jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwaHeaderValue(alg) }, { "enc", jwtSettings.JweHeaderValue(enc) }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[][] contentKeys  = keys.WrapNewKey(_enc.KeySize, key, jwtHeader);
            byte[]   cek          = contentKeys[0];
            byte[]   encryptedCek = contentKeys[1];

            if (compression.HasValue)
            {
                jwtHeader["zip"] = jwtSettings.CompressionHeader(compression.Value);
                payload          = jwtSettings.Compression(compression.Value).Compress(payload);
            }

            byte[]   header   = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));
            byte[]   aad      = Encoding.UTF8.GetBytes(Compact.Serialize(header));
            byte[][] encParts = _enc.Encrypt(aad, payload, cek);

            return(Compact.Serialize(header, encryptedCek, encParts[0], encParts[1], encParts[2]));
        }
Esempio n. 10
0
        /// <summary>
        /// Encodes given binary data to JWT token and applies requested encryption/compression algorithms.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for encryption, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, encrypted and/or compressed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }
            JwtSettings    jwtSettings = GetSettings(settings);
            IKeyManagement keys        = jwtSettings.Jwa(alg);
            IJweAlgorithm  _enc        = jwtSettings.Jwe(enc);

            if (keys == null)
            {
                throw new JoseException(string.Format("Unsupported JWA algorithm requested: {0}", alg));
            }

            if (_enc == null)
            {
                throw new JoseException(string.Format("Unsupported JWE algorithm requested: {0}", enc));
            }

            IDictionary <string, object> jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwaHeaderValue(alg) }, { "enc", jwtSettings.JweHeaderValue(enc) }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);

            byte[][] contentKeys  = keys.WrapNewKey(_enc.KeySize, key, jwtHeader);
            byte[]   cek          = contentKeys[0];
            byte[]   encryptedCek = contentKeys[1];

            if (compression.HasValue)
            {
                jwtHeader["zip"] = JweCompressionMethods[compression.Value];
                payload          = jwtSettings.Compression(compression.Value).Compress(payload);
            }

            byte[]   header   = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));
            byte[]   aad      = Encoding.UTF8.GetBytes(Compact.Serialize(header));
            byte[][] encParts = _enc.Encrypt(aad, payload, cek);

            return(Compact.Serialize(header, encryptedCek, encParts[0], encParts[1], encParts[2]));
        }
Esempio n. 11
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
                // nameof is not defined prior to c# 6.0 spec
                // throw new ArgumentNullException(nameof(payload));
                throw new ArgumentNullException("payload is null");
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }
            var jwtSettings = GetSettings(settings);


            var jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwsHeaderValue(algorithm) }
            };

            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));

            var bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));

            var jwsAlgorithm = jwtSettings.Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(bytesToSign, key);

            return(Compact.Serialize(headerBytes, payload, signature));
        }
Esempio n. 12
0
        /// <summary>
        /// Encodes given binary data to JWT token and sign it using given algorithm.
        /// </summary>
        /// <param name="payload">Binary data to encode (not null)</param>
        /// <param name="key">key for signing, suitable for provided JWS algorithm, can be null.</param>
        /// <param name="algorithm">JWT algorithm to be used.</param>
        /// <param name="extraHeaders">optional extra headers to pass along with the payload.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>JWT in compact serialization form, digitally signed.</returns>
        public static string EncodeBytes(byte[] payload, object key, JwsAlgorithm algorithm, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null)
        {
            if (payload == null)
            {
                throw new ArgumentNullException(nameof(payload));
            }

            if (extraHeaders == null) //allow overload, but keep backward compatible defaults
            {
                extraHeaders = new Dictionary <string, object> {
                    { "typ", "JWT" }
                };
            }
            var jwtSettings = GetSettings(settings);


            var jwtHeader = new Dictionary <string, object> {
                { "alg", jwtSettings.JwsHeaderValue(algorithm) }
            };
            bool b64EncodePayload = true;

            if (extraHeaders.ContainsKey("b64"))
            {
                var b64Header = extraHeaders["b64"];
                if (b64Header != null && b64Header is bool)
                {
                    b64EncodePayload = (bool)b64Header;
                }
            }
            Dictionaries.Append(jwtHeader, extraHeaders);
            byte[] headerBytes = Encoding.UTF8.GetBytes(jwtSettings.JsonMapper.Serialize(jwtHeader));


            byte[] bytesToSign;
            if (b64EncodePayload)
            {
                bytesToSign = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes, payload));
            }
            else
            {
                var tmpBytes = Encoding.UTF8.GetBytes(Compact.Serialize(headerBytes) + ".");
                bytesToSign = new byte[tmpBytes.Length + payload.Length];
                System.Buffer.BlockCopy(tmpBytes, 0, bytesToSign, 0, tmpBytes.Length);
                System.Buffer.BlockCopy(payload, 0, bytesToSign, tmpBytes.Length, payload.Length);
            }

            var jwsAlgorithm = jwtSettings.Jws(algorithm);

            if (jwsAlgorithm == null)
            {
                throw new JoseException(string.Format("Unsupported JWS algorithm requested: {0}", algorithm));
            }

            byte[] signature = jwsAlgorithm.Sign(bytesToSign, key);

            if (b64EncodePayload)
            {
                return(Compact.Serialize(headerBytes, payload, signature));
            }
            else
            {
                return(Base64Url.Encode(headerBytes) + ".." + Base64Url.Encode(signature));
            }
        }