萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

VB.NET 2008 實戰:基於 DES 對稱加密的文字加解密程式完整教學

使用 Visual Studio 2008 (VB.NET) 與 System.Security.Cryptography 命名空間,實作一個完整的文字加密/解密 WinForms 程式。採用 DES 對稱加密算法,涵蓋介面設計、類別封裝、事件處理、錯誤處理全流程,適合 .NET 入門開發者理解加密基礎與 WinForms 開發模式。

開發環境與專案建立

  • Visual Studio 2008 / .NET Framework 3.5
  • 專案類型:Windows Forms Application
  • 目標平台:x86 (Any CPU 亦可)

介面設計

控件名稱關鍵屬性用途
LabelLabel1Text="原始文字"提示標籤
TextBoxTextBox1Multiline=True, ScrollBars=Vertical輸入待加密文字
LabelLabel2Text="加密結果"提示標籤
TextBoxTextBox2Multiline=True, ScrollBars=Vertical, ReadOnly=True顯示 Base64 加密串
LabelLabel3Text="解密結果"提示標籤
TextBoxTextBox3Multiline=True, ScrollBars=Vertical, ReadOnly=True顯示解密後明文
ButtonButton1Text="加密 (&E)"觸發加密
ButtonButton2Text="解密 (&D)"觸發解密

核心加密類 CryptoHelper

Imports System
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text

Public Class CryptoHelper
    ' DES 需要 8 字節 Key 和 8 字節 IV
    Private Shared ReadOnly KeyBytes As Byte() = Encoding.Default.GetBytes("20000000") ' 8 字節
    Private Shared ReadOnly IVBytes As Byte() = Encoding.Default.GetBytes("12345678")   ' 8 字節

    Public Shared Function Encrypt(plainText As String) As String
        If String.IsNullOrEmpty(plainText) Then Return String.Empty
        Try
            Dim inputBytes = Encoding.Default.GetBytes(plainText)
            Using ms As New MemoryStream()
                Using des As New DESCryptoServiceProvider()
                    Using cs As New CryptoStream(ms, des.CreateEncryptor(KeyBytes, IVBytes), CryptoStreamMode.Write)
                        cs.Write(inputBytes, 0, inputBytes.Length)
                        cs.FlushFinalBlock()
                        Return Convert.ToBase64String(ms.ToArray())
                    End Using
                End Using
            End Using
        Catch ex As CryptographicException
            Throw New ApplicationException("加密失敗: " & ex.Message, ex)
        End Try
    End Function

    Public Shared Function Decrypt(cipherBase64 As String) As String
        If String.IsNullOrEmpty(cipherBase64) Then Return String.Empty
        Try
            Dim inputBytes = Convert.FromBase64String(cipherBase64)
            Using ms As New MemoryStream()
                Using des As New DESCryptoServiceProvider()
                    Using cs As New CryptoStream(ms, des.CreateDecryptor(KeyBytes, IVBytes), CryptoStreamMode.Write)
                        cs.Write(inputBytes, 0, inputBytes.Length)
                        cs.FlushFinalBlock()
                        Return Encoding.Default.GetString(ms.ToArray())
                    End Using
                End Using
            End Using
        Catch ex As CryptographicException
            Throw New ApplicationException("解密失敗: " & ex.Message, ex)
        End Try
    End Function
End Class

Form 代碼隱藏碼

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            TextBox2.Text = CryptoHelper.Encrypt(TextBox1.Text)
        Catch ex As Exception
            MessageBox.Show("加密錯誤: " & ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Try
            TextBox3.Text = CryptoHelper.Decrypt(TextBox2.Text)
        Catch ex As Exception
            MessageBox.Show("解密錯誤: " & ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class

關鍵技術點解析

  1. DES 對稱加密:鍵長 56 位 (含 8 位校驗),塊大小 64 位。已被 AES 取代,**不建議用於新系統機密數據**。
  2. Key/IV 硬編碼風險:示例中硬編碼 "20000000"、"12345678",實際專案必須從安全配置/金鑰管理系統讀取。
  3. Encoding.Default:依賴系統當前 ANSI 代碼頁,**跨平台/跨地區會亂碼**,生產環境統一用 Encoding.UTF8。
  4. CryptoStream 模式:CryptoStreamMode.Write 表示寫入明文/密文流,FlushFinalBlock() 必須調用以完成填充/終止區塊。
  5. Base64 編碼:將二進制密文轉為可存儲/傳輸的 ASCII 字符串。
  6. Using 區塊:確保 IDisposable 資源 (Stream、CryptoServiceProvider、CryptoStream) 及時釋放。

運行測試

  1. 輸入:Hello, VB.NET 加密測試!
  2. 點「加密」→ TextBox2 顯示 Base64 字符串 (如 xYzAbC123==)
  3. 點「解密」→ TextBox3 還原原文

程式運行截圖

安全性升級路線圖

層級算法Key Size備註
教學/非敏感DES56-bit本例使用,僅供學習
生產標準AES (Rijndael)128/192/256-bitAes.Create()、GCM 模式 (需 .NET Core 3.1+)
高安全AES-GCM / ChaCha20-Poly1305256-bit認證加密 (AEAD),防篡改
密碼派生PBKDF2 / Argon2-從密碼生成 Key/IV,Rfc2898DeriveBytes

現代 .NET (Core/5/6/7/8) 寫法差異

' 現代寫法更簡潔、安全、跨平台
Using aes = Aes.Create()
  aes.Key = keyBytes
  aes.IV = ivBytes
  Using encryptor = aes.CreateEncryptor()
    ' ... 同 CryptoStream 模式
  End Using
End Using

' 或 .NET 7+ 暫不支援內建 AEAD,需引用 System.Security.Cryptography.Aead (實驗) 或第三方庫

這個範例展示了「加密服務封裝 + WinForms 事件驅動」的經典架構。理解 CryptoStream 流式處理、Base64 編碼、Key/IV 管理,是進階學習 TLS、JWT、數據保護 API 的基石。

copyright © 萬盛學電腦網 all rights reserved