as in the title, I need to implement in my C# code the equivalent of php's openssl_encrypt method, because I need to call a service on a php page, but we work with c#.
The php code is this:
$textToEncrypt = "test";
$algo = "AES256";
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($algo));
$key = "1234567890987654"; //Not this key, but just same length
$parametri_enc = openssl_encrypt($textToEncrypt , $algo, $key, 0, $iv);
$iv = bin2hex($iv);
I tried many thing, actually my code is:
string textToEncrypt = "test";
string secretCode = "1234567890987654"
// Create sha256 hash
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(secretCode));
// Create secret IV
byte[] iv = new byte[16];
RandomNumberGenerator generator = RandomNumberGenerator.Create();
generator.GetBytes(iv);
string encryptedText = EncryptString(textToEncrypt, key, iv);
// And I try to port also the bin2hex method
var sb = new StringBuilder();
foreach (byte b in iv)
{
sb.AppendFormat("{0:x2}", b);
}
var tokenBytesHex = sb.ToString();
And the method EncryptString is
public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
//Instantiate a new Aes object to perform string symmetric encryption
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
// Set key and IV
byte[] aesKey = new byte[32];
Array.Copy(key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = iv;
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our Aes object
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
// Return the encrypted data as a string
return cipherText;
}
I tried many variation about this porting (that I've found on internet), but without result. If I use a correct encrypted string from my code, I can call the service, so it is working. I need only to encrypt correctly that string, but until now, I've failed
Ok i solved my own problem. I'll share it so if anyone has the same problem, this could work. Basically I saw a decryption c# code here so I update my code in this way
First, I pass my secretCode in string format instead of byte[]
So i changed my method signature in this way:
public static string EncryptString(string plainText, string secretcode, byte[] iv)
and inside I changed the way I manipulate the secretCode (passphrase in php equivalent method)
// Set key and IV
var aesKey = Encoding.ASCII.GetBytes(secretcode);
//pad key out to 32 bytes (256bits) if its too short
if (aesKey.Length < 32)
{
var paddedkey = new byte[32];
Buffer.BlockCopy(aesKey, 0, paddedkey, 0, aesKey.Length);
aesKey = paddedkey;
}
So it worked! No other change, just this two small change from my previous post
Updated method
public static string EncryptString(string plainText, string secretcode, byte[] iv)
{
// Instantiate a new Aes object to perform string symmetric encryption
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
// Set key and IV
var aesKey = Encoding.ASCII.GetBytes(secretcode);
//pad key out to 32 bytes (256bits) if its too short
if (aesKey.Length < 32)
{
var paddedkey = new byte[32];
Buffer.BlockCopy(aesKey, 0, paddedkey, 0, aesKey.Length);
aesKey = paddedkey;
}
encryptor.Key = aesKey;
encryptor.IV = iv;
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our Aes object
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
// Return the encrypted data as a string
return cipherText;
}
Related
I have got a string for you guys.
Normal string = nmrufETK
Encrypted string = ultYIi4GtHhb//Cl0J8wIg==
Here is the things that I know so far, the old decyrption method was :
public static List<string> hadibuloc = new List<string>();
Functions.hadibuloc.Add("OZt4nd8ZZpAEnZBdU3Z7");
Functions.hadibuloc.Add("fkheb1PFtPIKTi05Zpzz");
Functions.hadibuloc.Add("0kx96D8OzZ3rznUk4qyi");
Functions.hadibuloc.Add("TgAji9cqMALlhJV12elB");
Functions.hadibuloc.Add("0XQ3XXjUo3HTzzevUmDm");
Functions.hadibuloc.Add("F3Ib4qRHXDgQwoJyhWra");
Functions.hadibuloc.Add("eRWoJ0s1B0uln8fFgxqX");
Functions.hadibuloc.Add("iUE0FKl2Ntawpt6sbV7u");
Functions.hadibuloc.Add("me9fMa0WTreWRrmYpBh7");
Functions.hadibuloc.Add("kyJB0qCUq269fzREzRxD");
Functions.hadibuloc.Add("WnTufxOov40st4L6qZF9");
Functions.hadibuloc.Add("7csfQq3YunqM9ziygmw8");
Functions.hadibuloc.Add("EyqWVpgOvZkyJCAmlgCh");
Functions.hadibuloc.Add("D2RAYhyatrMYrZjLdlqL");
Functions.hadibuloc.Add("nSdcM6NAAyekiwYHQqZl");
Functions.hadibuloc.Add("B3RPgAHYEpwKsFCkrLSq");
Functions.hadibuloc.Add("JgQuRU88IQC5Z77JUTiD");
Functions.hadibuloc.Add("v57wd6YIJTGhettATB8L");
Functions.hadibuloc.Add("Qzc1nrxQwuIOMrGynhXu");
Functions.hadibuloc.Add("ad5AKkogV91AfmdNwkEO");
Functions.hadibuloc.Add("vaG2jNiDHa5p18hazzyZ");
Functions.hadibuloc.Add("BbYJbJOcX4w5F84nrWYl");
Functions.hadibuloc.Add("QGMq1ffFpBV64UpWeLCP");
Functions.hadibuloc.Add("lrLJqwoJGAuwmqA12MWR");
Functions.hadibuloc.Add("VFqyK09HS3920srKbBvp");
Functions.hadibuloc.Add("wVjVwspocrBWWAnFz53M");
Functions.hadibuloc.Add("oGMgDdEBpy8vHa5RZQHa");
Functions.hadibuloc.Add("BAUsGUgYBvi7tGMJRmy6");
Functions.hadibuloc.Add("l1nEhAHzWbRlGQeOi9pz");
Functions.hadibuloc.Add("PLpbqWSUnkAoLJam79cD");
Functions.hadibuloc.Add("SWbChkYzbfB0XKKcE1wb");
Functions.hadibuloc.Add("ZRlERlOLlbbW7l4u4SLB");
Functions.hadibuloc.Add("4FaDBRIw2bRkeqLALQwq");
Functions.hadibuloc.Add("Z3Yb3QdFgAbOUMD4TT2E");
Functions.hadibuloc.Add("0QjIrotDsTJrBMVOUGEx");
Functions.hadibuloc.Add("rrBABwOTnnjoZH81Y10w");
Functions.hadibuloc.Add("Ig8OIDYp7SaHel8gQhYE");
Functions.hadibuloc.Add("Zkcq9DLCmmMb2pvgsnox");
Functions.hadibuloc.Add("Ta9QRpW1vH3vYNaWDuaT");
Functions.hadibuloc.Add("I5B3gCvXSrgfg7aKdyJ8");
Functions.hadibuloc.Add("F5U7PteCDqjtT2YYMbte");
Functions.hadibuloc.Add("NOzV5qhSRxEmEwHGrjSv");
Functions.hadibuloc.Add("9Ocg4R5TAqIQLJVY9aJA");
Functions.hadibuloc.Add("AoXect0Wd914NAKW957w");
Functions.hadibuloc.Add("ebNIGbCQ5e4vRkoKQ4SN");
Functions.hadibuloc.Add("DyQb0qmcovqZS6xA5Nbq");
Functions.hadibuloc.Add("7HjmPVonDspqmixH2FrJ");
Functions.hadibuloc.Add("EqU8wj6HBrXi5nW9l16l");
Functions.hadibuloc.Add("NI85VXOjCS0dgtylMyt1");
Functions.hadibuloc.Add("zFjG4ZJbkzrZxPwW5C1P");
Functions.hadibuloc.Add("sqkTwAiMc5iMRvam2AHs");
Functions.hadibuloc.Add("Kd2XiFoFdCheMCsD5SNk");
Functions.hadibuloc.Add("2PcWLkcAiLOo4AcM1n6f");
Functions.hadibuloc.Add("fZKaPRgxgb6EGc9A4epo");
Functions.hadibuloc.Add("pJCNj8hiQYd0mSwAAlG9");
Functions.hadibuloc.Add("FHLEOcgR8nZkPETgIau7");
Functions.hadibuloc.Add("fP0IIV133SBrSAhcm2xL");
Functions.hadibuloc.Add("J7dYgJsix1trFydJBCiD");
Functions.hadibuloc.Add("kuy5ZNe3SKh6NNwKsusq");
Functions.hadibuloc.Add("yw35qZxwIPY4vAndktx3");
Functions.hadibuloc.Add("lFIn4TrpaXAL6TUXTfRa");
Functions.hadibuloc.Add("2ajBkzl7mSl08rm0m9qq");
Functions.hadibuloc.Add("rQiGJrCD2qOw2cbTrHdX");
Functions.hadibuloc.Add("08Gm5pOBmKQPIpWw7NIu");
Functions.hadibuloc.Add("WRjgeZMotIAmyiGalpt3");
Functions.hadibuloc.Add("rYy1MGiBLxfMBufX9IJn");
Functions.hadibuloc.Add("LIv4dk2eh1DbWmuP2Xao");
Functions.hadibuloc.Add("xeNNc12ef0pmgBs3rYpV");
Functions.hadibuloc.Add("6IcTB4F0MYf3XEvPZ3Pp");
Functions.hadibuloc.Add("4FEEfd1l5qNsoX7VPkiS");
Functions.hadibuloc.Add("0kGF2Rb8HKT4Spn41RW1");
Functions.hadibuloc.Add("HDEsDvrgokF0b5jgXJ3J");
Functions.hadibuloc.Add("iU1NeT7jYaN7HB8eNn9V");
Functions.hadibuloc.Add("NT4HJ9M77hkWK3TqaFRR");
Functions.hadibuloc.Add("GEFxqMf38desyg3wO1K4");
Functions.hadibuloc.Add("Zgwk37JrBl9o3JMeQtZA");
Functions.hadibuloc.Add("64YkqXguAr8AmWTNKQj3");
Functions.hadibuloc.Add("tGWLK6h9TPrSFSA4ZocS");
Functions.hadibuloc.Add("9yHnDOfweXcCXOp1chBx");
Functions.hadibuloc.Add("LTuAf0bPkFYrQ5TbMD6U");
Functions.hadibuloc.Add("M4k0pUF7P04bLHs6dJV1");
Functions.hadibuloc.Add("x5X0gVtjCe8GDrfOFsaX");
Functions.hadibuloc.Add("BrFjmwvJMKjmLg5mYWRQ");
Functions.hadibuloc.Add("4iAcBuNr58pP2gux67ud");
Functions.hadibuloc.Add("jLuuVi2la7KfxRNNecG5");
Functions.hadibuloc.Add("3QssdnIkbDrMcQWQ2lsb");
Functions.hadibuloc.Add("7wvkS2KuPwCOApEMJW2s");
Functions.hadibuloc.Add("1ZxJdP8JxP4PR1t4yE9D");
Functions.hadibuloc.Add("aFL5rH066RA3eLF6BSrm");
Functions.hadibuloc.Add("pAvKpwz4fc4lmtsbNjHO");
Functions.hadibuloc.Add("ukOhB5O7NxLMgyC0q1rb");
Functions.hadibuloc.Add("69qB4rzAA4BsCYfY3c74");
Functions.hadibuloc.Add("fKYNy6gkdPDyk0pTkkN2");
Functions.hadibuloc.Add("l0SPSH2CeMdpPAa6tVP8");
Functions.hadibuloc.Add("NQkNZKgSFEq8sDHUCLAf");
Functions.hadibuloc.Add("yzM5F818BdeRcC8pHNjB");
Functions.hadibuloc.Add("tj8hZFSq4blLgTdPMlv1");
Functions.hadibuloc.Add("wXP72vnkO9eLMslKSphJ");
Functions.hadibuloc.Add("hdtln0yAp9O2StGrXkZL");
Functions.hadibuloc.Add("Ujvws8KLRf7fyz1oo9Fm");
public static string Uzaksunucudangelenmetnicoz(string metin)
{
string result = "";
try
{
List<string> list = new List<string>();
list.Add("6MRVk2iHrsSWxY739uU6");
list.Add("JNEbV73AIVv01UI4cCN9");
list.Add("fRUzPptifIk7mYhAGuwq");
list.Add("4okJUC1Nv8hT2RjIOlDH");
list.Add("jWJjtopKxt27xbPUmigk");
list.Add("cQiqthahKNnbJXUsXNai");
list.Add("LrGUCKUxIKsbHEoGNoZB");
list.Add("j3UVDV6B5P3ZTewgLs1J");
list.Add("a864WixaWMit6RdbnowV");
list.Add("bLfWxqaXSEsa9uNoDY1z");
list.Add("aTwGuGAL1aDEYLqZdydm");
list.Add("fipquWXp6Fde1l1yoePJ");
list.Add("xEFesiTXtE8GNiJoPURP");
list.Add("z1rleac3uxRnrwrlZ47P");
list.Add("HnauZy36NMCbnKQpBvXy");
list.Add("LsenKihueSeUm5D3vyGm");
list.Add("fBAvk2yApQGD90wPmTuz");
list.Add("kL61T5rai5sq1fPDPQIG");
list.Add("u4lTisX4LxhTouLGiVqv");
list.Add("dhgB32wDm0PgUccGC7vi");
list.Add("pDMQv1GbeU2h3aOP2aFf");
list.Add("Z9tMsKaXoC9569dQWLoH");
list.Add("wwl9YoScNaklEk6lYBRk");
list.Add("61oIv3D0asY8qHcsMvvn");
list.Add("AcUgy8GNAKmUmsi1wJZ2");
list.Add("cxAIFZaLeEYooksNACUm");
list.Add("hXtoz3WI4WWcD15U1HVj");
list.Add("1xU1M828PODASWox3CWc");
list.Add("XGJ6H04SndlopxeuJR2X");
list.Add("7XsDr8tAklPAUhRwgS31");
list.Add("SyUH2DS12ObKTXYzapMm");
list.Add("eyRb3S2EOIfnfHJZImOr");
list.Add("x47P7emhboAYBbSGN9BP");
list.Add("u2hp1Lnq0dJWqh5CXwFx");
list.Add("2DwFQJGsQdd46liK6YfI");
list.Add("qzlgXi9wFVsevBVljM7P");
list.Add("7iaN5LVfWpes5IZtvNJs");
list.Add("BjTUTmlDb9Haj3iiL4H8");
list.Add("E0vZK3rAmSD5TJQYqo06");
list.Add("cV0nXoWnC2qfAF6ijKti");
list.Add("ZnXX4xjkWxyhVzAE5f4T");
list.Add("uiBq4ynA6zVpvYcLG3Rr");
list.Add("iQddCas3XU4Wg1kJd0VG");
list.Add("TbLVNp3vf1d3uVYpNA9V");
list.Add("S9VKQiW7fMONpIZLoiZp");
list.Add("782urFNgLyB4NsVMF5PL");
list.Add("d0FetEyv8Kcpb4xsq4WL");
list.Add("vDxNe5VujuZxfmVWFzDO");
list.Add("eqSfybAFoNRwaWjTwGKl");
list.Add("pme5Rz3bm3afIJUNvGao");
list.Add("5GYm7wSxmD2XTfa1fMW2");
list.Add("G4pMJhDsO95pIAL8cPmS");
list.Add("htdFa3r1vnR3YfHoj518");
list.Add("AVwD2PBtkLy2IC6WPG3x");
list.Add("PCbXpVgmU0psYRcRLhDj");
list.Add("aoHChiGFaFSa4fy5lVcY");
list.Add("nDGKEbbKdNn1qF7YziCT");
list.Add("g9Caz2rzK3BrZM9Yywnk");
list.Add("9MDd0QU1Wasw7PARMzfC");
list.Add("BDTGEK8nSErokxtpx5qI");
list.Add("kAoxMqmbts92s2SvjXCQ");
list.Add("tI2AMshUkr7NvwjWWMWK");
list.Add("wjwPea52QEF5XteTWTBR");
list.Add("6QcQXhY6YhfaBOof38X9");
list.Add("T3ztIItPddcqCa6l4W9q");
list.Add("fk61VH7gogvZqScilAjc");
list.Add("rNiGeeaesugz1EuIhlkA");
list.Add("MUo3726lbUu1noFFdNQL");
list.Add("hXh5Ojy9M2mhscBQIFsU");
list.Add("UOC2A4ql6K0FnExnuy5N");
list.Add("jgQBAXfvMZ4anhRJkrhw");
list.Add("BCaFEzbVQZDSDePt2aOK");
list.Add("WwK7FAI1M3P6iLHChuDe");
list.Add("UyQTMeFsYPFWPmwSsyAn");
list.Add("LCJI9dPxYZUIpbVOLRXa");
list.Add("AljvoFtljUvbetI2uAm8");
list.Add("J9dS4PNwjQY95ZJrWgZK");
list.Add("LNXcRGdEUfZoaFUxYvnz");
list.Add("9TGNyTWYec9O5j77yKH2");
list.Add("0VfAzTM1kSPW1AEPgUgy");
list.Add("oPPBTadoRQuryClE6Set");
list.Add("LK5Taw6rC5LIqD8XlMuw");
list.Add("zydeLNO5dDco6rcniPQo");
list.Add("qorqKozLU6AEK00sij17");
list.Add("em5FrXNJf7dlUrPmMZAb");
list.Add("XGhnM6PUAbF6rqnumKN6");
list.Add("xobFyWikgplryg4zJ71Y");
list.Add("r7xh75Hg3Q1tjzx01zlb");
list.Add("3cUXFakPJAzY8TlO1g6t");
list.Add("ZaM8ELOP57j8wvagTkgj");
list.Add("YZtR13683gxaYnfHt2m2");
list.Add("uXjIph0fYIQUApaDhswh");
list.Add("yDewQ1dWb39AKRszMl2x");
list.Add("8wf1DTnyLhDICzoppHex");
list.Add("ubO0rGOZpD4WMN1zZYMS");
list.Add("iXS26dUzA4NFOAwHgHyg");
list.Add("XOHZ5TOPuMF8YqqWRXb8");
list.Add("oJzOJ5zoZKA6wnHJcJNZ");
list.Add("rzWXMzAgaWwZ2POulBbU");
list.Add("g7LoA9c7fNTnBbTWPBPu");
list.Add("uVCH6x1GfXEkB561Lx61");
list.Add("BJruYhyvqBtXTvZk93ua");
list.Add("uCkfQp4gFBOzlZTM59kn");
list.Add("yZD9B59o92Eqmbe3mJG5");
list.Add("vgdoztnujq9BTPoiQaQP");
list.Add("jfyJazaJJ3HgyUCmbVhN");
list.Add("MoZTMDMVMg3pFE94Q0Hp");
list.Add("sSHRIeqtDRWRIl3hqA50");
list.Add("4Bz3N3tfDwkyckMoJjVO");
list.Add("hBS3Dk5CN2VpWRmtbaxa");
SHA256 sha = SHA256.Create();
byte[] key = sha.ComputeHash(Encoding.ASCII.GetBytes(list[6].Substring(6)));
byte[] iv = new byte[16];
sha.Dispose();
result = Functions.DecryptString(metin, key, iv);
}
catch
{
result = "undefined";
}
return result;
}
public static string DecryptString(string cipherText, byte[] key, byte[] iv)
{
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
byte[] array = new byte[32];
Array.Copy(key, 0, array, 0, 32);
aes.Key = array;
aes.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform transform = aes.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
string result = string.Empty;
try
{
byte[] array2 = Convert.FromBase64String(cipherText);
cryptoStream.Write(array2, 0, array2.Length);
cryptoStream.FlushFinalBlock();
byte[] array3 = memoryStream.ToArray();
result = Encoding.ASCII.GetString(array3, 0, array3.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return result;
}
And this was the old encrytion method :
public static string AES256Hash(string plaintext)
{
SHA256 sha = SHA256.Create();
byte[] key = sha.ComputeHash(Encoding.ASCII.GetBytes(Functions.hadibuloc[87].Substring(8)));
byte[] iv = new byte[16];
sha.Dispose();
return Functions.EncryptString(plaintext, key, iv);
}
public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
Aes aes = Aes.Create();
aes.Mode = CipherMode.CBC;
byte[] array = new byte[32];
Array.Copy(key, 0, array, 0, 32);
aes.Key = array;
aes.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform transform = aes.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write);
byte[] bytes = Encoding.ASCII.GetBytes(plainText);
cryptoStream.Write(bytes, 0, bytes.Length);
cryptoStream.FlushFinalBlock();
byte[] array2 = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
return Convert.ToBase64String(array2, 0, array2.Length);
}
But as I said these were old codes that used. And I think he used a method that similar to these. I want the method that he used to encrypt. My english is not good if theres and spelling or grammer mistake sorry for that if you didnt understand my question you feel free to ask again.
It will be impossible to determine an encryption algorithm without source code or some amount of reverse engineering. The old encryption uses AES256 in CBC mode, but that is obvious.
If you don't have access to the new code, then you probably shouldn't be attempting this anyways..
I am tried to convert the php basic two way encryption code to C# code.the php code can be check with this site -> https://www.the-art-of-web.com/php/two-way-encryption/. I am not sure with the IV generate in my c# code is correct or not .The token which i have get from C# and PHP are in same format but the C# token shows invalid.please check my C# code that I need to change any thing.
PHP CODE:
<?php
$encrypted ="";
function encryptToken($token)
{
$cipher_method = 'aes-128-ctr';
$enc_key = openssl_digest('**********************', 'SHA256', TRUE);
$enc_iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher_method));
$crypted_token = openssl_encrypt($token, $cipher_method, $enc_key, 0, $enc_iv) . "::" .
bin2hex($enc_iv);
unset($token, $cipher_method, $enc_key, $enc_iv);
return $crypted_token;
}
function createAccessToken(){
$now = date("YmdHis");
$secret = '###################';
$plainText = $now."::".$secret;
$encrypted = encryptToken($plainText);
return $encrypted;
}
$encrypted = createAccessToken();
?>
C# CODE
public string GenerateToken()
{
var Date = DateTime.Now.ToString("yyyyMMddHHmmss");
var secret = "#############################";
string plainText = Date + "::" + secret;
var accessToken = EncryptString(plainText);
return accessToken;
}
public string EncryptString(string plainText)
{
try
{
string password = "************************";
// Create sha256 hash
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
// Instantiate a new Aes object to perform string symmetric encryption
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.ECB;
encryptor.Padding = PaddingMode.None;
encryptor.BlockSize = 128;
// Create secret IV
var iv = generateIV();
// Set key and IV
byte[] aesKey = new byte[32];
Array.Copy(key, 0, aesKey, 0, 32);
encryptor.Key = aesKey;
encryptor.IV = iv;
// Instantiate a new MemoryStream object to contain the encrypted bytes
MemoryStream memoryStream = new MemoryStream();
// Instantiate a new encryptor from our Aes object
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
// Instantiate a new CryptoStream object to process the data and write it to the
// memory stream
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
// Convert the plainText string into a byte array
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
// Encrypt the input plaintext string
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
// Complete the encryption process
cryptoStream.FlushFinalBlock();
// Convert the encrypted data from a MemoryStream to a byte array
byte[] cipherBytes = memoryStream.ToArray();
// Close both the MemoryStream and the CryptoStream
memoryStream.Close();
cryptoStream.Close();
// Convert the encrypted byte array to a base64 encoded string
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length) + "::" + ByteArrayToString(iv);
// Return the encrypted data as a string
return cipherText;
}
catch (Exception)
{
throw;
}
}
private static byte[] generateIV()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] nonce = new byte[IV_LENGTH];
rng.GetBytes(nonce);
return nonce;
}
}
Received Tokens
PHP Token
s9kMVUTBLvvjDJNean2kYyEHisYsEQHLQ54+7wV1zHdV1jRsSBFc6PNU0lyZ48VoCjckpm94xEgxKpTRCCXEX8CS/7PYbxZqNBFIZBtZZ3mXnkfA4rvkVEc6XuNXqLGdU3dFxbtWhikAMkHiiUPnPP5hR9UCyj2mAzJqHAwQ1Cn5VkyYWwJEHeyzQR4cwBVr::2e7d77b69ab1185e3d44af142aa6f358
C# token
qFSf2qQ+UHcqAoGUxj43wTO9fLhxfhwf+hYiRKq12amdcICJ6swXvSlV4P1/VYQm6ezNqF+x6LkjMfsxgG1Oyo71+T+mtSs0j5Bmu7eaZr5bDgAMMnZ8WrDKde2fGOgB81Gkj67L/Ka+dT+Ki0j/zsXMN454vqCzdUl0pw91TpwB8UHYni7sMA8JyLgto3Q4::418c68da838e2be51b0e84def5266024
I have been trying to implement proper IV practice in methods to encrypt and decrypt a UTF-8 string with AES which is then returned as a Base64 string. Using this question as a reference, I have prepended the generated IV to the byte array before the Base64 conversion. I'm having an issue where the decrypt method returns the UTF-8 string with exactly fifty characters of random junk (encryption artifacts?). I don't believe the issue is with the encryption because the decrypt method does consistently return the encrypted string. I think the problem is with one of the other conversion steps but I'm having trouble seeing where this might be coming from. Any help would be wildly appreciated.
Encrypt method
public static string EncryptString(string input, string key)
{
using (var aes = new AesCryptoServiceProvider())
{
aes.Key = System.Convert.FromBase64String(key);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
byte[] rawData = Encoding.UTF8.GetBytes(input);
// IV is the 16 byte AES Initialization Vector
aes.GenerateIV();
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
{
using (var ms = new MemoryStream())
{
ms.Write(aes.IV, 0, aes.IV.Length); // aes.IV.Length should be 16
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
cs.Write(rawData, 0, rawData.Length);
cs.FlushFinalBlock();
}
byte[] encryptedData = ms.ToArray();
// this will hold the IV prepended to the encrypted data
byte[] output = new byte[aes.IV.Length + encryptedData.Length];
Array.Copy(aes.IV, output, aes.IV.Length); // save the iv
Array.Copy(encryptedData, 0, output, aes.IV.Length, encryptedData.Length); // save the data
// now encode the whole thing as base 64
return System.Convert.ToBase64String(output);
}
}
}
}
Decrypt method
public static string DecryptString(string input, string key)
{
using (var aes = new AesCryptoServiceProvider())
{
aes.Key = Convert.FromBase64String(key);
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
byte[] rawData = Convert.FromBase64String(input);
byte[] IV = new byte[16]; // aes.IV.Length should be 16
Array.Copy(rawData, IV, IV.Length);
using (var ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, aes.CreateDecryptor(aes.Key, IV), CryptoStreamMode.Write))
{
using (var binaryWriter = new BinaryWriter(cs))
{
binaryWriter.Write(rawData,IV.Length ,rawData.Length - IV.Length);
}
}
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
My test
static void Main(string[] args)
{
string payload = "My super secret string";
string key = "tR4mPn7mBQ8G6HWusyFnGk/gqdd/enWiUTr7YbhNrJg=";
Console.WriteLine(payload);
Console.WriteLine(key);
Console.WriteLine("");
string encrypted = EncryptString(payload, key);
Console.WriteLine(encrypted);
Console.WriteLine("");
string decrypted = DecryptString(encrypted, key);
Console.WriteLine(decrypted);
Console.WriteLine(decrypted.Length.ToString() + " " + encrypted.Length.ToString());
Console.ReadKey();
}
Edit to add - this is an example of the output:
�XQ��=F�]�D�?�My super secret string
You are writing the IV to the output twice in EncryptString. First you have:
ms.Write(aes.IV, 0, aes.IV.Length); // aes.IV.Length should be 16
which is the start of encryptedData. You then copy the IV and encryptedData (which already includes the IV) into a new byte array:
// this will hold the IV prepended to the encrypted data
byte[] output = new byte[aes.IV.Length + encryptedData.Length];
Array.Copy(aes.IV, output, aes.IV.Length); // save the iv
Array.Copy(encryptedData, 0, output, aes.IV.Length, encryptedData.Length); // save the data
This doubling of the IV is what is causing the extra bytes.
You don’t need to do the second copying. Just convert encryptedData to base 64 directly and return that:
return System.Convert.ToBase64String(encryptedData);
I'm using Rijndael Algorithm to encrypt strings (user passwords), but when I decrypt them, it returns me "System.SecureString", and not my decrypted password.
I'm using this basic code:
public static string DecryptString(string cipherText, string password)
{
byte[] key, iv;
Rfc2898DeriveBytes rfcDb = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(password));
key = rfcDb.GetBytes(16);
iv = rfcDb.GetBytes(16);
byte[] cipheredData = Convert.FromBase64String(cipherText);
RijndaelManaged rijndael = new RijndaelManaged();
rijndael.Mode = CipherMode.CBC;
ICryptoTransform decryptor = rijndael.CreateDecryptor(key, iv);
MemoryStream ms = new MemoryStream(cipheredData);
CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
byte[] plainTextData = new byte[cipheredData.Length];
int decryptedByteCount = cs.Read(plainTextData, 0, plainTextData.Length);
ms.Close();
cs.Close();
return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount);
}
The real problem is that it's sending me back "System.SecureString", and I can't do anything.
I think it comes from the conversion at the end but I really don't know how to change that (it seems good btw)
return Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount);
So if you have an idea or a working code sample, I'm interested.
Have a nice day
I have implemented rijndael in the past, and here is my version if this is any help:
private static string Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
// Convert strings into byte arrays.
// Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
var initVectorBytes = Encoding.ASCII.GetBytes(initVector);
var saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our plaintext into a byte array.
// Let us assume that plaintext contains UTF8-encoded characters.
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
// First, we must create a password, from which the key will be derived.
// This password will be generated from the specified passphrase and
// salt value. The password will be created using the specified hash
// algorithm. Password creation can be done in several iterations.
var password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
var keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC };
// Generate encryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
var encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
var memoryStream = new MemoryStream();
// Define cryptographic stream (always use Write mode for encryption).
var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
// Start encrypting.
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
// Finish encrypting.
cryptoStream.FlushFinalBlock();
// Convert our encrypted data from a memory stream into a byte array.
var cipherTextBytes = memoryStream.ToArray();
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert encrypted data into a base64-encoded string.
var cipherText = Convert.ToBase64String(cipherTextBytes);
// Return encrypted string.
return cipherText;
}
private static string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
// Convert strings defining encryption key characteristics into byte
// arrays. Let us assume that strings only contain ASCII codes.
// If strings include Unicode characters, use Unicode, UTF7, or UTF8
// encoding.
var initVectorBytes = Encoding.ASCII.GetBytes(initVector);
var saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
// Convert our ciphertext into a byte array.
var cipherTextBytes = Convert.FromBase64String(cipherText);
// First, we must create a password, from which the key will be
// derived. This password will be generated from the specified
// passphrase and salt value. The password will be created using
// the specified hash algorithm. Password creation can be done in
// several iterations.
var password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
// Use the password to generate pseudo-random bytes for the encryption
// key. Specify the size of the key in bytes (instead of bits).
var keyBytes = password.GetBytes(keySize / 8);
// Create uninitialized Rijndael encryption object.
// It is reasonable to set encryption mode to Cipher Block Chaining
// (CBC). Use default options for other symmetric key parameters.
var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC };
// Generate decryptor from the existing key bytes and initialization
// vector. Key size will be defined based on the number of the key
// bytes.
var decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
// Define memory stream which will be used to hold encrypted data.
var memoryStream = new MemoryStream(cipherTextBytes);
// Define cryptographic stream (always use Read mode for encryption).
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
// Since at this point we don't know what the size of decrypted data
// will be, allocate the buffer long enough to hold ciphertext;
// plaintext is never longer than ciphertext.
var plainTextBytes = new byte[cipherTextBytes.Length];
// Start decrypting.
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
// Close both streams.
memoryStream.Close();
cryptoStream.Close();
// Convert decrypted data into a string.
// Let us assume that the original plaintext string was UTF8-encoded.
var plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
// Return decrypted string.
return plainText;
}
public static string EncryptData(string encryptText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
return Encrypt(encryptText, passPhrase, saltValue, hashAlgorithm, passwordIterations, initVector, keySize);
}
public static string DecryptData(string decryptText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize)
{
return Decrypt(decryptText, passPhrase, saltValue, hashAlgorithm, passwordIterations, initVector, keySize);
}
I then had some public methods that call into the above methods...
public static string EncryptData(string encryptText)
{
return EncryptionHelper.EncryptData(encryptText, ConfigHelper.PassPhrase, ConfigHelper.SaltValue, ConfigHelper.HashAlgorithm, ConfigHelper.PasswordIterations, ConfigHelper.InitVector, ConfigHelper.KeySize);
}
public static string DecryptData(string decryptText)
{
return EncryptionHelper.DecryptData(decryptText, ConfigHelper.PassPhrase, ConfigHelper.SaltValue, ConfigHelper.HashAlgorithm, ConfigHelper.PasswordIterations, ConfigHelper.InitVector, ConfigHelper.KeySize);
}
I then had these in a config file...
<add key="passPhrase" value=""/>
<add key="saltValue" value=""/>
<add key="hashAlgorithm" value="SHA1"/>
<add key="passwordIterations" value="5"/>
<add key="initVector" value=""/>
<add key="keySize" value="256"/>
I tried to encrypt data using this function in PHP and decrypt it with the other function in C#. But I don't get the same string.
//php function
public function onCrypt($text)
{
$key=md5('DFDFDFDFDFDFDFDFDFDFDFDF',true);
$crypttext = urldecode(trim(mcrypt_encrypt(MCRYPT_RIJNDAEL_128,$key, $text, MCRYPT_MODE_ECB, mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB), MCRYPT_RAND))));
$text_crp =base64_encode($crypttext);
return $text_crp;
}
//c# function
//public static void DecryptFile
Parameters :
strKey : the key choosed in decryption .
PathPlainTextFile : path of the crypted file
PathPlainTextFile : the original file decrypted.
public static void DecryptFile(string strKey, string pathPlainTextFile, string pathCypheredTextFile)
{
//crypt key with md5 function
System.Security.Cryptography.MD5 alg = System.Security.Cryptography.MD5.Create();
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] md5val = alg.ComputeHash(enc.GetBytes(strKey));
StreamReader fsPlainTextFile = File.OpenText(pathPlainTextFile);
FileInfo t = new FileInfo(pathCypheredTextFile);
StreamWriter Tex =t.CreateText();
string input = null;
while ((input = fsPlainTextFile.ReadLine()) != null)
{
byte[] cipheredData = Convert.FromBase64String(input);
RijndaelManaged rijndaeld = new RijndaelManaged();
// define the used mode
rijndaeld.Mode = CipherMode.ECB;
// create the cipher AES - Rijndael
ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val,null);
// Write the ciphered data in MemoryStream
MemoryStream ms= new MemoryStream(cipheredData);
CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
// Insert the ciphered data in a byte array
byte[] plainTextData = new byte[cipheredData.Length];
int decryptedByteCount = cs.Read(plainTextData, 0, plainTextData.Length);
ms.Close();
cs.Close();
// Insert the ciphered data in string encoded on Base64
Tex.WriteLine (Encoding.UTF8.GetString(plainTextData, 0, decryptedByteCount));
}
Tex.Close();
}
ECB mode is not secure. You should use either CTR mode or CBC mode. It is also best to explicitly specify the padding you are going to use at both ends.
At a quick glance, you're not supplying an IV to the C# decryptor:
ICryptoTransform decryptor = rijndaeld.CreateDecryptor(md5val, null);
I'm not familiar with php, but it looks like you created an IV when you encrypted the content. You'll need to have that same IV to decrypt it in the C# code (you'd need the same IV to decrypt it even if you were doing the decryption through php).