在傳輸過程中保護敏感資訊對於現代商業通訊至關重要,S/MIME 提供了一種經驗證的方式來保護電子郵件內容。Aspose.Email Cloud SDK for .NET 使開發人員能夠在 .NET 中以最少的程式碼加密和解密 S/MIME 電子郵件訊息。在本指南中,您將看到完整的 C# 範例、等效的 cURL 呼叫,以及確保訊息保持機密的實用技巧。

完整程式碼範例:在 .NET 中加密與解密 S/MIME 電子郵件訊息

此範例示範如何使用 Aspose.Email Cloud 函式庫對 S/MIME 電子郵件進行加密與解密。

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Aspose.Email.Cloud.Sdk.Api;
using Aspose.Email.Cloud.Sdk.Client;
using Aspose.Email.Cloud.Sdk.Model;
using Aspose.Email.Cloud.Sdk.Model.Requests;

namespace SmimeEncryptionDemo
{
    class Program
    {
        // Replace with your actual Aspose Cloud credentials
        private const string ClientId = "YOUR_CLIENT_ID";
        private const string ClientSecret = "YOUR_CLIENT_SECRET";

// File names used in Aspose Cloud storage
        private const string PublicCertFile = "public.cer";
        private const string PrivateKeyFile = "private.pfx";
        private const string PrivateKeyPassword = "pfxPassword";

// Local temporary files
        private const string EncryptedEmailPath = "encrypted_message.eml";
        private const string DecryptedEmailPath = "decrypted_message.eml";

static void Main()
        {
            // Configure Aspose Email Cloud SDK
            var config = new Configuration
            {
                ClientId = ClientId,
                ClientSecret = ClientSecret,
                BaseUrl = "https://api.aspose.cloud"
            };

var emailApi = new EmailApi(config);
            var storageApi = new StorageApi(config);

try
            {
                // -------------------------------------------------
                // Upload certificate and private key to cloud storage
                // -------------------------------------------------
                UploadFileToStorage(storageApi, PublicCertFile, "certs/" + PublicCertFile);
                UploadFileToStorage(storageApi, PrivateKeyFile, "certs/" + PrivateKeyFile);

// -------------------------------------------------
                // Build a simple email message
                // -------------------------------------------------
                var email = new EmailDto
                {
                    From = new MailAddress { Address = "sender@example.com" },
                    To = new List<MailAddress>
                    {
                        new MailAddress { Address = "recipient@example.com" }
                    },
                    Subject = "S/MIME Encryption Demo",
                    Body = new TextBody { Text = "Hello, this is a secure S/MIME message." }
                };

// -------------------------------------------------
                // Encrypt the email using the public certificate
                // -------------------------------------------------
                var encryptRequest = new EncryptRequest(email, "certs/" + PublicCertFile);
                var encryptedEmail = emailApi.Encrypt(encryptRequest);

// Save encrypted message locally for inspection
                File.WriteAllBytes(EncryptedEmailPath, Encoding.UTF8.GetBytes(encryptedEmail.Raw));
                Console.WriteLine($"Encrypted email saved to '{EncryptedEmailPath}'.");

// -------------------------------------------------
                // Decrypt the previously encrypted email using the private key
                // -------------------------------------------------
                var decryptRequest = new DecryptRequest(encryptedEmail, "certs/" + PrivateKeyFile, PrivateKeyPassword);
                var decryptedEmail = emailApi.Decrypt(decryptRequest);

// Save decrypted message locally
                File.WriteAllBytes(DecryptedEmailPath, Encoding.UTF8.GetBytes(decryptedEmail.Raw));
                Console.WriteLine($"Decrypted email saved to '{DecryptedEmailPath}'.");

// -------------------------------------------------
                // Verify that decryption succeeded
                // -------------------------------------------------
                Console.WriteLine("Decrypted Email Subject: " + decryptedEmail.Subject);
                Console.WriteLine("Decrypted Email Body: " + ((TextBody)decryptedEmail.Body).Text);
            }
            catch (ApiException apiEx)
            {
                // Common API errors (authentication, missing files, invalid certificates, etc.)
                Console.WriteLine($"API Error: {apiEx.ErrorCode} - {apiEx.Message}");
            }
            catch (Exception ex)
            {
                // General errors (IO, serialization, etc.)
                Console.WriteLine($"Unexpected error: {ex.Message}");
            }
        }

private static void UploadFileToStorage(StorageApi storageApi, string localPath, string remotePath)
        {
            if (!File.Exists(localPath))
                throw new FileNotFoundException($"File '{localPath}' not found.");

var fileBytes = File.ReadAllBytes(localPath);
            var uploadRequest = new UploadFileRequest
            {
                Path = remotePath,
                File = fileBytes
            };
            storageApi.UploadFile(uploadRequest);
        }
    }
}

注意: 此程式碼範例展示了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。若遇到任何問題,請參閱官方文件或聯繫支援團隊尋求協助。

使用 cURL 透過 REST API 進行 S/MIME 電子郵件加密與解密

以下是執行與上述 C# 程式碼相同操作的 REST 呼叫。請將佔位符值替換為您的實際憑證和檔案名稱。

# 1. Get an access token
curl -X POST "https://api.aspose.cloud/connect/token" \
     -H "Content-Type: application/x-www-form-urlencoded" \
     -d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
# 2. Upload the public certificate
curl -X PUT "https://api.aspose.cloud/v4.0/email/storage/file/certs/public.cer" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -T "public.cer"
# 3. Upload the private key
curl -X PUT "https://api.aspose.cloud/v4.0/email/storage/file/certs/private.pfx" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -T "private.pfx"

4. 建立 email JSON 載荷 (另存為 email.json)

cat > email.json <<EOF
{
  "from": { "address": "sender@example.com" },
  "to": [ { "address": "recipient@example.com" } ],
  "subject": "S/MIME Encryption Demo",
  "body": { "text": "Hello, this is a secure S/MIME message." }
}
EOF
# 5. Encrypt the email
curl -X POST "https://api.aspose.cloud/v4.0/email/encrypt" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d @email.json \
     -F "certificate=certs/public.cer"
# 6. Decrypt the email
curl -X POST "https://api.aspose.cloud/v4.0/email/decrypt" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -H "Content-Type: application/json" \
     -d @encrypted_email.json \
     -F "certificate=certs/private.pfx" \
     -F "password=pfxPassword"

如需所有端點的完整參考,請參閱官方 API 文件。

了解 .NET 程式碼中的加密與解密 S/MIME 電子郵件訊息

  1. 配置設定 - Configuration 物件保存您的 ClientId、ClientSecret 以及基礎 URL。此設定在每個 API 呼叫中皆為必需。
    var config = new Configuration { ClientId = ClientId, ClientSecret = ClientSecret, BaseUrl = "https://api.aspose.cloud" };
    
  2. 上傳檔案 - UploadFileToStorage 讀取本機檔案並使用 StorageApi.UploadFile 將其傳送至 Aspose Cloud 儲存空間。
    var fileBytes = File.ReadAllBytes(localPath);
    storageApi.UploadFile(new UploadFileRequest { Path = remotePath, File = fileBytes });
    
  3. 建立電子郵件 - 會以寄件者、收件者、主旨以及純文字內容填充 EmailDto 物件。
    var email = new EmailDto { From = new MailAddress { Address = "sender@example.com" }, ... };
    
  4. 加密 - EncryptRequest 接受電子郵件物件與公鑰憑證的路徑。EmailApi.Encrypt 回傳包含加密 MIME 內容的 EmailDto。
    var encryptRequest = new EncryptRequest(email, "certs/public.cer");
    var encryptedEmail = emailApi.Encrypt(encryptRequest);
    
  5. 解密 - DecryptRequest 提供加密的電子郵件、私鑰路徑及其密碼。EmailApi.Decrypt 產生原始訊息。
    var decryptRequest = new DecryptRequest(encryptedEmail, "certs/private.pfx", PrivateKeyPassword);
    var decryptedEmail = emailApi.Decrypt(decryptRequest);
    

這些步驟直接對應先前顯示的 REST 呼叫,讓您可以在 C# 與原始 HTTP 之間靈活選擇。

S/MIME 電子郵件處理的先決條件與設定

  1. 安裝 Aspose.Email Cloud SDK for .NET:
    dotnet add package Aspose.Email-Cloud
    
  2. 確保您擁有有效的 Aspose Cloud 帳戶,並取得 ClientId 和 ClientSecret。
  3. 從官方發行頁面下載 SDK 二進位檔案:Aspose.Email Cloud SDK for .NET Download。
  4. 將您的公用憑證(*.cer)和私密金鑰(*.pfx)檔案放置在本機資料夾中,準備上傳。

S/MIME 操作的配置選項

  • Base URL - 您可以在 Configuration 物件中更改 BaseUrl,如果需要針對不同區域。
var config = new Configuration { BaseUrl = "https://api.aspose.cloud" };
  • Timeout Settings - 為大型訊息調整 HTTP 客戶端的逾時時間。
config.Timeout = 300000; // 5 minutes
  • Logging - 透過 SDK 內建的記錄器啟用請求/回應日誌以進行除錯(請參閱 API 參考以取得詳細資訊)。

如需完整的參數列表,請參閱 API 參考。

安全 S/MIME 電子郵件處理的最佳實踐

  • 使用安全路徑將證書和私鑰存儲在 Aspose Cloud 儲存中,並限制存取權限。
  • 在加密之前驗證證書鏈,以避免執行時失敗。
  • 將私鑰密碼從原始碼中移除;使用環境變數或祕密管理器。
  • 解密後,透過檢查主旨和內容是否符合預期值來驗證訊息完整性。
  • 只記錄非敏感資訊;絕不要將原始私鑰寫入主控台輸出。

總結

在 .NET 中加密和解密 S/MIME 電子郵件訊息相當簡單,只需使用 Aspose.Email Cloud SDK for .NET。該函式庫負責證書管理、MIME 格式化以及加密運算等繁重工作,讓您專注於業務邏輯。請務必保護您的憑證、對私鑰使用強密碼,並在部署至生產環境前使用真實證書測試工作流程。商業使用時需要付費授權;您可以在產品頁面查看價格,並在臨時授權頁面取得評估用的臨時授權。

常見問題

  • Aspose.Email Cloud SDK for .NET 如何在 .NET 中加密和解密 S/MIME 電子郵件訊息?
    SDK 提供 Encrypt 和 Decrypt 方法,接受 EmailDto 和證書路徑。它在伺服器端執行 S/MIME 包裝/解包,並返回處理後的 MIME 內容。

  • 我需要運行郵件伺服器來測試加密訊息嗎?
    不需要。SDK 可獨立於任何郵件伺服器運作。您可以加密、保存 .eml 檔案,然後在本機或透過 API 解密。

  • 我可以在其他語言中使用相同的程式碼嗎?
    是的。底層的 REST API 與語言無關。您可以從 Java、Python、PHP 或任何能發送 HTTP 請求的平台呼叫相同的端點。

  • 我可以在哪裡找到更多範例和詳細的 API 規格說明?
    詳細的指南和參考資料可在 Aspose.Email Cloud documentation 和 API 參考 中取得。

閱讀更多