ExamCryptoJanvier/crypto/CryptoPerso.cs

95 lines
2.9 KiB
C#
Raw Normal View History

2018-01-06 11:51:38 +01:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace crypto
{
class CryptoPerso
{
//Basé sur le cryptage césar
private const string alphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXTZ0123456789&@,?;.:/ ";
public string Alphabet { get { return alphabet; } set { } }
private byte[] alphabetArray = Encoding.ASCII.GetBytes(alphabet);
private byte[] textArray;
public CryptoPerso()
{
}
public byte[] StrToInt(string texte)
{
List<byte> tmp = new List<byte>();
textArray = Encoding.ASCII.GetBytes(texte);
for(int i=0; i<textArray.Length;i++)
{
byte j;
for (j = 0; textArray[i] != alphabetArray[j] && j < alphabetArray.Length; j++);
tmp.Add(j);
}
return tmp.ToArray();
}
public byte[] IntToStr(byte[] textArray)
{
List<byte> tmp = new List<byte>();
for (int i = 0; i < textArray.Length; i++)
{
tmp.Add(alphabetArray[textArray[i]]);
}
return tmp.ToArray();
}
public string Crypt(string texte, string pw)
{
try
{
byte[] texteInt = StrToInt(texte);
byte[] pwInt = StrToInt(pw);
List<byte> tmp = new List<byte>();
for (int i = 0; i < texteInt.Length; i++)
{
byte a = (byte)((texteInt[i] + pwInt[i % (pwInt.Length)]) % (alphabetArray.Length));
tmp.Add(a);
}
return Encoding.ASCII.GetString(IntToStr(tmp.ToArray()));
}
catch(Exception e)
{
warn w = new warn("ERREUR : "+e.ToString());
w.Show();
Console.WriteLine(e.ToString());
return null;
}
}
public string decryptage(string texte, string pw)
{
try
{
byte[] texteInt = StrToInt(texte);
byte[] pwInt = StrToInt(pw);
List<byte> tmp = new List<byte>();
for (int i = 0; i < texteInt.Length; i++)
{
if (texteInt[i] < pwInt[i % (pwInt.Length)])
texteInt[i] += (byte)(alphabet.Length);
byte a = (byte)((texteInt[i] - pwInt[i % (pwInt.Length)]));
tmp.Add(a);
}
return Encoding.ASCII.GetString(IntToStr(tmp.ToArray()));
}
catch (Exception e)
{
warn w = new warn("ERREUR : "+e.ToString());
w.Show();
Console.WriteLine(e.ToString());
return null;
}
}
}
}