Exemplo n.º 1
0
        public static void RC2RoundTrip(CipherMode cipherMode, PaddingMode paddingMode, string key, string iv, string textHex, string expectedDecrypted, string expectedEncrypted)
        {
            byte[] expectedDecryptedBytes = expectedDecrypted == null?textHex.HexToByteArray() : expectedDecrypted.HexToByteArray();

            byte[] expectedEncryptedBytes = expectedEncrypted.HexToByteArray();
            byte[] keyBytes = key.HexToByteArray();

            using (RC2 alg = RC2Factory.Create())
            {
                alg.Key     = keyBytes;
                alg.Padding = paddingMode;
                alg.Mode    = cipherMode;
                if (iv != null)
                {
                    alg.IV = iv.HexToByteArray();
                }

                byte[] cipher = alg.Encrypt(textHex.HexToByteArray());
                Assert.Equal <byte>(expectedEncryptedBytes, cipher);

                byte[] decrypted = alg.Decrypt(cipher);
                Assert.Equal <byte>(expectedDecryptedBytes, decrypted);

                if (RC2Factory.OneShotSupported)
                {
                    byte[] oneShotEncrypt = cipherMode switch
                    {
                        CipherMode.ECB => alg.EncryptEcb(textHex.HexToByteArray(), paddingMode),
                        CipherMode.CBC => alg.EncryptCbc(textHex.HexToByteArray(), iv.HexToByteArray(), paddingMode),
                        _ => throw new NotImplementedException(),
                    };

                    Assert.Equal(expectedEncryptedBytes, oneShotEncrypt);

                    byte[] oneShotDecrypt = cipherMode switch
                    {
                        CipherMode.ECB => alg.DecryptEcb(cipher, paddingMode),
                        CipherMode.CBC => alg.DecryptCbc(cipher, iv.HexToByteArray(), paddingMode),
                        _ => throw new NotImplementedException(),
                    };

                    Assert.Equal(expectedDecryptedBytes, oneShotDecrypt);
                }
            }
        }