How to use XOR Encryption (XOR Cipher) to encrypt and decrypt text in C#

1 Answer

0 votes
using System;

class Program
{
     public static string XORCipher(string str, string key) {
	    int strlen = str.Length;
	    int keyLen = key.Length;
	    char[] output = new char[strlen];

	    for (int i = 0; i < strlen; i++) {
		    output[i] = (char)(str[i] ^ key[i % keyLen]);
	    }

	    return new string(output);
    }
    
    static void Main() {
        string str = "C# Programming Language";
        string key = "secretkey";
        
        string cipherText = XORCipher(str, key);
        Console.WriteLine(cipherText);
        
        string decryptText = XORCipher(cipherText, key);
        Console.WriteLine(decryptText);
    }
}




/*
run:

0FC"
T'
C# Programming Language

*/

 



answered Jan 19, 2023 by avibootz
...