I am converting a PHP file to C#,completed 75%,stuck with these lines
if(file_put_contents($uploaddir.$randomName, $decodedData)) {
//echo $randomName.":uploaded successfully"; //NO NEED TO CONVERT ECHO PART
}
PHP Brothers please help
MORE INFO
I converted this
// Encode it correctly
$encodedData = str_replace(' ','+',$data[1]);
$decodedData = base64_decode($encodedData);
to this
// Encode it correctly
string encodedData = data[1].Replace(' ', '+');
string decodedData = base64Decode(encodedData);
where base64Decode is
public static string base64Decode(string data)
{
byte[] binary = Convert.FromBase64String(data);
return Encoding.Default.GetString(binary);
}
Try this:
System.IO.File.WriteAllText (uploaddir + randomname, decodedData);
See the MSDN for details on the WriteAllText method.
However, your approach of converting your data to a byte array, and then converting it to a string in the base64Decode method, followed by writing it to the file is a bit too complicated IMO. You can just write your byte array to a file, decode the data like this:
public static byte[] base64Decode(string data)
{
return Convert.FromBase64String(data);
}
and then call
byte[] decodedData = base64Decode(encodedData);
System.IO.File.WriteAllBytes(uploaddir + randomname, decodedData);
WriteAllBytes documentation here.
Closest analogon is probably System.IO.File.WriteAllText
string uploaddir;
string randomName;
string decodedData;
// ....
System.IO.File.WriteAllText(
System.IO.Path.Combine(uploaddir, randomName),
decodedData
);
Related
I initilaly have a string which is converted to byteArray.
Then I convert this byteArray to HEX as shown below in my code.
Then I further need to convert this to a binary value.
string ID = "A0101185K";
byte[] ba = Encoding.Default.GetBytes(IC);
var hexString= BitConverter.ToString(ba).Replace("-", "");
You can convert byte to string in that way
static string ToBinary(byte b) => Convert.ToString(b, 2).PadLeft(8, '0');
and use it in your program like this
string MESSAGE = "A0101185K";
byte[] bytes = Encoding.Default.GetBytes(MESSAGE);
var binaries = string.Concat(bytes.Select(ToBinary));
I hope that helps you. But of course you didn't tell how you want to store your result, so maybe this is not the right answer.
I have following string as utf-8. i want convert it to persian unicode:
ابراز داشت: امام رضا برخال� دیگر ائمه با جنگ نرم
this site correctly do convert and result is: ابراز داشت: امام رضا برخالف دیگر ائمه با جنگ نرم
I test many method and ways but can't resolve this problem, for example these two lines did not produce the desired result:
string result = Encoding.GetEncoding("all type").GetString(input);
and
byte[] preambleBytes= Encoding.UTF8.GetPreamble();
byte[] inputBytes= Encoding.UTF8.GetBytes(input);
byte[] resultBytes= preambleBytes.Concat(inputBytes).ToArray();
string result=Encoding.UTF8.GetString(resultBytes.ToArray());
string resultAscii=Encoding.Ascii.GetString(inputBytes);
string resultUnicode=Encoding.Unicode.GetString(inputBytes);
You can use Encoding.Convert.
string source = // Your source
byte[] utfb = Encoding.UTF8.GetBytes(source);
byte[] resb = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("ISO-8859-6"), utfb);
string result = Encoding.GetEncoding("ISO-8859-6").GetString(resb);
NOTE: I wasn't sure which standard you wanted so for the example I used ISO-8859-6 (Arabic).
I understand what is problem by reading What is problem and Solution .
when i converted string to byte[], i forced that to convert as utf-8 format but really i should use default format for converting.
False converting:
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
resultString = Encoding.UTF8.GetString(bytes);
But
True converting:
byte[] bytes = Encoding.Default.GetBytes(inputString);
resultString = Encoding.UTF8.GetString(bytes);
Tanks for your comments and answers.
I get bytes by UTF8 and Get String by Default as follow. This worked for me.
byte[] bytes = Encoding.UTF8.GetBytes(inputString);
resultString = Encoding.Default.GetString(bytes);
I'm having a very strange issue and have no idea what can be causing it.
A customer this morning emailed me about some customers getting an error when trying to view the his website, he also got the error but then when he tried again it worked.
Looking at the logs, the error is with Chrome 65 and 67, I use 67 and do not get the error.
The querystring which is encrypted is below, this never worked for a customer but worked for me:
AQAAANCMnd8BFdERjHoAwE%2fCl%2bsBAAAA0PyFDdX%2brkGTpXZG7C49nAQAAAACAAAAAAAQZgAAAAEAACAAAACI39m3OhUEFw3GBxXP%2bsVpw6zLJOqRkcJx1%2bFPcozLZgAAAAAOgAAAAAIAACAAAAAJpDYiaxnPjDprOQEA9u02%2bU0%2fDQDCIF7sXsjxaU3onYAAAACWWCv%2bKNSRbQjLTNeJjgE37yHviV1UmfJyoUn%2fcUg%2f0MTr23%2b16qZs9F%2fDNm4wU%2bJITVn3xXuarzcNB6ClJ2ZpwtEsMdUNBRUW0B7XA9%2bQjC69V1O2XqTp%2fgXQazHOITEBpgokD1tSbnv4pRMUfkVlogYoo0H9Lnf24FEDEnSp30AAAACwtnrmVACY71%2bcAAMANRoCuihUumid0i8P75KV0ZlUIRBXyOzASHwq9I7icvXWDbI2nNOa0mQDOgNdvZEti%2bYz
Below is my code, I'm hoping the issue is with this, but as some customers are having the issue and some not, I'm not holding my breath.
var encrtptUserId = EncryptionDecryption.WindowsEncrypted(encryptQueryParameters);
string urlToValidateUser = $"{baseUrl}?id={HttpUtility.UrlEncode(encrtptUserId)}";
public static string WindowsEncrypted(string text)
{
return Convert.ToBase64String(ProtectedData.Protect(Encoding.Unicode.GetBytes(text), null, DataProtectionScope.LocalMachine));
}
public static string WindowsDecrypted(string text)
{
return Encoding.Unicode.GetString(ProtectedData.Unprotect(Convert.FromBase64String(text), null, DataProtectionScope.LocalMachine));
}
Its the decryption that is causing the issue, but not all the time
Any help would be appreciated.
The query string includes encoded values, e.g. "%2b". That's at least inconvenient.
You could decode those values to end up with the original base64 value that you could then convert back to a byte array. but it would be better to use a web-safe base64 encoding to start with.
Convert.ToBase64String doesn't provide a URL-safe approach, but you can easily just use Replace on the result:
public static string WindowsEncrypted(string text)
{
byte[] plainBinary= Encoding.Unicode.GetBytes(text);
byte[] encrypted = ProtectedData.Protect(plainBinary, null, DataProtectionScope.LocalMachine);
string base64 = Convert.ToBase64String(encrypted);
// Return a url-safe string
return base64.Replace("+", "-").Replace("/", "_").Replace("=", ".");
}
public static string WindowsDecrypted(string text)
{
string base64 = text.Replace("-", "+").Replace("_", "/").Replace(".", "=");
byte[] encrypted = Convert.FromBase64String(base64);
byte[] plainBinary = ProtectedData.Unprotect(encrypted, null, DataProtectionScope.LocalMachine);
return Encoding.Unicode.GetString(plainBinary);
}
I have some PHP code and I want to make it in c#.
My code in PHP :
$md5raw = md5($str2hash, true);
My code in c# :
static string GetMd5Hash(MD5 md5Hash, string input)
{
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
the result of this two codes is not identical
PHP:�賞�}��+X�6�
C#:0f9de8b39ee7187d92bb2b5817bb36ee
What should I change in my c# code?
If you want just the byte array, skip the conversion:
static byte[] GetMd5Hash(MD5 md5Hash, string input)
{
return md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
}
UPDATE:
You definitively should change your PHP function to return encoded data and use the same encoding in .net (C#).
What you want is to get an string with binary data, but with that you will lose information due to reencoding of the binary data during transfer.
static string GetMd5Hash(MD5 md5Hash, string input)
{
// BUG: This code probably will lose information
return Encoding.ASCII.GetString(md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input)));
}
The way you should do is to use your C# function as in your question and use this as your PHP function:
$md5raw = bin2hex(md5($str2hash, true));
I have a encryption method GetDecryptedSSN(). I tested it’s correctness by the following test. It works fine
//////////TEST 2//////////
byte[] encryptedByteWithIBMEncoding2 = DecryptionServiceHelper.GetEncryptedSSN("123456789");
string clearTextSSN2 = DecryptionServiceHelper.GetDecryptedSSN(encryptedByteWithIBMEncoding2);
But when I do a conversion to ASCII String and then back, it is not working correctly. What is the problem in the conversion logic?
//////////TEST 1//////////
//String -- > ASCII Byte --> IBM Byte -- > encryptedByteWithIBMEncoding
byte[] encryptedByteWithIBMEncoding = DecryptionServiceHelper.GetEncryptedSSN("123456789");
//encryptedByteWithIBMEncoding --> Encrypted Byte ASCII
string EncodingFormat = "IBM037";
byte[] encryptedByteWithASCIIEncoding = Encoding.Convert(Encoding.GetEncoding(EncodingFormat), Encoding.ASCII,
encryptedByteWithIBMEncoding);
//Encrypted Byte ASCII - ASCII Encoded string
string encodedEncryptedStringInASCII = System.Text.ASCIIEncoding.ASCII.GetString(encryptedByteWithASCIIEncoding);
//UpdateSSN(encodedEncryptedStringInASCII);
byte[] dataInBytesASCII = System.Text.ASCIIEncoding.ASCII.GetBytes(encodedEncryptedStringInASCII);
byte[] bytesInIBM = Encoding.Convert(Encoding.ASCII, Encoding.GetEncoding(EncodingFormat),
dataInBytesASCII);
string clearTextSSN = DecryptionServiceHelper.GetDecryptedSSN(bytesInIBM);
Helper Class
public static class DecryptionServiceHelper
{
public const string EncodingFormat = "IBM037";
public const string SSNPrefix = "0000000";
public const string Encryption = "E";
public const string Decryption = "D";
public static byte[] GetEncryptedSSN(string clearTextSSN)
{
return GetEncryptedID(SSNPrefix + clearTextSSN);
}
public static string GetDecryptedSSN(byte[] encryptedSSN)
{
return GetDecryptedID(encryptedSSN);
}
private static byte[] GetEncryptedID(string id)
{
ServiceProgram input = new ServiceProgram();
input.RequestText = Encodeto64(id);
input.RequestType = Encryption;
ProgramInterface inputRequest = new ProgramInterface();
inputRequest.Test__Request = input;
using (MY_Service operation = new MY_Service())
{
return ((operation.MY_Operation(inputRequest)).Test__Response.ResponseText);
}
}
private static string GetDecryptedID(byte[] id)
{
ServiceProgram input = new ServiceProgram();
input.RequestText = id;
input.RequestType = Decryption;
ProgramInterface request = new ProgramInterface();
request.Test__Request = input;
using (MY_Service operationD = new MY_Service())
{
ProgramInterface1 response = operationD.MY_Operation(request);
byte[] encodedBytes = Encoding.Convert(Encoding.GetEncoding(EncodingFormat), Encoding.ASCII,
response.Test__Response.ResponseText);
return System.Text.ASCIIEncoding.ASCII.GetString(encodedBytes);
}
}
private static byte[] Encodeto64(string toEncode)
{
byte[] dataInBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
Encoding encoding = Encoding.GetEncoding(EncodingFormat);
return Encoding.Convert(Encoding.ASCII, encoding, dataInBytes);
}
}
REFERENCE:
Getting incorrect decryption value using AesCryptoServiceProvider
This is the problem, I suspect:
string encodedEncryptedStringInASCII =
System.Text.ASCIIEncoding.ASCII.GetString(encryptedByteWithASCIIEncoding);
(It's not entirely clear because of all the messing around with encodings beforehand, which seems pointless to me, but...)
The result of encryption is not "text encoded in ASCII" - so you shouldn't try to treat it that way. (You haven't said what kind of encryption you're using, but it would be very odd for it to produce ASCII text.)
It's just an arbitrary byte array. In order to represent that in text only using the ASCII character set, the most common approach is to use base64. So the above code would become:
string encryptedText = Convert.ToBase64(encryptedByteWithIBMEncoding);
Then later, you'd convert it back to a byte array ready for decryption as:
encryptedByteWithIBMEncoding = Convert.FromBase64String(encryptedText);
I would strongly advise you to avoid messing around with the encodings like this if you can help it though. It's not clear why ASCII needs to get involved at all. If you really want to encode your original text as IBM037 before encryption, you should just use:
Encoding encoding = Encoding.GetEncoding("IBM037");
string unencryptedBinary = encoding.GetBytes(textInput);
Personally I'd usually use UTF-8, as an encoding which can handle any character data rather than just a limited subset, but that's up to you. I think you're making the whole thing much more complicated than it needs to be though.
A typical "encrypt a string, getting a string result" workflow is:
Convert input text to bytes using UTF-8. The result is a byte array.
Encrypt result of step 1. The result is a byte array.
Convert result of step 2 into base64. The result is a string.
To decrypt:
Convert the string from base64. The result is a byte array.
Decrypt the result of step 1. The result is a byte array.
Convert the result of step 2 back to a string using the same encoding as step 1 of the encryption process.
In DecryptionServiceHelper.GetEncryptedSSN you are encoding the text in IBM037 format BEFORE encrypting.
So the following piece of code is not correct as you are converting the encrypted bytes to ASCII assuming that its in the IBM037 format. That's wrong as the encrypted bytes is not in IBM037 format (the text was encoded before encryption)
//encryptedByteWithIBMEncoding --> Encrypted Byte ASCII
string EncodingFormat = "IBM037";
byte[] encryptedByteWithASCIIEncoding = Encoding.Convert(Encoding.GetEncoding(EncodingFormat), Encoding.ASCII,
encryptedByteWithIBMEncoding);
One possible solution is to encode the encrypted text using IBM037 format, that should fix the issue I guess.