public static byte[] Decrypt(byte[] secretKeyBytes, JweObject jweObject) { // Extract the encryption key byte[] aesKey = new byte[16]; Array.Copy(secretKeyBytes, 16, aesKey, 0, aesKey.Length); byte[] plaintext; using (var aes = Aes.Create()) { aes.Key = aesKey; aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.IV = Base64Utils.URLDecode(jweObject.Iv); byte[] ciphertext = Base64Utils.URLDecode(jweObject.CipherText); using (var decryptor = aes.CreateDecryptor()) { using (var memoryStream = new MemoryStream(ciphertext)) { using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) { var output = new MemoryStream(); var decrypted = new byte[Math.Min(1024, ciphertext.Length)]; int byteCount; while ((byteCount = cryptoStream.Read(decrypted, 0, decrypted.Length)) > 0) { output.Write(decrypted, 0, byteCount); } plaintext = output.ToArray(); } } } } return(plaintext); }
public void TestDecrypt_ShouldReturnDecryptedPayload_WhenPayloadIsCbcEncrypted() { // GIVEN JweObject jweObject = TestUtils.GetTestCbcJweObject(); // WHEN string decryptedPayload = jweObject.Decrypt(TestUtils.GetTestJweConfigBuilder().Build()); // THEN Assert.AreEqual("bar", decryptedPayload); }
internal static byte[] Decrypt(byte[] secretKeyBytes, JweObject jweObject) { #if NETSTANDARD2_1 byte[] plaintext; using (var aes = new System.Security.Cryptography.AesGcm(secretKeyBytes)) { byte[] nonce = Base64Utils.URLDecode(jweObject.Iv); byte[] aad = Encoding.ASCII.GetBytes(jweObject.RawHeader); byte[] authTag = Base64Utils.URLDecode(jweObject.AuthTag); byte[] ciphertext = Base64Utils.URLDecode(jweObject.CipherText); plaintext = new byte[ciphertext.Length]; aes.Decrypt(nonce, ciphertext, authTag, plaintext, aad); } return(plaintext); #else throw new EncryptionException("AES/GCM/NoPadding is unsupported on .NET Standard < 2.1"); #endif }
internal static JweObject GetTestGcmJweObject() { return(JweObject.Parse("eyJraWQiOiI3NjFiMDAzYzFlYWRlM2E1NDkwZTUwMDBkMzc4ODdiYWE1Z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