1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
| static void Main(string[] args)
{
string secret = "mon code secret";
string crypte = Crypter("ma phrase à encoder", secret);
Console.WriteLine(Decrypter(crypte, secret));
}
public static string Decrypter(string encryptedString, string keyPhrase)
{
byte[] Key = new byte[24];
byte[] IV = new byte[16];
GenerateKey(keyPhrase, ref Key, ref IV);
byte[] encrypted = Convert.FromBase64String(encryptedString);
UnicodeEncoding textConverter = new UnicodeEncoding(); // ou ASCIIEncoding si besoin
RijndaelManaged myRijndael = new RijndaelManaged { Key = Key, IV = IV };
ICryptoTransform decryptor = myRijndael.CreateDecryptor(Key, IV);
MemoryStream msDecrypt = new MemoryStream(encrypted);
CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);
byte[] fromEncrypt = new byte[encrypted.Length];
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
return textConverter.GetString(fromEncrypt);
}
public static string Crypter(string original, string keyPhrase)
{
byte[] Key = new byte[24];
byte[] IV = new byte[16];
GenerateKey(keyPhrase, ref Key, ref IV);
UnicodeEncoding textConverter = new UnicodeEncoding(); // ou ASCIIEncoding si besoin
RijndaelManaged myRijndael = new RijndaelManaged { Key = Key, IV = IV };
ICryptoTransform encryptor = myRijndael.CreateEncryptor(Key, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
byte[] toEncrypt = textConverter.GetBytes(original);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
byte[] encrypted = msEncrypt.ToArray();
return Convert.ToBase64String(encrypted);
}
public static void GenerateKey(string SecretPhrase, ref byte[] Key, ref byte[] IV)
{
byte[] bytePhrase = Encoding.ASCII.GetBytes(SecretPhrase);
SHA384Managed sha384 = new SHA384Managed();
sha384.ComputeHash(bytePhrase);
byte[] result = sha384.Hash;
for (int loop = 0; loop < 24; loop++)
Key[loop] = result[loop];
for (int loop = 24; loop < 40; loop++)
IV[loop - 24] = result[loop];
} |
Partager