コード例 #1
0
        private static JweToken ParseJson(IDictionary <string, object> json)
        {
            var recipients = new List <JweRecipient>();

            IEnumerable _recipients = Dictionaries.Get <IEnumerable>(json, "recipients");

            if (_recipients != null)
            {
                foreach (IDictionary <string, object> recipient in _recipients)
                {
                    byte[] encryptedCek = Base64Url.Decode(Dictionaries.Get <string>(recipient, "encrypted_key"));
                    recipients.Add(new JweRecipient(encryptedCek, Dictionaries.Get <IDictionary <string, object> >(recipient, "header")));
                }
            }
            else if (recipients.Count == 0)
            {
                byte[] encryptedCek = Base64Url.Decode(Dictionaries.Get <string>(json, "encrypted_key"));
                recipients.Add(new JweRecipient(encryptedCek, Dictionaries.Get <IDictionary <string, object> >(json, "header")));
            }

            var _protected = Dictionaries.Get <string>(json, "protected");
            var _aad       = Dictionaries.Get <string>(json, "aad");

            return(new JweToken(
                       protectedHeaderBytes: _protected == null ? new byte[0] : Base64Url.Decode(_protected),
                       unprotectedHeader: Dictionaries.Get <IDictionary <string, object> >(json, "unprotected"),
                       recipients: recipients,
                       aad: _aad == null ? null : Base64Url.Decode(_aad),
                       iv: Base64Url.Decode(Dictionaries.Get <string>(json, "iv")),
                       ciphertext: Base64Url.Decode(Dictionaries.Get <string>(json, "ciphertext")),
                       authTag: Base64Url.Decode(Dictionaries.Get <string>(json, "tag")),
                       encoding: SerializationMode.Json));
        }
コード例 #2
0
ファイル: JWT.cs プロジェクト: XinicsInc/jose-jwt
        /// <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]));
        }
コード例 #3
0
ファイル: JWT.cs プロジェクト: XinicsInc/jose-jwt
        /// <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));
        }
コード例 #4
0
ファイル: JWT.cs プロジェクト: cuteant/IdentityModel
        /// <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));
        }
コード例 #5
0
ファイル: JWT.cs プロジェクト: senzacionale/xamarin-jose-jwt
        /// <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));
        }
コード例 #6
0
ファイル: JWT.cs プロジェクト: senzacionale/xamarin-jose-jwt
        /// <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]));
        }
コード例 #7
0
ファイル: JWT.cs プロジェクト: itbetaw/TPlus-.netCore-
        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 }));
        }
コード例 #8
0
ファイル: JWT.cs プロジェクト: itbetaw/TPlus-.netCore-
        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] }));
        }
コード例 #9
0
        public static JwkSet FromDictionary(IDictionary <string, object> data)
        {
            var keyList = Dictionaries.Get <IEnumerable <object> >(data, "keys");

            JwkSet result = new JwkSet();

            foreach (var key in keyList)
            {
                result.Add(Jwk.FromDictionary((IDictionary <string, object>)key));
            }

            return(result);
        }
コード例 #10
0
ファイル: JWT.cs プロジェクト: lvtao2415/jose-jwt
        /// <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));
        }
コード例 #11
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]));
        }
コード例 #12
0
ファイル: JWT.cs プロジェクト: ldavismead/jose-jwt
        /// <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]));
        }
コード例 #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)
            {
                // 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));
        }
コード例 #14
0
        /// <summary>
        /// Parses JWE token, extracts and unmarshal protected+unprotcted+per recipient headers
        /// This method is NOT performing integrity checking and actual decryption
        /// </summary>
        /// <param name="jwe">Serialized JWE string to decrypt.</param>
        /// <param name="settings">optional settings to override global DefaultSettings</param>
        /// <returns>List of Jose headers. For Compact and Flattened this will be length 1 and contain just the protected header.
        ///  For General Json this will be the Jose headers (merge of protected, unprotected and per-recipient).</returns>
        /// <exception cref="IntegrityException">if AEAD operation validation failed</exception>
        /// <exception cref="EncryptionException">if JWE can't be decrypted</exception>
        /// <exception cref="InvalidAlgorithmException">if encryption or compression algorithm is not supported</exception>
        public static JweToken Headers(string jwe, JwtSettings settings = null)
        {
            settings = GetSettings(settings);

            var token = JweToken.FromString(jwe, settings.JsonMapper);

            var protectedHeader = settings.JsonMapper.Parse <IDictionary <string, object> >(
                Encoding.UTF8.GetString(token.ProtectedHeaderBytes));

            foreach (var recipient in token.Recipients)
            {
                try
                {
                    recipient.JoseHeader = Dictionaries.MergeHeaders(protectedHeader, token.UnprotectedHeader, recipient.Header);
                }
                catch (ArgumentException)
                {
                    throw new JoseException("Invalid JWE data, duplicate header keys found between protected, unprotected and recipient headers");
                }
            }

            return(token);
        }
コード例 #15
0
ファイル: JWT.cs プロジェクト: ncichris/jose-jwt
        /// <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));
            }
        }
コード例 #16
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}.");
            }
        }