90 lines
3.4 KiB
C#
90 lines
3.4 KiB
C#
using System;
|
|
using System.Text;
|
|
using System.Linq;
|
|
namespace FCS
|
|
{
|
|
class Program
|
|
{
|
|
static StringBuilder encoded=new StringBuilder();
|
|
static void Main(string[] args)
|
|
{
|
|
while(true)
|
|
{
|
|
Console.Clear();
|
|
Console.WriteLine("1. Zakoduj wiadomosc");
|
|
Console.WriteLine("2. Odkoduj wiadomosc");
|
|
Console.WriteLine("3. Wyjscie");
|
|
int choice=0;
|
|
if(!int.TryParse(Console.ReadLine(),out choice))
|
|
Console.WriteLine("Nieprawidlowe dane");
|
|
else{
|
|
Console.Clear();
|
|
if(choice==1)
|
|
{
|
|
Console.WriteLine("Podaj wiadomosc do zaszyfrowania.");
|
|
string input =Console.ReadLine();
|
|
byte[] bytes = BitConverter.GetBytes(EncodeCRT(input));
|
|
Encoding.ASCII.GetBytes(input).ToList().ForEach(x=>{Console.Write(x+" ");});
|
|
foreach(byte b in bytes)
|
|
Console.Write(b+" ");
|
|
Console.WriteLine();
|
|
}
|
|
if(choice==2)
|
|
{
|
|
Console.WriteLine("Podaj wiadomosc do odkodowania.(kod ASCII odzielony spacjami wraz z checksum)");
|
|
string input=Console.ReadLine();
|
|
string[] asciiInput=input.Split(' ');
|
|
StringBuilder msg=new StringBuilder();
|
|
for(int i=0;i<asciiInput.Length-2;i++)
|
|
{
|
|
msg.Append((char)int.Parse(asciiInput[i]));
|
|
}
|
|
byte[] bytes = BitConverter.GetBytes(EncodeCRT(msg.ToString()));
|
|
bool result=true;
|
|
for(int j=0;j<bytes.Length;j++)
|
|
{
|
|
if(bytes[j]!=int.Parse(asciiInput[j + asciiInput.Length - 2].ToString()))
|
|
{
|
|
result=false;
|
|
break;
|
|
}
|
|
}
|
|
Console.WriteLine(result);
|
|
}
|
|
if(choice==3)
|
|
{
|
|
return;
|
|
}
|
|
Console.WriteLine("Nacisnij dowolny klawisz, aby wrocic do poczatku.");
|
|
Console.ReadKey();
|
|
}
|
|
|
|
}
|
|
}
|
|
private static ushort EncodeCRT(string strInput)
|
|
{
|
|
ushort data;
|
|
ushort crc = 0xFFFF; //uzupelniamy 16 bitow jedynkami
|
|
|
|
byte[] bytes = Encoding.ASCII.GetBytes(strInput);
|
|
for (int j = 0; j < bytes.Length; j++)
|
|
{
|
|
crc = (ushort)(crc ^ bytes[j]); // XOR
|
|
for (int i = 0; i < 8; i++) //obsluga bajta
|
|
{
|
|
if ((crc & 0x0001) == 1)
|
|
crc = (ushort)((crc >> 1) ^ 0x8408); //Wykonuje XOR
|
|
else
|
|
crc >>= 1;
|
|
}
|
|
}
|
|
crc = (ushort)~crc; //negujemy
|
|
data = crc;
|
|
crc = (ushort)((crc << 8) ^ (data >> 8 & 0xFF));
|
|
return crc;
|
|
}
|
|
|
|
|
|
}
|
|
}
|