.NET 幫助

C# XOR(如何為開發人員工作)

介紹

在使用 C# 處理 PDF 時,安全性和資料操作是重要的考量。 一種有效的輕量級加密和數據轉換技術是位元 XOR 運算。 此技術廣泛用於邏輯運算、資料混淆和浮水印。

IronPDF 是一個強大的 C# 庫,用於處理 PDF,允許開發人員將按位邏輯運算符整合到 PDF 工作流程中。 通過使用邏輯 XOR 運算符,我們可以對 PDF 中的文字、圖像和元數據進行轉換。

在本指南中,我們將探討IronPDF進行PDF處理時應用它。

了解 C# 中的 XOR

XOR 是什麼?

XOR(也稱為邏輯異或運算)在代碼中由'^'符號表示,是一種用於執行位元異或運算的二元運算。 那它與邏輯 OR 運算符有什麼不同呢? 雖然這兩個運算子名稱相似,但在 XOR 運算子的名稱中使用exclusive這個詞正是區別這兩者的關鍵。 邏輯或運算符更像是一個包容性的運算元,更像是 AND/OR 運算符,如果兩個運算元中的一個或兩個為真,它將返回真。

另一方面,XOR 的運作方式有些不同。 這個位元運算子評估布林值,只有當提供的兩個運算元之一返回真時才會返回真。 如果兩個選擇返回相同的結果,則返回 false。

為了更簡單的概述,我們來看一個展示 XOR 工作原理的真值表:

in1

in2

1

1

1

1

1

1

而 OR 的作用是这样的:

in1

in2

1

1

1

1

1

例如:

byte a = 0b10101010; // 170 in decimal
byte b = 0b11001100; // 204 in decimal
byte result = (byte)(a ^ b); // XOR operation
Console.WriteLine(Convert.ToString(result, 2)); // Output: 01100110
byte a = 0b10101010; // 170 in decimal
byte b = 0b11001100; // 204 in decimal
byte result = (byte)(a ^ b); // XOR operation
Console.WriteLine(Convert.ToString(result, 2)); // Output: 01100110
Dim a As Byte = &B10101010 ' 170 in decimal
Dim b As Byte = &B11001100 ' 204 in decimal
Dim result As Byte = CByte(a Xor b) ' XOR operation
Console.WriteLine(Convert.ToString(result, 2)) ' Output: 01100110
$vbLabelText   $csharpLabel

損壞的圖像

清除替代文字

在布林表達式中,XOR 可以應用於布林操作數:

bool a = true;
bool b = false;
bool result = a ^ b; // Logical XOR operator
Console.WriteLine(result); // Output: True
bool a = true;
bool b = false;
bool result = a ^ b; // Logical XOR operator
Console.WriteLine(result); // Output: True
Dim a As Boolean = True
Dim b As Boolean = False
Dim result As Boolean = a Xor b ' Logical XOR operator
Console.WriteLine(result) ' Output: True
$vbLabelText   $csharpLabel

C# XOR(開發人員如何運作):圖2 - 布林運算式輸出

從Pixabay添加上傳

或將圖片拖放到此處

清除替代文字

在這裡,我們使用位元運算來比較兩個操作數。 右運算元與左運算元不同,這確保輸出為真。 若第二個操作數與第一個相同,我們將會看到 false。

運算子優先順序和 XOR

位元運算 XOR 的運算子優先順序低於算術運算子,但高於位元補數(~)和邏輯否定(!)。

例如:

int x = 5 ^ 2 + 3; 
Console.WriteLine(x); // Output: 0
int x = 5 ^ 2 + 3; 
Console.WriteLine(x); // Output: 0
CONVERTER NOT RUNNING
$vbLabelText   $csharpLabel

損壞的圖像

新增圖片替代文字

C#中的運算子優先順序

  • 加法運算符(+)的優先級高於按位異或運算符(^)。

    • 這意味著該表達式被評估為:
int x = 5 ^ (2 + 3); // Equivalent to 5 ^ 5
int x = 5 ^ (2 + 3); // Equivalent to 5 ^ 5
Dim x As Integer = 5 Xor (2 + 3) ' Equivalent to 5 ^ 5
$vbLabelText   $csharpLabel
  • 現在,計算按位 XOR
5  = 00000101  
    5  = 00000101  
    -------------
    XOR = 00000000  (Decimal 0)
5  = 00000101  
    5  = 00000101  
    -------------
    XOR = 00000000  (Decimal 0)
CONVERTER NOT RUNNING
$vbLabelText   $csharpLabel
  • 最終結果: 0。

XOR 用於 PDF 安全性和處理

使用 XOR 進行 PDF 的基礎加密

由於 XOR 可以使用相同的操作對數據進行編碼和解碼,因此經常用於輕量級加密。 雖然與 AES 加密相比,它不是一種強大的安全措施,但它提供了一種快速混淆 PDF 內容的方法。

XOR 用於圖像可見性切換

XOR 可用於動態切換基於圖像的水印的可見性。 例如,水印可以使用 XOR 編碼,僅在應用已知密鑰時才可見。 此相同方法可應用於文字水印和印戳。

XOR 在元數據混淆中

PDF 中的元數據通常包含敏感細節,如文件作者、創建日期和其他標識符。 XOR 可應用於元數據欄位,使其在未解碼的情況下無法讀取。

使用 IronPDF 在 C# 中實現 XOR

基於 XOR 的 PDF 文字處理

在將文本插入 PDF 之前應用 XOR 可以提供一種基本的模糊處理形式。 在以下範例中,我們仔細看看此過程中涉及的程式碼。

範例:使用 XOR 在 IronPDF 中編碼和解碼文字

using IronPdf;
using IronSoftware.Drawing;
using System;
using System.Text;
class Program
{
    static string XorEncryptDecrypt(string text, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in text)
        {
            output.Append((char)(c ^ key));
        }
        return output.ToString();
    }
    static void Main()
    {
        var text = "Confidential Information";
        char key = 'X'; // Simple XOR key
        string encodedText = XorEncryptDecrypt(text, key);
        var pdf = new PdfDocument(270, 270);
        pdf.DrawText(encodedText, FontTypes.TimesNewRoman.Name, FontSize: 40, PageIndex: 0, X: 150, Y: 300, Color.Black, Rotation: 0);
        pdf.SaveAs("XorEncoded.pdf");
        Console.WriteLine("PDF with XOR-encoded text created.");
    }
}
using IronPdf;
using IronSoftware.Drawing;
using System;
using System.Text;
class Program
{
    static string XorEncryptDecrypt(string text, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in text)
        {
            output.Append((char)(c ^ key));
        }
        return output.ToString();
    }
    static void Main()
    {
        var text = "Confidential Information";
        char key = 'X'; // Simple XOR key
        string encodedText = XorEncryptDecrypt(text, key);
        var pdf = new PdfDocument(270, 270);
        pdf.DrawText(encodedText, FontTypes.TimesNewRoman.Name, FontSize: 40, PageIndex: 0, X: 150, Y: 300, Color.Black, Rotation: 0);
        pdf.SaveAs("XorEncoded.pdf");
        Console.WriteLine("PDF with XOR-encoded text created.");
    }
}
Imports IronPdf
Imports IronSoftware.Drawing
Imports System
Imports System.Text
Friend Class Program
	Private Shared Function XorEncryptDecrypt(ByVal text As String, ByVal key As Char) As String
		Dim output As New StringBuilder()
		For Each c As Char In text
			output.Append(ChrW(AscW(c) Xor AscW(key)))
		Next c
		Return output.ToString()
	End Function
	Shared Sub Main()
		Dim text = "Confidential Information"
		Dim key As Char = "X"c ' Simple XOR key
		Dim encodedText As String = XorEncryptDecrypt(text, key)
		Dim pdf = New PdfDocument(270, 270)
		pdf.DrawText(encodedText, FontTypes.TimesNewRoman.Name, FontSize:= 40, PageIndex:= 0, X:= 150, Y:= 300, Color.Black, Rotation:= 0)
		pdf.SaveAs("XorEncoded.pdf")
		Console.WriteLine("PDF with XOR-encoded text created.")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

C# XOR(它對開發者的工作原理):圖 4 - 編碼文本 PDF 輸出

從Pixabay添加上傳

或將圖片拖放到此處

清除替代文字

這裡使用 XOR 函數在將文字插入 PDF 之前進行混淆。 相同的函數可以透過再次使用相同的密鑰進行 XOR 來解密。

XOR 用於 PDF 圖像操縱

在將圖像嵌入 PDF 之前,也可以對其進行 XOR 操作,改變其像素值,以便只有在解碼後才可查看。

範例:在插入到PDF之前對影像像素應用XOR

using IronPdf;
using IronPdf.Editing;
using System;
using System.Drawing;
using System.Text;
class Program
{
    static Bitmap XorImage(Bitmap image, byte key)
    {
        for (int y = 0; y < image.Height; y++)
        {
            for (int x = 0; x < image.Width; x++)
            {
                Color pixel = image.GetPixel(x, y);
                Color newPixel = Color.FromArgb(pixel.A, pixel.R ^ key, pixel.G ^ key, pixel.B ^ key);
                image.SetPixel(x, y, newPixel);
            }
        }
        return image;
    }
    static void Main()
    {
        var pdf = new PdfDocument(270, 270);
        Bitmap image = new Bitmap("example_image.png");
        Bitmap encodedImage = XorImage(image, 0x55);
        encodedImage.Save("XorImage.png");
        ImageStamper imageStamp = new ImageStamper("XorImage.png")
        {
            VerticalAlignment = VerticalAlignment.Middle,
        };
        pdf.SaveAs("XorImagePDF.pdf");
        Console.WriteLine("PDF with XOR-modified image created.");
    }
}
using IronPdf;
using IronPdf.Editing;
using System;
using System.Drawing;
using System.Text;
class Program
{
    static Bitmap XorImage(Bitmap image, byte key)
    {
        for (int y = 0; y < image.Height; y++)
        {
            for (int x = 0; x < image.Width; x++)
            {
                Color pixel = image.GetPixel(x, y);
                Color newPixel = Color.FromArgb(pixel.A, pixel.R ^ key, pixel.G ^ key, pixel.B ^ key);
                image.SetPixel(x, y, newPixel);
            }
        }
        return image;
    }
    static void Main()
    {
        var pdf = new PdfDocument(270, 270);
        Bitmap image = new Bitmap("example_image.png");
        Bitmap encodedImage = XorImage(image, 0x55);
        encodedImage.Save("XorImage.png");
        ImageStamper imageStamp = new ImageStamper("XorImage.png")
        {
            VerticalAlignment = VerticalAlignment.Middle,
        };
        pdf.SaveAs("XorImagePDF.pdf");
        Console.WriteLine("PDF with XOR-modified image created.");
    }
}
Imports IronPdf
Imports IronPdf.Editing
Imports System
Imports System.Drawing
Imports System.Text
Friend Class Program
	Private Shared Function XorImage(ByVal image As Bitmap, ByVal key As Byte) As Bitmap
		For y As Integer = 0 To image.Height - 1
			For x As Integer = 0 To image.Width - 1
				Dim pixel As Color = image.GetPixel(x, y)
				Dim newPixel As Color = Color.FromArgb(pixel.A, pixel.R Xor key, pixel.G Xor key, pixel.B Xor key)
				image.SetPixel(x, y, newPixel)
			Next x
		Next y
		Return image
	End Function
	Shared Sub Main()
		Dim pdf = New PdfDocument(270, 270)
		Dim image As New Bitmap("example_image.png")
		Dim encodedImage As Bitmap = XorImage(image, &H55)
		encodedImage.Save("XorImage.png")
		Dim imageStamp As New ImageStamper("XorImage.png") With {.VerticalAlignment = VerticalAlignment.Middle}
		pdf.SaveAs("XorImagePDF.pdf")
		Console.WriteLine("PDF with XOR-modified image created.")
	End Sub
End Class
$vbLabelText   $csharpLabel

XOR 圖像輸出

C# XOR (開發人員如何使用):圖 5 - XOR 圖像輸出

從Pixabay添加上傳

或將圖片拖放到此處

清除替代文字

這種方法使用 XOR 改變像素顏色,確保圖像在未使用正確密鑰解碼的情況下顯得混亂。

XOR 用於 PDF 元資料處理

PDF 中的元數據通常包含可能需要混淆的重要信息。 XOR 可以應用於元數據欄位,使它們在沒有解密密鑰的情況下不可讀。

範例:PDF 元數據欄位的 XOR 加密

using IronPdf;
using System;
using System.Text;
class Program
{
    static string XorEncryptDecrypt(string input, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in input)
        {
            output.Append((char)(c ^ key));
        }
        return output.ToString();
    }
    static void Main()
    {
        var pdf = new PdfDocument(270, 270);
        pdf.MetaData.Author = XorEncryptDecrypt("John Doe", 'K');
        pdf.MetaData.Title = XorEncryptDecrypt("Confidential Report", 'K');
        pdf.SaveAs("XorMetadata.pdf");
        Console.WriteLine("PDF with XOR-encoded metadata created.");
    }
}
using IronPdf;
using System;
using System.Text;
class Program
{
    static string XorEncryptDecrypt(string input, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in input)
        {
            output.Append((char)(c ^ key));
        }
        return output.ToString();
    }
    static void Main()
    {
        var pdf = new PdfDocument(270, 270);
        pdf.MetaData.Author = XorEncryptDecrypt("John Doe", 'K');
        pdf.MetaData.Title = XorEncryptDecrypt("Confidential Report", 'K');
        pdf.SaveAs("XorMetadata.pdf");
        Console.WriteLine("PDF with XOR-encoded metadata created.");
    }
}
Imports IronPdf
Imports System
Imports System.Text
Friend Class Program
	Private Shared Function XorEncryptDecrypt(ByVal input As String, ByVal key As Char) As String
		Dim output As New StringBuilder()
		For Each c As Char In input
			output.Append(ChrW(AscW(c) Xor AscW(key)))
		Next c
		Return output.ToString()
	End Function
	Shared Sub Main()
		Dim pdf = New PdfDocument(270, 270)
		pdf.MetaData.Author = XorEncryptDecrypt("John Doe", "K"c)
		pdf.MetaData.Title = XorEncryptDecrypt("Confidential Report", "K"c)
		pdf.SaveAs("XorMetadata.pdf")
		Console.WriteLine("PDF with XOR-encoded metadata created.")
	End Sub
End Class
$vbLabelText   $csharpLabel

輸出

C# XOR(對開發者來說如何運作):圖6 - XOR編碼的元數據輸出

從Pixabay添加上傳

或將圖片拖放到此處

清除替代文字

在這裡,元數據欄位被 XOR 加密,防止輕易獲取敏感信息。

最佳實踐和限制

何时在 PDF 处理中使用 XOR

  • 輕量級混淆文本、圖像和元數據
  • 簡單的浮水印技術
  • 不需要高安全性的基本加密

安全問題與替代方案

  • XOR 不是一種強大的加密方法,不應用於保護高度敏感的信息。
  • 為了更強的安全性,請考慮使用 AES 加密或 PDF 密碼保護功能。

大型 PDF 的效能考量

  • 對大型 PDF 文件(特別是圖像)執行 XOR 操作可能會影響性能。
  • 考慮僅對選定元素應用 XOR 進行優化,而不是整個 PDF。

結論

XOR 是一種簡單但有效的技術,用於位元邏輯運算、浮水印和 PDF 中的元資料處理。 通過對文本、圖像和元數據運用 XOR 變換,開發人員可以創建具有可逆混淆的 PDF。 然而,對於更高的安全需求,應使用更強的加密方法。

透過了解位元邏輯運算子、運算子優先順序以及布林表示式在 C# 中的運作方式,開發人員可以在各種實用應用中有效地將 XOR 與 IronPDF 結合使用。 還沒有 IronPDF 嗎? 試用免費試用版,看看IronPDF今天如何將您的PDF項目提升到新的高度!

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# ObservableCollection(它如何為開發人員工作)
下一個 >
C# Interlocked(如何為開發人員工作)