Need help converting c# encryption/Decryption to php - c#

C#
public void start()
{
Constants.APIENCRYPTKEY = Convert.ToBase64String(Encoding.Default.GetBytes(Session(32)));
Constants.APIENCRYPTSALT = Convert.ToBase64String(Encoding.Default.GetBytes(Session(16)));
string results = EncryptService("start");
}
private static string Session(int length)
{
Random random = new Random();
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
return new string(Enumerable.Repeat(chars, length)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
public static string DecryptService(string value)
{
string message = value;
string password = Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTKEY));
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
byte[] iv = Encoding.ASCII.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTSALT)));
string decrypted = DecryptString(message, key, iv);
return decrypted;
}
public static string DecryptString(string cipherText, byte[] key, byte[] iv)
{
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
encryptor.Key = key;
encryptor.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesDecryptor = encryptor.CreateDecryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesDecryptor, CryptoStreamMode.Write);
string plainText = String.Empty;
try
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
cryptoStream.Write(cipherBytes, 0, cipherBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] plainBytes = memoryStream.ToArray();
plainText = Encoding.ASCII.GetString(plainBytes, 0, plainBytes.Length);
}
finally
{
memoryStream.Close();
cryptoStream.Close();
}
return plainText;
}
public static string EncryptService(string value)
{
string message = value;
string password = Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTKEY));
SHA256 mySHA256 = SHA256Managed.Create();
byte[] key = mySHA256.ComputeHash(Encoding.ASCII.GetBytes(password));
byte[] iv = Encoding.ASCII.GetBytes(Encoding.Default.GetString(Convert.FromBase64String(Constants.APIENCRYPTSALT)));
string encrypted = EncryptString(message, key, iv);
int property = Int32.Parse((OnProgramStart.AID.Substring(0, 2)));
string final = encrypted + Security.Obfuscate(property);
return final;
}
public static string EncryptString(string plainText, byte[] key, byte[] iv)
{
Aes encryptor = Aes.Create();
encryptor.Mode = CipherMode.CBC;
encryptor.Key = key;
encryptor.IV = iv;
MemoryStream memoryStream = new MemoryStream();
ICryptoTransform aesEncryptor = encryptor.CreateEncryptor();
CryptoStream cryptoStream = new CryptoStream(memoryStream, aesEncryptor, CryptoStreamMode.Write);
byte[] plainBytes = Encoding.ASCII.GetBytes(plainText);
cryptoStream.Write(plainBytes, 0, plainBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherBytes, 0, cipherBytes.Length);
return cipherText;
}
This is what I got so far in PHP
function decrypt_string($msg='', $salt='', $key='')
{
$key = utf8_encode(base64_decode($key));
$key = hash('sha256', $key);
$salt = utf8_encode(base64_decode($salt));
$salt = EncodingASCII($salt);
$method = 'aes-256-cbc';
$msg = openssl_decrypt($msg, $method, $key, OPENSSL_RAW_DATA, $salt);
return $msg;
}
The encrypt and decrypt works perfect on c#, but I can't get it to decrypt on php. Haven't attempted to make the encrypt in php yet. My c# application calls on the php script with a encrypted data and needs to be decrypted on the php side then encrypted data sent back to the c# application.

Related

Encryption and Decryption I want the method that he used to encrypt

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..

PHP Token generation to C#.Net

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

C# RijndaelManaged cryptographic storage key

my doubt is about the key to decrypt a encrypted string, without the same key used to encrypt the string i dont get the original string ok, but I need to protect this key not use her in hardcode because any hacker could decompiling a dll and see this key, if I to store this key in any archive, the hacker could copy this archive and my method and decrypt my text, how can i prevent this attack? following my code implementation, here the salt and key are static I'm trying to think in anyway to safe these datas
private static byte[] salt = new byte[255];
private static byte[] key;
internal static string EncryptString(string InputText)
{
System.Security.Cryptography.RijndaelManaged RijndaelCipher =
new System.Security.Cryptography.RijndaelManaged();
RNGCryptoServiceProvider rcs = new RNGCryptoServiceProvider();
rcs.GetBytes(salt);
key = RijndaelCipher.Key;
byte[] plainText = System.Text.Encoding.Unicode.GetBytes(InputText);
System.Security.Cryptography.PasswordDeriveBytes SecretKey =
new System.Security.Cryptography.PasswordDeriveBytes(RijndaelCipher.Key, salt);
System.Security.Cryptography.ICryptoTransform Encryptor =
RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
System.Security.Cryptography.CryptoStream cryptoStream =
new System.Security.Cryptography.CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
byte[] CipherBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string EncryptedData = Convert.ToBase64String(CipherBytes);
return EncryptedData;
}
internal static string DecryptString(string text)
{
System.Security.Cryptography.RijndaelManaged RijndaelCipher =
new System.Security.Cryptography.RijndaelManaged();
byte[] EncryptedData = Convert.FromBase64String(text);
System.Security.Cryptography.PasswordDeriveBytes SecretKey =
new System.Security.Cryptography.PasswordDeriveBytes(RijndaelCipher.Key, salt);
ICryptoTransform Decryptor =
RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(EncryptedData);
CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);
byte[] PlainText = new byte[EncryptedData.Length];
int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
memoryStream.Close();
cryptoStream.Close();
string DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
return DecryptedData;
}
#endregion
}

C# RIJNDAEL decrypt

I try to decrypt request params for JDownloader CNL Feature.
http://jdownloader.org/knowledge/wiki/glossary/cnl2
In this sample the iv and the key is '31323334353637383930393837363534' and i try to decrypt this value 'DRurBGEf2ntP7Z0WDkMP8e1ZeK7PswJGeBHCg4zEYXZSE3Qqxsbi5EF1KosgkKQ9SL8qOOUAI'
The php code in sample to encrypt is the following
I know i need to decode the key from hex to string, that means the correct key is 1234567890987654
function base16Encode($arg){
$ret="";
for($i=0;$i<strlen($arg);$i++){
$tmp=ord(substr($arg,$i,1));
$ret.=dechex($tmp);
}
return $ret;
}
$key="1234567890987654";
$transmitKey=base16Encode($key);
$link="http://rapidshare.com/files/285626259/jDownloader.dmg\r\nhttp://rapidshare.com/files/285622259/jDownloader2.dmg";
$cp = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', 'cbc', '');
#mcrypt_generic_init($cp, $key,$key);
$enc = mcrypt_generic($cp, $link);
mcrypt_generic_deinit($cp);
mcrypt_module_close($cp);
$crypted=base64_encode($enc);
echo $crypted;
My last try to decrypt is the following c# code but i have some troble with lenght of input.
public static String DecryptRJ(string input, string iv, string key )
{
key = key.DecodeBase16(); // Extension method
byte[] initVectorBytes = Encoding.UTF8.GetBytes(iv);
byte[] cipherTextBytes = Encoding.UTF8.GetBytes(input);
byte[] keyBytes = Encoding.UTF8.GetBytes(key);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
symmetricKey.BlockSize = 256;
symmetricKey.KeySize = 256;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
One more Information this PHP Code works fine and can decode and decrypt correct.
function decrypt($data, $_key){
echo '<br><hr><br>';
out($data);
$plain=base64_decode($data);
out($plain);
echo 'init';
//$e = mcrypt_decrypt ( $_cp , $_key , $plain , 'cbc' );
$e = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $_key, $plain, 'cbc', $_key);
out($e);
echo 'end';
}
Ok now i can decrypt the encrypted sample data (see php code or http://jdownloader.org/knowledge/wiki/glossary/cnl2) Code C# is this
public static string DecryptDLCData(string data, string _key, Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding.Default;
data = data.DecodeBase64(encoding);
RijndaelManaged rijndaelCipher = new RijndaelManaged();
rijndaelCipher.Mode = CipherMode.CBC;
rijndaelCipher.Padding = PaddingMode.Zeros;
rijndaelCipher.KeySize = 256;
rijndaelCipher.BlockSize = 128;
byte[] pwdBytes = Encoding.Default.GetBytes(_key);
byte[] keyBytes = new byte[16];
int len = pwdBytes.Length;
if (len > keyBytes.Length) len = keyBytes.Length;
Array.Copy(pwdBytes, keyBytes, len);
rijndaelCipher.Key = keyBytes;
rijndaelCipher.IV = keyBytes;
var transform = rijndaelCipher.CreateDecryptor();
byte[] plainText = Encoding.Default.GetBytes(data);
byte[] cipherBytes = transform.TransformFinalBlock(plainText, 0, plainText.Length);
return Encoding.UTF8.GetString(cipherBytes);
}

Java Encryption and C# Decryption Issue

I have a DLL in C# that encrypts and decrypts string texts (something basic), but now I need to implement the same encryption method in Java, so that some applications can encrypt data and send it to the library.
I can't modify the C# code, because it's already in production, but the Java don't, so please, any suggestion must be done at the Java side.
Basically I'm trying to implement the same C# encryption method in Java. Here are my C# codes:
NOTE: the passphrase, salt, etc. values obviously are just referential.
const string PassPhrase = "IhDyHz6bgQyS0Ff1/1s=";
const string SaltValue = "0A0Qvv09OXd3GsYHVrA=";
const string HashAlgorithm = "SHA1";
const int PasswordIterations = 3;
const string InitVector = "GjrlRZ6INgNckBqv";
const int KeySize = 256;
public static string Encrypt(string plainText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(InitVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);
byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
PassPhrase,
saltValueBytes,
HashAlgorithm,
PasswordIterations);
byte[] keyBytes = password.GetBytes(KeySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
encryptor,
CryptoStreamMode.Write);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
byte[] cipherTextBytes = memoryStream.ToArray();
memoryStream.Close();
cryptoStream.Close();
string cipherText = Convert.ToBase64String(cipherTextBytes);
return cipherText;
}
public static string Decrypt(string cipherText)
{
byte[] initVectorBytes = Encoding.ASCII.GetBytes(InitVector);
byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
PasswordDeriveBytes password = new PasswordDeriveBytes(
PassPhrase,
saltValueBytes,
HashAlgorithm,
PasswordIterations);
byte[] keyBytes = password.GetBytes(KeySize / 8);
RijndaelManaged symmetricKey = new RijndaelManaged();
symmetricKey.Mode = CipherMode.CBC;
ICryptoTransform decryptor = symmetricKey.CreateDecryptor(
keyBytes,
initVectorBytes);
MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
CryptoStream cryptoStream = new CryptoStream(memoryStream,
decryptor,
CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes,
0,
plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
string plainText = Encoding.UTF8.GetString(plainTextBytes,
0,
decryptedByteCount);
return plainText;
}
Here is my java code, it encrypts the data, but not at the same way as the C# encryption code, so when I try to decrypt it using the C# library it throws the exception: "Length of the data to decrypt is invalid"
static final String PassPhrase = "IhDyHz6bgQyS0Ff1/1s=";
static final String SaltValue = "0A0Qvv09OXd3GsYHVrA=";
static final String HashAlgorithm = "SHA1";
static final int PasswordIterations = 3;
static final String InitVector = "GjrlRZ6INgNckBqv";
static final int KeySize = 256;
public static String encrypt(String plainText)
{
char[] password = PassPhrase.toCharArray();
byte[] salt = SaltValue.getBytes();
byte[] iv = InitVector.getBytes();
byte[] ciphertext = new byte[0];
SecretKeyFactory factory;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, PasswordIterations, 256);
SecretKey tmp;
tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
//iv = params.getParameterSpec(IvParameterSpec.class).getIV();
ciphertext = cipher.doFinal(plainText.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//catch (InvalidParameterSpecException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
//}
catch (IllegalBlockSizeException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BadPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Base64.encode(new String(ciphertext));
}
EDIT 1: I fixed the final byte array conversion to String in the Java code, as Jon Skeet suggested.
This is what's wrong, in the Java code:
return Base64.encode(ciphertext.toString());
You're calling toString() on the byte array, which will always give a string such as [B#3e25a5.
EDIT: Ooh, just noticed that you can change the Java side. Hooray.
Basically, you need to use a Base64 API which allows:
return Base64.encode(ciphertext);
I'm always disappointed in Base64 APIs which allow you to "encode" a string, to be honest... base64 fundamentally encodes binary data to text, and decodes text data to binary. Oh well...
Anyway, use this API (the encodeBytes method) if you need one which allows you to pass in a byte array.
I haven't checked over the actual encryption part in detail, but the C# code at least looks like it's doing the right thing in terms of encodings. It could do with using statements though :)
Here is a C# example, you need the IterationCount and PaddingMode.None
protected void Page_Load(object sender, EventArgs e)
{
string value = "";
string password = "";
string salt = "";
string iv = "";
byte[] vectorBytes = Convert.FromBase64String(Server.UrlDecode(iv));
byte[] cipherText = Convert.FromBase64String(Server.UrlDecode(value));
Rfc2898DeriveBytes key1 = new Rfc2898DeriveBytes(password, StringToByteArray(salt)); //same as PBKDF2WithHmacSHA1
key1.IterationCount = 32;
byte[] keyBytes = key1.GetBytes(16);
string Answer = DecryptDataAES(cipherText, keyBytes, vectorBytes); //vectorBytes is good
//litAnswer.Text = Answer;
}
public static string DecryptDataAES(byte[] cipherText, byte[] key, byte[] iv)
{
string plaintext = null;
using (Rijndael rijndael = Rijndael.Create())
{
rijndael.Key = key;
rijndael.IV = iv;
rijndael.Padding = PaddingMode.None;
ICryptoTransform decryptor = rijndael.CreateDecryptor(rijndael.Key, rijndael.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
return plaintext;
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length / 2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
}
return bytes;
}

Categories

Resources