예제 #1
0
        public int Encrypt_CharacterLength_CipherIsExpectedNumberOfBytes(string plainText)
        {
            using var provider = new AesCbc();
            var encryptionResult = provider.Encrypt(plainText);

            return(encryptionResult.Cipher.Length);
        }
예제 #2
0
        public string Decrypt(JweConfig config)
        {
            byte[] unwrappedKey = RsaEncryption.UnwrapSecretKey(config, Base64Utils.URLDecode(EncryptedKey), "SHA-256");
            if (unwrappedKey == null)
            {
                throw new EncryptionException(String.Format("Failed to unwrap key {0}", EncryptedKey));
            }

            string encryptionMethod = Header.Enc;

            byte[] plaintext;
            if (A256GCM.Equals(encryptionMethod))
            {
                plaintext = AesGcm.Decrypt(unwrappedKey, this);
            }
            else if (A128CBC_HS256.Equals(encryptionMethod))
            {
                plaintext = AesCbc.Decrypt(unwrappedKey, this);
            }
            else
            {
                throw new EncryptionException(String.Format("Encryption method {0} is not supported", encryptionMethod));
            }
            return(Encoding.UTF8.GetString(plaintext));
        }
예제 #3
0
        public void KeyVault_Aes128CbcTwoBlock()
        {
            // Arrange.
            // Note that AES128CBC as implemented in this library uses PKCS7 padding mode where the test
            // vectors do not use padding.
            byte[] CEK   = { 0xc2, 0x86, 0x69, 0x6d, 0x88, 0x7c, 0x9a, 0xa0, 0x61, 0x1b, 0xbb, 0x3e, 0x20, 0x25, 0xa4, 0x5a };
            byte[] PLAIN = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
            byte[] IV    = { 0x56, 0x2e, 0x17, 0x99, 0x6d, 0x09, 0x3d, 0x28, 0xdd, 0xb3, 0xba, 0x69, 0x5a, 0x2e, 0x6f, 0x58 };
            byte[] ED    = { 0xd2, 0x96, 0xcd, 0x94, 0xc2, 0xcc, 0xcf, 0x8a, 0x3a, 0x86, 0x30, 0x28, 0xb5, 0xe1, 0xdc, 0x0a, 0x75, 0x86, 0x60, 0x2d, 0x25, 0x3c, 0xff, 0xf9, 0x1b, 0x82, 0x66, 0xbe, 0xa6, 0xd6, 0x1a, 0xb1 };

            AesCbc algo = AesCbc.Aes128Cbc;

            byte[] encrypted;

            using (var encryptor = algo.CreateEncryptor(CEK, IV))
            {
                encrypted = encryptor.TransformFinalBlock(PLAIN, 0, PLAIN.Length);

                // Assert: we only compare the first 32 bytes as this library uses PKCS7 padding
                var unpadded = encrypted.Take(32).ToArray();
                Assert.True(unpadded.SequenceEqual(ED));
            }

            using (var decryptor = algo.CreateDecryptor(CEK, IV))
            {
                var decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);

                // Assert
                Assert.True(decrypted.SequenceEqual(PLAIN));
            }
        }
예제 #4
0
        public void KeyVault_Aes128CbcOneBlock_ExcessKeyMaterial()
        {
            // Arrange.
            // Note that AES128CBC as implemented in this library uses PKCS7 padding mode where the test
            // vectors do not use padding.
            byte[] CEK   = { 0x06, 0xa9, 0x21, 0x40, 0x36, 0xb8, 0xa1, 0x5b, 0x51, 0x2e, 0x03, 0xd5, 0x34, 0x12, 0x00, 0x06, 0xc2, 0x86, 0x69, 0x6d, 0x88, 0x7c, 0x9a, 0xa0, 0x61, 0x1b, 0xbb, 0x3e, 0x20, 0x25, 0xa4, 0x5a };
            byte[] PLAIN = System.Text.UTF8Encoding.UTF8.GetBytes("Single block msg");
            byte[] IV    = { 0x3d, 0xaf, 0xba, 0x42, 0x9d, 0x9e, 0xb4, 0x30, 0xb4, 0x22, 0xda, 0x80, 0x2c, 0x9f, 0xac, 0x41 };
            byte[] ED    = { 0xe3, 0x53, 0x77, 0x9c, 0x10, 0x79, 0xae, 0xb8, 0x27, 0x08, 0x94, 0x2d, 0xbe, 0x77, 0x18, 0x1a };

            AesCbc algo = AesCbc.Aes128Cbc;

            byte[] encrypted;

            using (var encryptor = algo.CreateEncryptor(CEK, IV))
            {
                encrypted = encryptor.TransformFinalBlock(PLAIN, 0, PLAIN.Length);

                // Assert: we only compare the first 16 bytes as this library uses PKCS7 padding
                var unpadded = encrypted.Take(16).ToArray();
                Assert.True(unpadded.SequenceEqual(ED));
            }

            using (var decryptor = algo.CreateDecryptor(CEK, IV))
            {
                var decrypted = decryptor.TransformFinalBlock(encrypted, 0, encrypted.Length);

                // Assert
                Assert.True(decrypted.SequenceEqual(PLAIN));
            }
        }
예제 #5
0
        private async Task Encrypt()
        {
            AesCbc key = await GetKey();

            byte[] output = await key.EncryptAsync(
                GetInputBytes(),
                new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });

            _output = Convert.ToBase64String(output);
        }
예제 #6
0
        private async Task <AesCbc> GetKey()
        {
            if (_key == null)
            {
                _key = await GetSubtleCrypto().ImportAesCbcKeyAsync(new byte[16]);

                _keyLabel = Convert.ToHexString(await _key.ExportKeyAsync());
            }

            return(_key);
        }
예제 #7
0
        public void Decrypt_CipherLengthNotDivisibleBy16_ThrowsArgumentException()
        {
            CbcResult encryptionResult;

            using (var provider1 = new AesCbc())
            {
                encryptionResult = provider1.Encrypt("Hello world");
            }

            using var provider2 = new AesCbc();
            Assert.That(() => provider2.Decrypt(new byte[new Random().Next(1, 16)], encryptionResult.Key, encryptionResult.IV), Throws.ArgumentException);
        }
예제 #8
0
        public void TestChallenge10()
        {
            var keyStr = "YELLOW SUBMARINE";
            var key    = System.Text.Encoding.ASCII.GetBytes(keyStr);
            var iv     = new HexString("0000000000000000");
            var data   = Convert.FromBase64String(Set2Data.Challenge10Input);

            var decrypted = AesCbc.Decrypt(key, iv.Bytes.ToArray(), data);
            var actual    = System.Text.Encoding.ASCII.GetString(decrypted);

            Assert.AreEqual(Set2Data.Challenge10Solution, actual);
        }
예제 #9
0
        public void TestEncrypt()
        {
            var key       = new HexString("0102030405060708090A0B0C0D0E0F10");
            var iv        = new HexString("1112131415161718191A1B1C1D1E1F20");
            var clearText = "Hello World, let's try something longer than just one block.";
            var data      = System.Text.Encoding.ASCII.GetBytes(clearText);
            var expected  = new HexString("C29B1B0E628232FA5A8F77F88546DF259D8B8B4E73B5D21D9BA1EDB557CAE0A67CA855B59DC1F423A2540EC15377EF70B7750F310C8E40AE68A52E57D478BB60");

            var actual = AesCbc.Encrypt(key.Bytes.ToArray(), iv.Bytes.ToArray(), data);

            CollectionAssert.AreEqual(expected.Bytes.ToArray(), actual);
        }
예제 #10
0
        public void Decrypt_KeyIsNot32Bytes_ThrowsArgumentException()
        {
            CbcResult encryptionResult;

            using (var provider1 = new AesCbc())
            {
                encryptionResult = provider1.Encrypt("Hello world");
            }

            using var provider2 = new AesCbc();
            Assert.That(() => provider2.Decrypt(encryptionResult.Cipher, new byte[16], encryptionResult.IV), Throws.ArgumentException);
        }
예제 #11
0
        public void TestEncryptOneBlock()
        {
            var key       = new HexString("0102030405060708090A0B0C0D0E0F10");
            var iv        = new HexString("1112131415161718191A1B1C1D1E1F20");
            var clearText = "Hello World";
            var data      = System.Text.Encoding.ASCII.GetBytes(clearText);
            var expected  = new HexString("E0A209AC01C9052681925942E0E5EA53");

            var actual = AesCbc.Encrypt(key.Bytes.ToArray(), iv.Bytes.ToArray(), data);

            CollectionAssert.AreEqual(expected.Bytes.ToArray(), actual);
        }
예제 #12
0
        public void Decrypt_NullIV_ThrowsArgumentNullException()
        {
            CbcResult encryptionResult;

            using (var provider1 = new AesCbc())
            {
                encryptionResult = provider1.Encrypt("Hello world");
            }

            using var provider2 = new AesCbc();
            Assert.That(() => provider2.Decrypt(encryptionResult.Cipher, encryptionResult.Key, null), Throws.ArgumentNullException);
        }
예제 #13
0
        public void Decrypt_PlainTextStringEncrypted_ResultMatchesPlaintext(string plainText)
        {
            CbcResult encryptionResult;

            using (var provider1 = new AesCbc())
            {
                encryptionResult = provider1.Encrypt(plainText);
            }

            using var provider2 = new AesCbc();
            var plainTextResult = provider2.Decrypt(encryptionResult.Cipher, encryptionResult.Key, encryptionResult.IV);

            Assert.That(plainTextResult, Is.EqualTo(plainText));
        }
예제 #14
0
 /**
  * This is a small demo that will encrypt the text in the file
  * `plaintext.txt` in the current directory, and write the cipher text to
  * `ciphertext.hex`. A python 3 implementation of decryption can be found
  * in `decrypt.py`, that will read `ciphertext.hex` and write the decrypted
  * plain text to the console. Any padding problems should be exposed when running
  * the decryption program.
  *
  * Note that the key and iv that have been hard-coded here for demo
  * purposes also can be found in the `decrypt.py` decryption program.
  **/
 public static void Main(string[] args)
 {
     byte[] key = Hex2Bytes("1adbe7770c41ab6712486368801b4cb557b1951546ffeed1b78e088da1c4f46d");
     byte[] iv  = Hex2Bytes("bce0fd9681ea31757e207a84683fff63");
     using (FileStream fIn = File.OpenRead("plaintext.txt"))
     {
         byte[] ciphertext = AesCbc.encrypt(fIn, key, iv);
         using (FileStream fOut = File.OpenWrite("ciphertext.hex")) {
             /*  there is probably a nicer way of doing this - just for demo anyway */
             using (StreamWriter w = new StreamWriter(fOut))
             {
                 w.Write(BitConverter.ToString(ciphertext).Replace("-", ""));
             }
         }
         Console.WriteLine($"Ciphertext length: {ciphertext.Length}");
     }
 }
예제 #15
0
        private async Task Decrypt()
        {
            AesCbc key = await GetKey();

            try
            {
                byte[] output = await key.DecryptAsync(
                    GetInputBytes(),
                    new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 });

                _output = Encoding.UTF8.GetString(output);
            }
            catch (Exception e)
            {
                _output = e.ToString();
            }
        }
예제 #16
0
        private async Task GenerateKey()
        {
            try
            {
                int keySize = int.Parse(_input);

                AesCbc newKey = await GetSubtleCrypto().CreateAesCbcKey(keySize);

                if (_key != null)
                {
                    await _key.DisposeAsync();
                }

                _key      = newKey;
                _keyLabel = Convert.ToHexString(await _key.ExportKeyAsync());
            }
            catch (Exception e)
            {
                _output = e.ToString();
            }
        }
예제 #17
0
 public void Encrypt_EmptyPlainText_ThrowsArgumentException()
 {
     using var provider = new AesCbc();
     Assert.That(() => provider.Encrypt(string.Empty), Throws.ArgumentException);
 }
예제 #18
0
 public void Encrypt_NullPlainText_ThrowsArgumentNullException()
 {
     using var provider = new AesCbc();
     Assert.That(() => provider.Encrypt(null as string), Throws.ArgumentNullException);
 }