/// <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) { Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null."); IKeyManagement keys = KeyAlgorithms[alg]; IJweAlgorithm _enc = EncAlgorithms[enc]; var jwtHeader = new Dictionary <string, object> { { "alg", JweAlgorithms[alg] }, { "enc", JweEncryptionMethods[enc] } }; 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])); }
public void ShouldValidateJwe(string algorithm, KeyType keyType, string encryption) { var options = new JwksOptions() { KeyPrefix = $"{nameof(JsonWebKeySetServiceTests)}_", Jwe = JweAlgorithm.Create(algorithm, keyType).WithEncryption(encryption) }; var encryptingCredentials = _jwksService.GenerateEncryptingCredentials(options); var handler = new JsonWebTokenHandler(); var now = DateTime.Now; var jwt = new SecurityTokenDescriptor { Issuer = "me", Audience = "you", IssuedAt = now, NotBefore = now, Expires = now.AddMinutes(5), Subject = new ClaimsIdentity(GenerateClaim().Generate(5)), EncryptingCredentials = encryptingCredentials }; var jwe = handler.CreateToken(jwt); var result = handler.ValidateToken(jwe, new TokenValidationParameters { ValidIssuer = "me", ValidAudience = "you", RequireSignedTokens = false, TokenDecryptionKey = encryptingCredentials.Key }); result.IsValid.Should().BeTrue(); }
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] })); }
/// <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])); }
/// <summary>VerifyResult</summary> /// <param name="testLabel">string</param> /// <param name="jwt">string</param> /// <param name="key">object</param> /// <param name="alg">JweAlgorithm</param> /// <param name="enc">JweEncryption</param> private static void VerifyResult(string testLabel, string jwt, object key, JweAlgorithm alg, JweEncryption enc) { MyDebug.OutputDebugAndConsole(testLabel, "Original:" + jwt); MyDebug.InspectJwt(testLabel, jwt); MyDebug.OutputDebugAndConsole(testLabel, "Decoded:" + JWT.Decode(jwt, key, alg, enc)); }
/// <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> /// <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 Encode(string payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null) { Ensure.IsNotEmpty(payload, "Payload expected to be not empty, whitespace or null."); byte[] plainText = Encoding.UTF8.GetBytes(payload); return(EncodeBytes(plainText, key, alg, enc, compression, extraHeaders, settings)); }
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]; 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 alg = (string)jwtHeader["zip"]; var compression = jwtSettings.Compression(GetJweCompression(alg)); if (compression == null) { throw new JoseException(string.Format("Unsupported compressions algorithm requested: {0}", alg)); } plainText = compression.Decompress(plainText); } return(plainText); }
/// <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])); }
/// <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])); }
public void ShouldRemovePrivateKeyFromJweAfterUpdateAExpiredJwk(string algorithm, KeyType keyType, string encryption) { var alg = JweAlgorithm.Create(algorithm, keyType).WithEncryption(encryption); var key = _keyService.GenerateSigningCredentials(new JwksOptions() { KeyPrefix = "ShouldGenerateManyRsa_", Jwe = alg }); var privateKey = new SecurityKeyWithPrivate(); privateKey.SetJweParameters(key.Key, alg); _jsonWebKeyStore.Save(privateKey); /*Remove private*/ _jsonWebKeyStore.Revoke(privateKey); var jsonWebKey = _keyService.GetLastKeysCredentials(JsonWebKeyType.Jwe, 5).First(w => w.Kid == privateKey.KeyId); jsonWebKey.Kty.Should().NotBeNullOrEmpty(); jsonWebKey.HasPrivateKey.Should().BeFalse(); switch (jsonWebKey.Kty) { case JsonWebAlgorithmsKeyTypes.EllipticCurve: jsonWebKey.D.Should().BeNullOrEmpty(); break; case JsonWebAlgorithmsKeyTypes.RSA: jsonWebKey.D.Should().BeNullOrEmpty(); jsonWebKey.DP.Should().BeNullOrEmpty(); jsonWebKey.DQ.Should().BeNullOrEmpty(); jsonWebKey.P.Should().BeNullOrEmpty(); jsonWebKey.Q.Should().BeNullOrEmpty(); jsonWebKey.QI.Should().BeNullOrEmpty(); break; case JsonWebAlgorithmsKeyTypes.Octet: jsonWebKey.K.Should().NotBeNullOrEmpty(); break; } }
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); }
public byte[] Decrypt(string keyId, byte[] payload, JweAlgorithm algorithm) { RSAEncryptionPadding padding; switch (algorithm) { case JweAlgorithm.Rsa15: padding = RSAEncryptionPadding.Pkcs1; break; case JweAlgorithm.RsaOaep: padding = RSAEncryptionPadding.OaepSHA1; break; case JweAlgorithm.RsaOaep256: padding = RSAEncryptionPadding.OaepSHA256; break; default: throw new ArgumentOutOfRangeException(nameof(algorithm), algorithm, null); } return(_keys[keyId].Decrypt(payload, padding)); }
public static byte[] DecodeBytes(string token, object key, JweAlgorithm alg, JweEncryption enc) { JwsAlgorithm?nullable = null; return(JWT.DecodeBytes(token, key, nullable, new JweAlgorithm?(alg), new JweEncryption?(enc))); }
public static T Decode <T>(string token, object key, JweAlgorithm alg, JweEncryption enc) { return(JWT.jsMapper.Parse <T>(JWT.Decode(token, key, alg, enc))); }
/// <summary> /// Decodes JWT token by performing necessary decompression/decryption and signature verification as defined in JWT token header. /// Resulting json string will be parsed and mapped to desired type via configured IJsonMapper implementation. /// </summary> /// <typeparam name="T">Deserid object type after json mapping</typeparam> /// <param name="token">JWT token in compact serialization form.</param> /// <param name="key">key for decoding suitable for JWT algorithm used.</param> /// <param name="alg">The algorithm type that we expect to receive in the header.</param> /// <param name="enc">The encryption type that we expect to receive in the header.</param> /// <param name="settings">optional settings to override global DefaultSettings</param> /// <returns>object of provided T, result of decoded json mapping</returns> /// <exception cref="IntegrityException">if signature validation failed</exception> /// <exception cref="EncryptionException">if JWT token can't be decrypted</exception> /// <exception cref="InvalidAlgorithmException">if JWT signature, encryption or compression algorithm is not supported</exception> public static T Decode <T>(string token, object key, JweAlgorithm alg, JweEncryption enc, JwtSettings settings = null) { return(GetSettings(settings).JsonMapper.Parse <T>(Decode(token, key, alg, enc, settings))); }
public void ShouldSaveJweRecoverAndEncrypt(string algorithm, KeyType keyType, string encryption) { this.WarmupData.Clear(); var options = new JwksOptions() { Jwe = JweAlgorithm.Create(algorithm, keyType).WithEncryption(encryption) }; var handler = new JsonWebTokenHandler(); var now = DateTime.Now; // Generate right now and in memory var newKey = _keyService.GetCurrentEncryptingCredentials(options); // recovered from database var currentKey = _keyService.GetCurrentEncryptingCredentials(options); newKey.Key.KeyId.Should().Be(currentKey.Key.KeyId); var claims = new ClaimsIdentity(GenerateClaim().Generate(5)); var descriptor = new SecurityTokenDescriptor { Issuer = "me", Audience = "you", IssuedAt = now, NotBefore = now, Expires = now.AddMinutes(5), Subject = claims, EncryptingCredentials = newKey }; var descriptorFromDb = new SecurityTokenDescriptor { Issuer = "me", Audience = "you", IssuedAt = now, NotBefore = now, Expires = now.AddMinutes(5), Subject = claims, EncryptingCredentials = currentKey }; var jwt1 = handler.CreateToken(descriptor); var jwt2 = handler.CreateToken(descriptorFromDb); var result = handler.ValidateToken(jwt1, new TokenValidationParameters { ValidIssuer = "me", ValidAudience = "you", RequireSignedTokens = false, TokenDecryptionKey = currentKey.Key }); result.IsValid.Should().BeTrue(); result = handler.ValidateToken(jwt2, new TokenValidationParameters { ValidIssuer = "me", ValidAudience = "you", RequireSignedTokens = false, TokenDecryptionKey = currentKey.Key }); result.IsValid.Should().BeTrue(); }
/// <summary> /// Decodes JWT token by performing necessary decompression/decryption and signature verification as defined in JWT token header. /// Resulting bytes of the payload are returned untouched (e.g. no parsing or mapping) /// </summary> /// <param name="token">JWT token in compact serialization form.</param> /// <param name="key">key for decoding suitable for JWT algorithm used.</param> /// <param name="alg">The algorithm type that we expect to receive in the header.</param> /// <param name="enc">The encryption type that we expect to receive in the header.</param> /// <param name="settings">optional settings to override global DefaultSettings</param> /// <returns>Decrypted payload as binary data</returns> /// <exception cref="IntegrityException">if signature validation failed</exception> /// <exception cref="EncryptionException">if JWT token can't be decrypted</exception> /// <exception cref="InvalidAlgorithmException">if JWT signature, encryption or compression algorithm is not supported</exception> public static byte[] DecodeBytes(string token, object key, JweAlgorithm alg, JweEncryption enc, JwtSettings settings = null) { return(DecodeBytes(token, key, null, alg, enc, settings)); }
/// <summary> /// Decodes JWT token by performing necessary decompression/decryption and signature verification as defined in JWT token header. /// Resulting bytes of the payload are returned untouched (e.g. no parsing or mapping) /// </summary> /// <param name="token">JWT token in compact serialization form.</param> /// <param name="key">key for decoding suitable for JWT algorithm used.</param> /// <param name="alg">The algorithm type that we expect to receive in the header.</param> /// <param name="enc">The encryption type that we expect to receive in the header.</param> /// <param name="settings">optional settings to override global DefaultSettings</param> /// <returns>Decrypted payload as binary data</returns> /// <exception cref="IntegrityException">if signature validation failed</exception> /// <exception cref="EncryptionException">if JWT token can't be decrypted</exception> /// <exception cref="InvalidAlgorithmException">if JWT signature, encryption or compression algorithm is not supported</exception> public static byte[] DecodeBytes(string token, object key, JweAlgorithm alg, JweEncryption enc, JwtSettings settings = null, bool requireSignature = false) { return(DecodeBytes(token, key, null, alg, enc, settings, null, requireSignature)); }
/// <summary> /// Serialize and encodes object to JWT token and applies requested encryption/compression algorithms. /// </summary> /// <param name="payload">json string to encode</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 Encode(object payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null) { return(Encode(GetSettings(settings).JsonMapper.Serialize(payload), key, alg, enc, compression, extraHeaders, settings)); }
/// <summary> /// Decodes JWT token by performing necessary decompression/decryption and signature verification as defined in JWT token header. /// Resulting json string is returned untouched (e.g. no parsing or mapping) /// </summary> /// <param name="token">JWT token in compact serialization form.</param> /// <param name="key">key for decoding suitable for JWT algorithm used.</param> /// <param name="alg">The algorithm type that we expect to receive in the header.</param> /// <param name="enc">The encryption type that we expect to receive in the header.</param> /// <param name="cek">The content encryption key derived during the decryption</param> /// <param name="settings">optional settings to override global DefaultSettings</param> /// <returns>decoded json string</returns> /// <exception cref="IntegrityException">if signature validation failed</exception> /// <exception cref="EncryptionException">if JWT token can't be decrypted</exception> /// <exception cref="InvalidAlgorithmException">if JWT signature, encryption or compression algorithm is not supported</exception> public static string Decode(string token, object key, JweAlgorithm alg, JweEncryption enc, out byte[] cek, JwtSettings settings = null) { return(Decode(token, out cek, key, null, alg, enc, settings)); }
protected Dictionary <string, object> JoseDotNetCore(string token, JweEncryption enc, JweAlgorithm alg, byte[] key) { return(Jose.JWT.Decode <Dictionary <string, object> >(token, key: key, enc: enc /*JweEncryption.A128CBC_HS256*/, alg: alg /*JweAlgorithm.A128KW*/)); }
public void Decrypt_MultipleRecipients_MismatchEncOrAlgThrows(JweEncryption expectedJweEnc, JweAlgorithm expectedJweAlg, string expectedMessage) { //given byte[] payload = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; var recipients = new Recipient[] { recipientAes256KW1, recipientAes256KW2, recipientRsa1, }; var sharedProtectedHeaders = new Dictionary <string, object> { { "cty", "application/octet-string" }, }; var jwe = JWE.Encrypt( plaintext: payload, recipients: recipients, JweEncryption.A256GCM, mode: SerializationMode.Json, extraHeaders: sharedProtectedHeaders); //when var exception = Record.Exception(() => JWE.Decrypt(jwe, aes256KWKey2, expectedJweAlg, expectedJweEnc)); //then Assert.IsType <InvalidAlgorithmException>(exception); Assert.Equal(expectedMessage, exception.Message); }
public static string Encode(object payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null) { return(JWT.Encode(JsonConvert.SerializeObject(payload), key, alg, enc, compression, extraHeaders)); }
/// <summary /// A recipient for a Jwe /// </summary /// <param name="alg">algorithm to be used to encrypt the CEK (Content Encryption Key).</param> /// <param name="key">key for encrypting CEK (Content Encryption Key). Cannot be null.</param> public Recipient(JweAlgorithm alg, object key, IDictionary <string, object> perRecipientHeaders = null) { this.Alg = alg; this.Key = key ?? throw new ArgumentNullException(nameof(key)); this.PerRecipientHeaders = perRecipientHeaders; }
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.", new object[0]); return(JWT.EncodeBytes(Encoding.UTF8.GetBytes(payload), key, alg, enc, compression, extraHeaders)); }
/// <summary> /// Decodes JWT token by performining necessary decompression/decryption and signature verification as defined in JWT token header. /// Resulting json string is returned untouched (e.g. no parsing or mapping) /// </summary> /// <param name="token">JWT token in compact serialization form.</param> /// <param name="key">key for decoding suitable for JWT algorithm used.</param> /// <param name="alg">The algorithm type that we expect to receive in the header.</param> /// <param name="enc">The encryption type that we expect to receive in the header.</param> /// <returns>decoded json string</returns> /// <exception cref="IntegrityException">if signature valdation failed</exception> /// <exception cref="EncryptionException">if JWT token can't be decrypted</exception> /// <exception cref="InvalidAlgorithmException">if JWT signature, encryption or compression algorithm is not supported</exception> public static string Decode(string token, object key, JweAlgorithm alg, JweEncryption enc) { return(Decode(token, key, null, alg, enc)); }
/// <summary> /// Serialize and encodes object to JWT token and applies requested encryption/compression algorithms. /// </summary> /// <param name="payload">json string to encode</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(object payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null) { return(Encode(jsMapper.Serialize(payload), key, alg, enc)); }
/// <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> /// <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 Encode(string payload, object key, JweAlgorithm alg, JweEncryption enc, JweCompression?compression = null, IDictionary <string, object> extraHeaders = null, JwtSettings settings = null) { byte[] plainText = Encoding.UTF8.GetBytes(payload); return(EncodeBytes(plainText, key, alg, enc, compression, extraHeaders, settings)); }
/// <summary /// Constructs recipient for JWE encryption with desired KEK and key management algorithm /// </summary /// <param name="alg">algorithm to be used to encrypt the CEK (Content Encryption Key).</param> /// <param name="key">key for encrypting CEK (Content Encryption Key). Cannot be null.</param> public JweRecipient(JweAlgorithm alg, object key, IDictionary <string, object> header = null) { this.Alg = alg; this.Key = key ?? throw new ArgumentNullException(nameof(key)); this.Header = header; }
/// <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) { return(JWE.EncryptBytes(payload, new JweRecipient[] { new JweRecipient(alg, key) }, enc, aad: null, SerializationMode.Compact, compression, extraHeaders, null, settings)); }