Guest User

Guest User

  • Tech Writer
  • 2.1k
  • 480.6k

How to encrypt letters in c# console?

Feb 26 2024 10:00 AM

Hi Team

I have a console app, but the issue is i dont get all the expected letters when decrypt them meaning, instead of getting all expected letters when a user types their username, it print one letter that is wrong. Let me share this logic below;

 

using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter the encrypted username: ");
        string encryptedUsername = Console.ReadLine();
        string decryptedUsername = Decrypt(encryptedUsername);
        Console.WriteLine("Decrypted username: " + decryptedUsername);
    }

    static string Decrypt(string encryptedText)
    {
        Dictionary<char, char> decryptionMap = GenerateDecryptionMap("CuanChicken@2024", "wgqpwijwlalgbxbd");
        string decryptedText = "";

        foreach (char encryptedChar in encryptedText)
        {
            if (decryptionMap.ContainsKey(encryptedChar))
            {
                decryptedText += decryptionMap[encryptedChar];
            }
            else
            {
                // Keep non-alphabetic characters as they are
                decryptedText += encryptedChar;
            }
        }

        return decryptedText;
    }

    static Dictionary<char, char> GenerateDecryptionMap(string encryptedChars, string decryptedChars)
    {
        Dictionary<char, char> map = new Dictionary<char, char>();

        for (int i = 0; i < encryptedChars.Length; i++)
        {
            char encryptedChar = encryptedChars[i];
            char decryptedChar = decryptedChars[i];

            // Correcting the mapping for 'l' to 'p'
            if (encryptedChar == 'l')
            {
                decryptedChar = 'p';
            }

            map[encryptedChar] = decryptedChar;
        }

        return map;
    }

}

 


Answers (1)