[ASP.NET]上傳檔案加解密

有些檔案由USER上傳檔案放在Server上,因為怕被人Copy走,所以存在Server上時,可以將該檔案加密後再存檔,Client端需要時,再將該File解密後傳回給Client。

有些檔案由USER上傳檔案放在Server上,因為怕被人Copy走,所以存在Server上時,可以將該檔案加密後再存檔,Client端需要時,再將該File解密後傳回給Client。

image

image

加解密的方式可參考Cryptography 101 for the .NET Framework,有詳細說明及範例。

我只是針對我需要的部份,在Crypto中加入2個Method如下,

'將檔案解密後,傳出Byte Array
Public Shared Function DecryptFile(ByVal Filename As String) As Byte()
    Dim result() As Byte
    If Not File.Exists(Filename) Then
        _exception = New CryptographicException(ERR_NO_FILE)
        Return result
    End If
    Dim inStream() As Byte
    Try
        inStream = File.ReadAllBytes(Filename)
    Catch ex As Exception
        _exception = New CryptographicException(ERR_FILE_READ)
        Return result
    End Try
    Try
        result = _Decrypt(inStream)
    Catch ex As Exception
        _exception = New CryptographicException(ex.Message, ex.InnerException)
    End Try
    Return result
End Function

'將傳入的Byte Array加密後,存檔
Public Shared Function EncryptFile(ByRef inStream() As Byte, ByVal Target As String) As Boolean
    'Make sure the target file can be written
    Try
        Dim fs As FileStream = File.Create(Target)
        fs.Close()
        fs.Dispose()
        File.Delete(Target)
    Catch ex As Exception
        _exception = New CryptographicException(ERR_FILE_WRITE)
        Return False
    End Try
    Dim cipherBytes() As Byte
    Try
        cipherBytes = _Encrypt(inStream)
    Catch ex As CryptographicException
        _exception = ex
        Return False
    End Try
    Dim encodedString As String = String.Empty
    If _encodingType = EncodingType.BASE_64 Then
        encodedString = System.Convert.ToBase64String(cipherBytes)
    Else
        encodedString = BytesToHex(cipherBytes)
    End If
    Dim encodedBytes() As Byte = UTF8.GetBytes(encodedString)
    'Create the encrypted file
    Dim outStream As FileStream = File.Create(Target)
    outStream.Write(encodedBytes, 0, encodedBytes.Length)
    outStream.Close()
    outStream.Dispose()
    Return True
End Function

所以在Server端讀到上傳的檔案後,就將它加密後存檔,當Client要檔案時,就解密後給Client端。

'上傳加密存檔
Protected Sub btnUploadFile_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUploadFile.Click
    '設定存檔的Full Name
    Dim saveFileName As String = System.IO.Path.Combine(Server.MapPath("~/Files"), System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName))
    '取出upload file的byte array資料
    Dim uploadFileReader As New System.IO.BinaryReader(FileUpload1.PostedFile.InputStream)
    Dim fileData() As Byte = uploadFileReader.ReadBytes(FileUpload1.PostedFile.ContentLength)
    '將檔案加密儲存*************************************************
    '設定加密的演算法
    Crypto.EncryptionAlgorithm = Crypto.Algorithm.RC2
    '設定加密的Key
    Crypto.Key = "RAINMAKER"
    Crypto.Encoding = Crypto.EncodingType.HEX
    Crypto.EncryptFile(fileData, saveFileName)
    '將檔案加密儲存*************************************************
    lblFileName.Text = saveFileName
End Sub

'Download 解密給Client
Protected Sub btnDownloadDecrypt_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnDownloadDecrypt.Click
    Response.ContentType = "application/octet-stream"
    Dim downloadFile As String = System.IO.Path.GetFileName(lblFileName.Text)
    If (Context.Request.Browser.Browser = "IE") Then
        '要編碼
        downloadFile = Context.Server.UrlPathEncode(downloadFile)
    End If
    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", downloadFile))
    '解密完後,再給Client****
    '設定加密的演算法
    Crypto.EncryptionAlgorithm = Crypto.Algorithm.RC2
    '設定加密的Key
    Crypto.Key = "RAINMAKER"
    Crypto.Encoding = Crypto.EncodingType.HEX
    Dim byFile() As Byte = Crypto.DecryptFile(lblFileName.Text)
    With Context.Response
        .Clear()
        .BufferOutput = False
        .OutputStream.Write(byFile, 0, byFile.Length)
        .Flush()
    End With
    Response.End()
End Sub

參考資料

Cryptography 101 for the .NET Framework

ASP.NET 如何設定強制下載檔案並正確處理中文檔名的問題

範例程式

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^