1. 程式人生 > 實用技巧 >AES上傳檔案加密下載檔案解密(完整,附助手實體類)

AES上傳檔案加密下載檔案解密(完整,附助手實體類)

首先可以自定義實體類,祕鑰是最重要的,不要透露給任何人,來看助手類

    public class AesHelper
    {
        //
        // 摘要:
        //     預設金鑰
        private const string PublicKey = "88888jghe8888uh8";

        //
        // 摘要:
        //     預設向量
        private const string Iv = "abudkdghij8888p8";

        //
        // 摘要:
        //     AES加密 (使用系統內建金鑰)
        
// // 引數: // str: // 需要加密字串 // // 返回結果: // 加密後字串 public static string Encrypt(string str) { return Encrypt(str, "88888jghe8888uh8"); } // // 摘要: // AES解密 (使用系統內建金鑰) // // 引數: // str:
// 需要解密字串 // // 返回結果: // 解密後字串 public static string Decrypt(string str) { return Decrypt(str, "88888jghe8888uh8"); } // // 摘要: // AES加密 // // 引數: // str: // 需要加密的字串 // // key:
// 32位金鑰(如果小於32位則自動補0) // // 返回結果: // 加密後的字串 public static string Encrypt(string str, string key) { key = Key32Handler(key); return Encrypt(str, key, IvHandler("abudkdghij8888p8")); } // // 摘要: // AES解密 // // 引數: // str: // 需要解密的字串 // // key: // 32位金鑰(如果小於32位則自動補0) // // 返回結果: // 解密後的字串 public static string Decrypt(string str, string key) { key = Key32Handler(key); return Decrypt(str, key, IvHandler("abudkdghij8888p8")); } // // 摘要: // AES解密 // // 引數: // str: // 需要解密的字串 // // key: // 16位金鑰(如果小於16位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) // // 返回結果: // 解密後的字串 public static string Decrypt16(string str, string key, string iv) { key = Key16Handler(key); return Decrypt(str, key, IvHandler(iv)); } // // 摘要: // AES加密 // // 引數: // str: // 需要加密的字串 // // key: // 16位金鑰(如果小於16位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) // // 返回結果: // 加密後的字串 public static string Encrypt16(string str, string key, string iv) { key = Key16Handler(key); return Encrypt(str, key, IvHandler(iv)); } // // 摘要: // AES解密 // // 引數: // str: // 需要解密的字串 // // key: // 32位金鑰(如果小於32位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) // // 返回結果: // 解密後的字串 public static string Decrypt32(string str, string key, string iv) { key = Key32Handler(key); return Decrypt(str, key, IvHandler(iv)); } // // 摘要: // AES加密 // // 引數: // str: // 需要加密的字串 // // key: // 32位金鑰(如果小於32位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) // // 返回結果: // 加密後的字串 public static string Encrypt32(string str, string key, string iv) { key = Key32Handler(key); return Encrypt(str, key, IvHandler(iv)); } // // 摘要: // AES解密 // // 引數: // str: // 需要解密的字串 // // key: // 16/32位金鑰 // // iv: // 16位偏向量(如果小於16位則自動補0) // // 返回結果: // 解密後的字串 public static string Decrypt(string str, string key, string iv) { byte[] bytes = Encoding.UTF8.GetBytes(key); byte[] array = Convert.FromBase64String(str); byte[] bytes2 = new RijndaelManaged { Key = bytes, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, IV = Encoding.UTF8.GetBytes(IvHandler(iv)) }.CreateDecryptor().TransformFinalBlock(array, 0, array.Length); return Encoding.UTF8.GetString(bytes2); } // // 摘要: // AES加密 // // 引數: // str: // 需要加密的字串 // // key: // 16/32位金鑰 // // iv: // 16位偏向量(如果小於16位則自動補0) // // 返回結果: // 加密後的字串 public static string Encrypt(string str, string key, string iv) { byte[] bytes = Encoding.UTF8.GetBytes(key); byte[] bytes2 = Encoding.UTF8.GetBytes(str); byte[] array = new RijndaelManaged { Key = bytes, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, IV = Encoding.UTF8.GetBytes(IvHandler(iv)) }.CreateEncryptor().TransformFinalBlock(bytes2, 0, bytes2.Length); return Convert.ToBase64String(array, 0, array.Length); } private static string Key32Handler(string key) { if (key.Length > 32) { throw new Exception("key(" + key + ")長度超過32位"); } if (key.Length < 32) { key = key.PadRight(32, '0'); } return key; } private static string Key16Handler(string key) { if (key.Length > 16) { throw new Exception("key(" + key + ")長度超過16位"); } if (key.Length < 16) { key = key.PadRight(16, '0'); } return key; } private static string IvHandler(string iv) { if (iv.Length > 16) { throw new Exception("iv(" + iv + ")長度超過16位"); } if (iv.Length < 16) { iv = iv.PadRight(16, '0'); } return iv; } // // 摘要: // AES加密 (使用系統內建金鑰) // // 引數: // bs: // 位元組陣列 // // 返回結果: // 加密後字串 public static byte[] Encrypt(byte[] bs) { return Encrypt32(bs, "88888jghe8888uh8"); } // // 摘要: // AES解密 (使用系統內建金鑰) // // 引數: // bs: // 位元組陣列 // // 返回結果: // 解密後字串 public static byte[] Decrypt(byte[] bs) { return Decrypt32(bs, "88888jghe8888uh8"); } // // 摘要: // 位元組陣列加密 // // 引數: // bs: // 位元組陣列 // // key: // 32位金鑰(如果小於32位則自動補0) public static byte[] Encrypt32(byte[] bs, string key) { key = Key32Handler(key); return Encrypt(bs, key, "abudkdghij8888p8"); } // // 摘要: // 位元組陣列解密 // // 引數: // bs: // 加密後的位元組陣列 // // key: // 32位金鑰(如果小於32位則自動補0) public static byte[] Decrypt32(byte[] bs, string key) { key = Key32Handler(key); return Decrypt(bs, key, "abudkdghij8888p8"); } // // 摘要: // 位元組陣列加密 // // 引數: // bs: // 位元組陣列 // // key: // 16位金鑰(如果小於16位則自動補0) public static byte[] Encrypt16(byte[] bs, string key) { key = Key16Handler(key); return Encrypt(bs, key, "abudkdghij8888p8"); } // // 摘要: // 位元組陣列解密 // // 引數: // bs: // 加密後的位元組陣列 // // key: // 16位金鑰(如果小於16位則自動補0) public static byte[] Decrypt16(byte[] bs, string key) { key = Key16Handler(key); return Decrypt(bs, key, "abudkdghij8888p8"); } // // 摘要: // 位元組陣列解密 // // 引數: // bs: // 加密後的位元組陣列 // // key: // 16位金鑰(如果小於16位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) public static byte[] Decrypt16(byte[] bs, string key, string iv) { key = Key16Handler(key); return Decrypt(bs, key, iv); } // // 摘要: // 位元組陣列加密 // // 引數: // bs: // 位元組陣列 // // key: // 16位金鑰(如果小於16位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) public static byte[] Encrypt16(byte[] bs, string key, string iv) { key = Key16Handler(key); return Encrypt(bs, key, iv); } // // 摘要: // 位元組陣列解密 // // 引數: // bs: // 加密後的位元組陣列 // // key: // 32位金鑰(如果小於16位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) public static byte[] Decrypt32(byte[] bs, string key, string iv) { key = Key32Handler(key); return Decrypt(bs, key, iv); } // // 摘要: // 位元組陣列加密 // // 引數: // bs: // 位元組陣列 // // key: // 32位金鑰(如果小於32位則自動補0) // // iv: // 16位偏向量(如果小於16位則自動補0) public static byte[] Encrypt32(byte[] bs, string key, string iv) { key = Key32Handler(key); return Encrypt(bs, key, iv); } // // 摘要: // 位元組陣列解密 // // 引數: // bs: // 加密後的位元組陣列 // // key: // 16/32位金鑰 // // iv: // 16位偏向量(如果小於16位則自動補0) public static byte[] Decrypt(byte[] bs, string key, string iv) { byte[] bytes = Encoding.UTF8.GetBytes(key); return new RijndaelManaged { Key = bytes, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, IV = Encoding.UTF8.GetBytes(IvHandler(iv)) }.CreateDecryptor().TransformFinalBlock(bs, 0, bs.Length); } // // 摘要: // 位元組陣列加密 // // 引數: // bs: // 位元組陣列 // // key: // 16/32位金鑰 // // iv: // 16位偏向量(如果小於16位則自動補0) public static byte[] Encrypt(byte[] bs, string key, string iv) { byte[] bytes = Encoding.UTF8.GetBytes(key); return new RijndaelManaged { Key = bytes, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7, IV = Encoding.UTF8.GetBytes(IvHandler(iv)) }.CreateEncryptor().TransformFinalBlock(bs, 0, bs.Length); } }

實際呼叫時 我們需要 讀--加密--寫 讀--解密--寫--刪

          //--------------------------------加密--------------------------------
            //上傳   
            byte[] Newbuffur = AuthGetFileData(@"E:\待上傳檔案\交接事宜.docx");
            Bytes2File(Newbuffur, @"F:\加密後文件\", "交接事宜.docx");


            ////下載
            byte[] UpLoadbuffur = LoadGetFileData(@"F:\加密後文件\Enclosure\交接事宜.docx");
            Bytes2File(UpLoadbuffur, @"F:\加密解密後下載\", "交接事宜.docx");

呼叫

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="fileUrl">檔案路徑檔名稱</param>
        /// <returns>byte[]</returns>

        protected byte[] AuthGetFileData(string fileUrl)
        {
            using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {

                byte[] buffur = new byte[fs.Length];
                //從當前讀寫指標的位置往後讀取位元組的資料到位元組陣列中
                //buffur = File2Bytes(fileUrl);
                fs.Read(buffur, 0, buffur.Length);
                //讀寫指標從開頭往後移動位元組
                fs.Seek(0, SeekOrigin.Begin);
                byte[] NewByte = AesHelper.Encrypt(buffur);
                return NewByte;
            }
        }




        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="fileUrl">檔案路徑檔名稱</param>
        /// <returns>byte[]</returns>

        protected byte[] LoadGetFileData(string fileUrl)
        {
            using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                byte[] buffur = new byte[fs.Length];
                //buffur = File2Bytes(fileUrl);
                //從當前讀寫指標的位置往後讀取位元組的資料到位元組陣列中
                fs.Read(buffur, 0, buffur.Length);
                //讀寫指標從開頭往後移動位元組
                fs.Seek(0, SeekOrigin.Begin);

                byte[] NewByte = AesHelper.Decrypt(buffur);
                return NewByte;
            }
        }



        /// <summary>
        /// 將byte陣列轉換為檔案並儲存到指定地址
        /// </summary>
        /// <param name="buff">byte陣列</param>
        /// <param name="savepath">儲存地址</param>
        public static void Bytes2File(byte[] buff, string savepath, string fileName)
        {
            try
            {
                if (!System.IO.File.Exists(savepath  + fileName))
                {
                    System.IO.File.Create(savepath + fileName).Close(); 
                }
                //建立Process命令
                var cmd = new Process();
                using (FileStream fs = new FileStream(savepath  + fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {
                    BinaryWriter bw = new BinaryWriter(fs);
                    bw.Write(buff, 0, buff.Length);

                    bw.Close();
                    fs.Close();

                    fs.Dispose();
                    bw.Dispose();
                } 
            }
            catch (Exception e)
            {
                string kk = e.Message;
            }

        }