Serialize() public static méthode

public static Serialize ( ) : string
Résultat string
Exemple #1
0
        private static byte[] DecryptBytes(Compact.Iterator parts, object key, JweAlgorithm?jweAlg, JweEncryption?jweEnc, JwtSettings settings = null)
        {
            byte[] header       = parts.Next();
            byte[] encryptedCek = parts.Next();
            byte[] iv           = parts.Next();
            byte[] cipherText   = parts.Next();
            byte[] authTag      = parts.Next();

            JwtSettings jwtSettings = GetSettings(settings);
            IDictionary <string, object> jwtHeader = jwtSettings.JsonMapper.Parse <Dictionary <string, object> >(Encoding.UTF8.GetString(header));

            JweAlgorithm  headerAlg = jwtSettings.JwaAlgorithmFromHeader((string)jwtHeader["alg"]);
            JweEncryption headerEnc = jwtSettings.JweAlgorithmFromHeader((string)jwtHeader["enc"]);

            IKeyManagement keys = jwtSettings.Jwa(headerAlg);
            IJweAlgorithm  enc  = jwtSettings.Jwe(headerEnc);

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

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

            if (jweAlg != null && (JweAlgorithm)jweAlg != headerAlg)
            {
                throw new InvalidAlgorithmException("The algorithm type passed to the Decrypt method did not match the algorithm type in the header.");
            }

            if (jweEnc != null && (JweEncryption)jweEnc != headerEnc)
            {
                throw new InvalidAlgorithmException("The encryption type passed to the Decrypt method did not match the encryption type in the header.");
            }

            byte[] cek = keys.Unwrap(encryptedCek, key, enc.KeySize, jwtHeader);
            byte[] aad = Encoding.UTF8.GetBytes(Compact.Serialize(header));

            byte[] plainText = enc.Decrypt(aad, cek, iv, cipherText, authTag);

            if (jwtHeader.ContainsKey("zip"))
            {
                var compression = jwtSettings.Compression((string)jwtHeader["zip"]);

                plainText = compression.Decompress(plainText);
            }

            return(plainText);
        }
Exemple #2
0
        /// <summary>
        /// Serialize token according to serialization mode
        /// </summary>
        public string AsString(IJsonMapper mapper = null)
        {
            if (Encoding == SerializationMode.Compact)
            {
                return(Compact.Serialize(ProtectedHeaderBytes, Recipients[0].EncryptedCek, Iv, Ciphertext, AuthTag));
            }

            var json = new Dictionary <string, object>()
            {
                { "ciphertext", Base64Url.Encode(Ciphertext) },
                { "protected", Base64Url.Encode(ProtectedHeaderBytes) },
                { "iv", Base64Url.Encode(Iv) },
                { "tag", Base64Url.Encode(AuthTag) }
            };

            if (Aad != null)
            {
                json["aad"] = Base64Url.Encode(Aad);
            }

            if (UnprotectedHeader != null)
            {
                json["unprotected"] = UnprotectedHeader;
            }


            if (Recipients.Count == 1)
            {
                json["header"]        = Recipients[0].Header;
                json["encrypted_key"] = Base64Url.Encode(Recipients[0].EncryptedCek);
            }
            else
            {
                var recipientList = new List <object>();


                foreach (var recipient in Recipients)
                {
                    recipientList.Add(
                        new Dictionary <string, object> {
                        { "header", recipient.Header },
                        { "encrypted_key", Base64Url.Encode(recipient.EncryptedCek) }
                    }
                        );
                }

                json["recipients"] = recipientList;
            }

            return(mapper.Serialize(json));
        }
Exemple #3
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));
        }
Exemple #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)
        {
            Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null.");

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

            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));
        }
Exemple #5
0
        private static byte[] DecodeBytes(string token, out byte[] cek, object key = null, JwsAlgorithm?expectedJwsAlg = null, JweAlgorithm?expectedJweAlg = null, JweEncryption?expectedJweEnc = null, JwtSettings settings = null)
        {
            Ensure.IsNotEmpty(token, "Incoming token expected to be in compact serialization form, not empty, whitespace or null.");

            byte[][] parts = Compact.Parse(token);
            cek = new byte[] {};

            if (parts.Length == 5) //encrypted JWT
            {
                return(DecryptBytes(parts, key, expectedJweAlg, expectedJweEnc, out cek, settings));
            }
            else
            {
                //signed or plain JWT
                byte[] header    = parts[0];
                byte[] payload   = parts[1];
                byte[] signature = parts[2];

                byte[] securedInput = Encoding.UTF8.GetBytes(Compact.Serialize(header, payload));

                var jwtSettings = GetSettings(settings);

                var headerData   = jwtSettings.JsonMapper.Parse <Dictionary <string, object> >(Encoding.UTF8.GetString(header));
                var algorithm    = (string)headerData["alg"];
                var jwsAlgorithm = jwtSettings.JwsAlgorithmFromHeader(algorithm);
                if (expectedJwsAlg != null && expectedJwsAlg != jwsAlgorithm)
                {
                    throw new InvalidAlgorithmException(
                              "The algorithm type passed to the Decode method did not match the algorithm type in the header.");
                }

                var jwsAlgorithmImpl = jwtSettings.Jws(jwsAlgorithm);

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

                if (!jwsAlgorithmImpl.Verify(signature, securedInput, key))
                {
                    throw new IntegrityException("Invalid signature.");
                }

                return(payload);
            }
        }
Exemple #6
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]));
        }
Exemple #7
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]));
        }
Exemple #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>
        /// <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));
        }
Exemple #9
0
        private static byte[] DecryptBytes(byte[][] parts, object key, JweAlgorithm?jweAlg, JweEncryption?jweEnc, JWTSettings settings = null)
        {
            byte[] header       = parts[0];
            byte[] encryptedCek = parts[1];
            byte[] iv           = parts[2];
            byte[] cipherText   = parts[3];
            byte[] authTag      = parts[4];

            IDictionary <string, object> jwtHeader = GetSettings(settings).JsonMapper.Parse <Dictionary <string, object> >(Encoding.UTF8.GetString(header));

            JweAlgorithm  headerAlg = GetJweAlgorithm((string)jwtHeader["alg"]);
            JweEncryption headerEnc = GetJweEncryption((string)jwtHeader["enc"]);

            IKeyManagement keys = GetSettings(settings).KeyAlgorithms[headerAlg];
            IJweAlgorithm  enc  = GetSettings(settings).EncAlgorithms[headerEnc];

            if (jweAlg != null && (JweAlgorithm)jweAlg != headerAlg)
            {
                throw new InvalidAlgorithmException("The algorithm type passed to the Decrypt method did not match the algorithm type in the header.");
            }

            if (jweEnc != null && (JweEncryption)jweEnc != headerEnc)
            {
                throw new InvalidAlgorithmException("The encryption type passed to the Decrypt method did not match the encryption type in the header.");
            }

            byte[] cek = keys.Unwrap(encryptedCek, key, enc.KeySize, jwtHeader);
            byte[] aad = Encoding.UTF8.GetBytes(Compact.Serialize(header));

            byte[] plainText = enc.Decrypt(aad, cek, iv, cipherText, authTag);

            if (jwtHeader.ContainsKey("zip"))
            {
                plainText = GetSettings(settings).CompressionAlgorithms[GetJweCompression((string)jwtHeader["zip"])].Decompress(plainText);
            }

            return(plainText);
        }
Exemple #10
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) }
            };

            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));
        }
Exemple #11
0
        private static byte[] DecodeBytes(string token, object key = null, JwsAlgorithm?jwsAlg = null, JweAlgorithm?jweAlg = null, JweEncryption?jweEnc = null)
        {
            Ensure.IsNotEmpty(token, "Incoming token expected to be in compact serialization form, not empty, whitespace or null.", new object[0]);
            byte[][] numArray = Compact.Parse(token);
            if ((int)numArray.Length == 5)
            {
                return(JWT.DecryptBytes(numArray, key, jweAlg, jweEnc));
            }
            byte[] numArray1 = numArray[0];
            byte[] numArray2 = numArray[1];
            byte[] numArray3 = numArray[2];
            byte[] bytes     = Encoding.UTF8.GetBytes(Compact.Serialize(new byte[][] { numArray1, numArray2 }));
            string item      = (string)JWT.jsMapper.Parse <Dictionary <string, object> >(Encoding.UTF8.GetString(numArray1))["alg"];

            if (jwsAlg.HasValue && jwsAlg.Value != JWT.GetHashAlgorithm(item))
            {
                throw new InvalidAlgorithmException("The algorithm type passed to the Decode method did not match the algorithm type in the header.");
            }
            if (!JWT.HashAlgorithms[JWT.GetHashAlgorithm(item)].Verify(numArray3, bytes, key))
            {
                throw new IntegrityException("Invalid signature.");
            }
            return(numArray2);
        }
Exemple #12
0
        private static byte[] DecodeBytes(string token, object key = null, JwsAlgorithm?expectedJwsAlg = null, JweAlgorithm?expectedJweAlg = null, JweEncryption?expectedJweEnc = null, JwtSettings settings = null)
        {
            Ensure.IsNotEmpty(token, "Incoming token expected to be in compact serialization form, not empty, whitespace or null.");

            if (token == null)
            {
                throw new ArgumentNullException(nameof(token));
            }

            string[] stringParts = token.Split('.');

            if (stringParts.Length == 5) //encrypted JWT
            {
                byte[][] parts = Compact.Parse(token);
                return(DecryptBytes(parts, key, expectedJweAlg, expectedJweEnc, settings));
            }
            else
            {
                //signed or plain JWT
                byte[] header = Base64Url.Decode(stringParts[0]);
                byte[] payload;
                byte[] signature           = Base64Url.Decode(stringParts[2]);
                bool   base64DecodePayload = GetBase64DecodeFlag(header);

                //Always base 64 decode paylod, even in b64=false detached since we have already attached the payload and encoded it
                payload = Base64Url.Decode(stringParts[1]);

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

                var jwtSettings = GetSettings(settings);

                var headerData   = jwtSettings.JsonMapper.Parse <Dictionary <string, object> >(Encoding.UTF8.GetString(header));
                var algorithm    = (string)headerData["alg"];
                var jwsAlgorithm = jwtSettings.JwsAlgorithmFromHeader(algorithm);
                if (expectedJwsAlg != null && expectedJwsAlg != jwsAlgorithm)
                {
                    throw new InvalidAlgorithmException(
                              "The algorithm type passed to the Decode method did not match the algorithm type in the header.");
                }

                var jwsAlgorithmImpl = jwtSettings.Jws(jwsAlgorithm);

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

                if (!jwsAlgorithmImpl.Verify(signature, securedInput, key))
                {
                    throw new IntegrityException("Invalid signature.");
                }

                return(payload);
            }
        }
Exemple #13
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));
            }
        }
Exemple #14
0
        /// <summary>
        /// Encrypts given binary plaintext using JWE and applies requested encryption/compression algorithms.
        /// </summary>
        /// <param name="plaintext">Binary data to encrypt (not null)</param>
        /// <param name="recipients">The details of who to encrypt the plaintext (or rather the CEK) to.</param>
        /// <param name="enc">encryption algorithm to be used to encrypt the plaintext.</param>
        /// <param name="aad">additional authentication data (SerializationMode.Json only)</param>
        /// <param name="mode">serialization mode to use. Note only one recipient can be specified for compact and flattened json serialization.</param>
        /// <param name="compression">optional compression type to use.</param>
        /// <param name="extraProtectedHeaders">optional extra headers to put in the protected header.</param>
        /// <param name="unprotectedHeaders">optional unprotected headers</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 EncryptBytes(byte[] plaintext, IEnumerable <JweRecipient> recipients, JweEncryption enc, byte[] aad = null, SerializationMode mode = SerializationMode.Json, JweCompression?compression = null, IDictionary <string, object> extraProtectedHeaders = null, IDictionary <string, object> unprotectedHeaders = null, JwtSettings settings = null)
        {
            if (plaintext == null)
            {
                throw new ArgumentNullException(nameof(plaintext));
            }

            settings = GetSettings(settings);
            IJweAlgorithm _enc = settings.Jwe(enc);

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

            IDictionary <string, object> joseProtectedHeader = Dictionaries.MergeHeaders(
                new Dictionary <string, object> {
                { "enc", settings.JweHeaderValue(enc) }
            },
                extraProtectedHeaders);

            byte[] cek = null;

            var recipientsOut = new List <JweRecipient>();

            foreach (var recipient in recipients)
            {
                IKeyManagement keys = settings.Jwa(recipient.Alg);

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

                // joseHeader - is merge of headers
                // - key management will read from (e.g. enc,apv,apu - ECDH-ES)
                // - key management will write to (e.g. iv, tag - AesGcmKW)
                IDictionary <string, object> joseHeader = Dictionaries.MergeHeaders(
                    joseProtectedHeader,
                    new Dictionary <string, object> {
                    { "alg", settings.JwaHeaderValue(recipient.Alg) }
                },
                    recipient.Header,
                    unprotectedHeaders
                    );

                byte[] encryptedCek;
                if (cek == null)
                {
                    byte[][] contentKeys = keys.WrapNewKey(_enc.KeySize, recipient.Key, joseHeader);
                    cek          = contentKeys[0];
                    encryptedCek = contentKeys[1];
                }
                else
                {
                    encryptedCek = keys.WrapKey(cek, recipient.Key, joseHeader);
                }

                // For the per-receipient header we want the headers from the result of IKeyManagements key wrapping but without the
                // shared headers
                IDictionary <string, object> recipientHeader = joseHeader
                                                               .Where(
                    kvp => !joseProtectedHeader.ContainsKey(kvp.Key) &&
                    (unprotectedHeaders == null || !unprotectedHeaders.ContainsKey(kvp.Key))
                    )
                                                               .ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

                recipientsOut.Add(new JweRecipient(encryptedCek, recipientHeader));
            }

            if (compression.HasValue)
            {
                joseProtectedHeader["zip"] = settings.CompressionHeader(compression.Value);
                plaintext = settings.Compression(compression.Value).Compress(plaintext);
            }

            switch (mode)
            {
            case SerializationMode.Compact:
            {
                if (recipientsOut.Count != 1)
                {
                    throw new JoseException("Only one recipient is supported by the JWE Compact Serialization.");
                }

                if (aad != null)
                {
                    throw new JoseException("JWE AAD value is not valid for JWE Compact Serialization.");
                }

                joseProtectedHeader = Dictionaries.MergeHeaders(recipientsOut[0].Header, joseProtectedHeader);

                byte[] header = Encoding.UTF8.GetBytes(settings.JsonMapper.Serialize(joseProtectedHeader));
                aad = Encoding.UTF8.GetBytes(Compact.Serialize(header));
                byte[][] encParts = _enc.Encrypt(aad, plaintext, cek);

                return(new JweToken(
                           header,
                           null,
                           recipientsOut,
                           null,
                           encParts[0],
                           encParts[1],
                           encParts[2],
                           mode)
                       .AsString());
            }

            case SerializationMode.Json:
            {
                var      protectedHeaderBytes        = Encoding.UTF8.GetBytes(settings.JsonMapper.Serialize(joseProtectedHeader));
                byte[]   asciiEncodedProtectedHeader = Encoding.ASCII.GetBytes(Base64Url.Encode(protectedHeaderBytes));
                byte[][] encParts = _enc.Encrypt(Aad(protectedHeaderBytes, aad), plaintext, cek);

                return(new JweToken(
                           protectedHeaderBytes,
                           unprotectedHeaders,
                           recipientsOut,
                           aad,
                           encParts[0],
                           encParts[1],
                           encParts[2],
                           mode)
                       .AsString(settings.JsonMapper));
            }

            default:
                throw new JoseException($"Unsupported serializtion mode: {mode}.");
            }
        }