编写实用程序类时的异常处理的最佳实践c#

时间:2018-06-12 04:14:06

标签: c# exception-handling software-design

  

在我的解决方案中,我正在为加密创建一个Utility类。它公开了加密,解密和其他一些东西的方法。任何其他项目都可以在需要加密的地方使用此实用程序。所有方法都是静态的。

     

我没有在Utility中处理任何Exception。相反,我将它留给调用者来处理异常。

     

在设计像这样的小型实用程序时,异常处理的最佳实践是什么。

代码:

public class AESEncryptionUtility
    {
        public static byte[] Encrypt(byte[] plainBytes, byte[] key, byte[] IV, CipherMode cipherMode, PaddingMode padding)
        {
            byte[] encrypted = null;
            using (AesCryptoServiceProvider aesAlgo = GetAesCryptoServiceProvider(key, IV, cipherMode, padding))
            {
                ICryptoTransform encryptor = aesAlgo.CreateEncryptor();
                encrypted = encryptor.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
            }
            return encrypted;
        }

        public static string EncryptUrlSafe(byte[] plainText, byte[] key, byte[] IV, CipherMode cipherMode, PaddingMode padding) // This will return safe Base64 Url Encoded string
        {
            byte[] encrypted = Encrypt(plainText, key, IV, cipherMode, padding);
            return Convert.ToBase64String(encrypted).Replace('+', '-').Replace('/', '_').Replace('=', ',');
        }

        private static AesCryptoServiceProvider GetAesCryptoServiceProvider(byte[] key, byte[] IV, CipherMode cipherMode, PaddingMode padding)
        {
            AesCryptoServiceProvider aesAlgo = new AesCryptoServiceProvider();
            aesAlgo.Key = key;
            aesAlgo.IV = IV;
            aesAlgo.Mode = cipherMode;
            aesAlgo.Padding = padding;
            return aesAlgo;
        }

        public static byte[] Decrypt(byte[] cipherBytes, byte[] key, byte[] IV, CipherMode cipherMode, PaddingMode padding)
        {
            byte[] decrypted = null;
            using (AesCryptoServiceProvider aesAlgo = GetAesCryptoServiceProvider(key, IV, cipherMode, padding))
            {
                ICryptoTransform decryptor = aesAlgo.CreateDecryptor();
                decrypted = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
            }
            return decrypted;
        }

        public static byte[] GenerateKey(string masterPassword, int size) //size in bytes
        {
            byte[] salt = GenerateSalt(size);
            Rfc2898DeriveBytes pbfdk = new Rfc2898DeriveBytes(masterPassword, salt, 20000);
            return pbfdk.GetBytes(size);
        }

        public static byte[] GenerateSalt(int size) //size in bytes
        {
            RNGCryptoServiceProvider generator = new RNGCryptoServiceProvider();
            byte[] salt = new byte[size];
            generator.GetNonZeroBytes(salt);
            return salt;
        } 
    }

0 个答案:

没有答案