Skip to footer content
.NET HELP

C# XOR (How it Works for Developers)

When working with PDFs in C#, security and data manipulation are important concerns. One effective technique for lightweight encryption and data transformation is the bitwise XOR operation. This technique is widely used in logical operations, data obfuscation, and watermarking.

IronPDF, a powerful C# library for handling PDFs, allows developers to integrate bitwise logical operators into PDF workflows. By leveraging the logical XOR operator, we can apply transformations to text, images, and metadata within PDFs.

In this guide, we will explore how XOR works, how it interacts with bool operands, and how to apply it in PDF processing with IronPDF.

Understanding XOR in C#

What is XOR?

XOR (otherwise known as the logical exclusive OR operator) is represented in code by the ^ symbol and is a binary operation that performs bitwise XOR operations. How is it different from the logical OR operator? While these two operators share a similar name, the use of the word "exclusive" in XOR's operator name sets them apart. The logical OR operator is more of an inclusive operand, equivalent to an AND/OR operator, where it will return true if one or both of the two operands are true.

XOR, on the other hand, works differently. This bitwise operator evaluates Boolean values and will only return true if exactly one of the two operands is true. If both choices result in the same value, it returns false.

For a more simplified overview, let's look at a truth table that demonstrates how XOR works:

in1in2out
101
011
110
000

Whereas OR works like this:

in1in2out
101
011
111
000

For example:

// Example demonstrating bitwise XOR operation
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
// Example demonstrating bitwise XOR operation
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
' Example demonstrating bitwise XOR operation
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

In boolean expressions, XOR can be applied to bool operands:

// Example demonstrating logical XOR operation with bools
bool a = true;
bool b = false;
bool result = a ^ b; // Logical XOR operator
Console.WriteLine(result); // Output: True
// Example demonstrating logical XOR operation with bools
bool a = true;
bool b = false;
bool result = a ^ b; // Logical XOR operator
Console.WriteLine(result); // Output: True
' Example demonstrating logical XOR operation with bools
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

Here, we perform a bitwise operation to compare two operands. The right operand is different from the left, ensuring that the output is true. Had the second operand been the same as the first, we would have seen false.

Operator Precedence and XOR

The bitwise XOR operation has lower operator precedence than arithmetic operators but higher than the bitwise complement (~) and logical negation (!).

For example:

// Example demonstrating operator precedence
int x = 5 ^ 2 + 3; 
Console.WriteLine(x); // Output: 0
// Example demonstrating operator precedence
int x = 5 ^ 2 + 3; 
Console.WriteLine(x); // Output: 0
' Example demonstrating operator precedence
Dim x As Integer = 5 Xor 2 + 3
Console.WriteLine(x) ' Output: 0
$vbLabelText   $csharpLabel

Operator Precedence in C#

    • (Addition) has higher precedence than ^ (Bitwise XOR).

    • This means the expression is evaluated as:
    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
    • Now, calculating bitwise XOR:
    5  = 00000101  
    5  = 00000101  
    -------------
    XOR = 00000000  (Decimal 0)
  • Final result: 0.

XOR for PDF Security and Processing

Using XOR for Basic Encryption in PDFs

Since XOR can encode and decode data with the same operation, it is often used for lightweight encryption. While it is not a strong security measure compared to AES encryption, it provides a quick way to obfuscate PDF content.

XOR for Image Visibility Toggling

XOR can be used to dynamically toggle the visibility of image-based stamps and watermarks. For instance, a watermark can be encoded using XOR, making it viewable only when a known key is applied. This same method could be applied to text-based watermarks and stamps.

XOR in Metadata Obfuscation

PDF metadata often contains sensitive details such as document author, creation date, and other identifiers. XOR can be applied to metadata fields to make them unreadable without decoding.

Implementing XOR with IronPDF in C#

XOR-Based PDF Text Processing

Applying XOR to text before inserting it into a PDF can provide a basic form of obfuscation. In the following example, we take a closer look at the code involved in this process.

Example: Encoding and Decoding Text with XOR in IronPDF

using IronPdf;
using System;
using System.Text;

class Program
{
    // Function to encrypt and decrypt text using XOR
    static string XorEncryptDecrypt(string text, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in text)
        {
            output.Append((char)(c ^ key)); // XOR operation
        }
        return output.ToString();
    }

    static void Main()
    {
        var text = "Confidential Information";
        char key = 'X'; // Simple XOR key
        string encodedText = XorEncryptDecrypt(text, key); // Encrypt text
        var pdf = new PdfDocument(270, 270); // Create a new PDF document
        pdf.DrawText(encodedText, FontTypes.TimesNewRoman.Name, FontSize: 40, 
            PageIndex: 0, X: 150, Y: 300, Color.Black, Rotation: 0); // Draw the text
        pdf.SaveAs("XorEncoded.pdf"); // Save the PDF
        Console.WriteLine("PDF with XOR-encoded text created.");
    }
}
using IronPdf;
using System;
using System.Text;

class Program
{
    // Function to encrypt and decrypt text using XOR
    static string XorEncryptDecrypt(string text, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in text)
        {
            output.Append((char)(c ^ key)); // XOR operation
        }
        return output.ToString();
    }

    static void Main()
    {
        var text = "Confidential Information";
        char key = 'X'; // Simple XOR key
        string encodedText = XorEncryptDecrypt(text, key); // Encrypt text
        var pdf = new PdfDocument(270, 270); // Create a new PDF document
        pdf.DrawText(encodedText, FontTypes.TimesNewRoman.Name, FontSize: 40, 
            PageIndex: 0, X: 150, Y: 300, Color.Black, Rotation: 0); // Draw the text
        pdf.SaveAs("XorEncoded.pdf"); // Save the PDF
        Console.WriteLine("PDF with XOR-encoded text created.");
    }
}
Imports IronPdf
Imports System
Imports System.Text

Friend Class Program
	' Function to encrypt and decrypt text using XOR
	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))) ' XOR operation
		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) ' Encrypt text
		Dim pdf = New PdfDocument(270, 270) ' Create a new PDF document
		pdf.DrawText(encodedText, FontTypes.TimesNewRoman.Name, FontSize:= 40, PageIndex:= 0, X:= 150, Y:= 300, Color.Black, Rotation:= 0) ' Draw the text
		pdf.SaveAs("XorEncoded.pdf") ' Save the PDF
		Console.WriteLine("PDF with XOR-encoded text created.")
	End Sub
End Class
$vbLabelText   $csharpLabel

Here, the XOR function is used to obfuscate text before inserting it into a PDF. The same function can decrypt it by applying XOR again with the same key.

XOR for PDF Image Manipulation

XOR can also be applied to images before embedding them into a PDF, altering their pixel values so that they are only viewable when decoded.

Example: Applying XOR on Image Pixels Before Inserting into PDFs

using IronPdf;
using IronPdf.Editing;
using System;
using System.Drawing;

class Program
{
    // Function to XOR image pixels
    static Bitmap XorImage(Bitmap image, byte key)
    {
        for (int y = 0; y < image.Height; y++)
        {
            for (int x = 0; x < image.Width; x++)
            {
                // Apply XOR operation to each color channel except alpha
                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); // Set the new pixel value
            }
        }
        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;

class Program
{
    // Function to XOR image pixels
    static Bitmap XorImage(Bitmap image, byte key)
    {
        for (int y = 0; y < image.Height; y++)
        {
            for (int x = 0; x < image.Width; x++)
            {
                // Apply XOR operation to each color channel except alpha
                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); // Set the new pixel value
            }
        }
        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

Friend Class Program
	' Function to XOR image pixels
	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
				' Apply XOR operation to each color channel except alpha
				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) ' Set the new pixel value
			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

This approach alters pixel colors using XOR, ensuring that the image appears scrambled unless decoded with the correct key.

XOR for PDF Metadata Handling

PDF metadata often contains important information that may need to be obfuscated. XOR can be applied to metadata fields to make them unreadable without the decryption key.

Example: XOR Encryption of PDF Metadata Fields

using IronPdf;
using System;
using System.Text;

class Program
{
    // Function to encrypt and decrypt metadata using XOR
    static string XorEncryptDecrypt(string input, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in input)
        {
            output.Append((char)(c ^ key)); // XOR operation
        }
        return output.ToString();
    }

    static void Main()
    {
        var pdf = new PdfDocument(270, 270);
        // Apply XOR to obfuscate metadata
        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
{
    // Function to encrypt and decrypt metadata using XOR
    static string XorEncryptDecrypt(string input, char key)
    {
        StringBuilder output = new StringBuilder();
        foreach (char c in input)
        {
            output.Append((char)(c ^ key)); // XOR operation
        }
        return output.ToString();
    }

    static void Main()
    {
        var pdf = new PdfDocument(270, 270);
        // Apply XOR to obfuscate metadata
        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
	' Function to encrypt and decrypt metadata using XOR
	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))) ' XOR operation
		Next c
		Return output.ToString()
	End Function

	Shared Sub Main()
		Dim pdf = New PdfDocument(270, 270)
		' Apply XOR to obfuscate metadata
		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

Here, the metadata fields are XOR-encrypted, preventing easy access to sensitive information.

Best Practices and Limitations

When to Use XOR in PDF Processing

  • Lightweight obfuscation of text, images, and metadata
  • Simple watermarking techniques
  • Basic encryption where high security is not required

Security Concerns and Alternatives

  • XOR is not a strong encryption method and should not be used for securing highly sensitive information.
  • For stronger security, consider AES encryption or PDF password protection features.

Performance Considerations in Large PDFs

  • XOR operations on large PDF files, especially images, may impact performance.
  • Consider optimizing by applying XOR to selective elements rather than entire PDFs.

Conclusion

XOR is a simple yet effective technique for bitwise logical operations, watermarking, and metadata handling in PDFs. By applying XOR transformations to text, images, and metadata, developers can create PDFs with reversible obfuscation. However, for higher security needs, stronger encryption methods should be used.

By understanding how bitwise logical operators, operator precedence, and boolean expressions work in C#, developers can effectively use XOR with IronPDF in various practical applications. Don't have IronPDF yet? Try out the free trial to see how IronPDF can take your PDF projects to the next level today!

Frequently Asked Questions

What is XOR in C#?

XOR, or the logical exclusive OR operator, is represented in C# by the `^` symbol. It is a binary operation that performs bitwise XOR operations, returning true only if exactly one of the operands is true.

How does XOR differ from the logical OR operator?

The logical OR operator returns true if one or both operands are true, whereas XOR returns true only if exactly one operand is true. XOR is exclusive, meaning both operands cannot be true simultaneously.

What are some applications of XOR in PDF processing?

XOR can be used for lightweight encryption, image visibility toggling, and metadata obfuscation in PDFs. Using IronPDF, it allows for reversible transformations of text, images, and metadata.

Can XOR be used for strong encryption?

No, XOR is not suitable for strong encryption as it provides only basic obfuscation. For secure encryption, methods like AES should be considered.

How does operator precedence affect XOR operations in C#?

In C#, XOR has lower precedence than arithmetic operators like addition but higher than bitwise complement and logical negation. This affects how expressions are evaluated.

What is a simple example of using XOR for image manipulation in PDFs?

XOR can alter image pixel values to create a scrambled effect, which can be reversed using the same XOR operation with the correct key. IronPDF can be utilized for this dynamic visibility control.

How can XOR be applied to PDF metadata?

XOR can obfuscate metadata fields such as author and title, making them unreadable without the correct decryption key. This can be done using IronPDF.

What is a key limitation of using XOR for security?

A major limitation is that XOR is not secure against determined attacks, as it can be easily reversed with knowledge of the XOR operation and key.

Is XOR suitable for large PDF files?

Applying XOR to large PDF files may impact performance, especially when manipulating images, so it is advised to apply XOR selectively to avoid performance degradation.

How can XOR be used with IronPDF?

IronPDF allows for the integration of XOR operations in PDF workflows, enabling text obfuscation, image modification, and metadata handling directly within C# applications.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of all products is growing daily, as he finds new ways to support customers. He enjoys how collaborative life is at Iron Software, with team members from across the company bringing their varied experience to contribute to effective, innovative solutions. When Chipego is away from his desk, he can often be found enjoying a good book or playing football.