I have a string that i would like to encode in base64. I would also like the final encoding to be saved in a string.
In iOS would be :
- (NSString *)encodeCredentials
{
//string to be encoded
NSString *deviceUUID = "34543647yrgsav635Chbvcew4f56v"
NSData *plainTextData = [deviceUUID dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
//i return the encoded string
return base64String;
}
How would that be in wp7 ?
For encoding:
public string Encode(string str)
{
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(str));
}
For decoding:
public string Decode(string str)
{
return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(str));
}
I find this method on the net, hope it can help :
static public string EncodeTo64(string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
In wp7 you will probably be forced to replace ASCIIEncoding by UTF8Encoding or Encoding I do not remember well but Intellisense does, it's in System.Text anyway.
Here is the doc for System.Convert.ToBase64String : http://msdn.microsoft.com/en-us/library/dhx0d524.aspx
Related
I'm working on receipt application on c#. I have receipt example with english and arabic words as in below.
I have json text and i try convert that json text to hex and sent as hex format via socket message.
My problem is i try to convert text to Hex i cannot convert successfully. Here is how i convert text to Hex
string hexOutput = "";
byte[] ba = Encoding.Default.GetBytes(output);
hexOutput = BitConverter.ToString(ba);
hexOutput = hexOutput.Replace("-", "");
Here my json example
"PaymentReceipt":[
{
"DocumentQualifier":"CustomerReceipt",
"OutputContent":{
"OutputFormat":"Text",
"OutputText":[
{
"Text":"------------------------------------------------------------"
},
{
"Text":"XXXXXXXXXX2345"
},
{
"Text":"Purchase Amount مبلغ الشراء"
},
{
"Text":"5.00"
},
{
"Text":""
},
{
"Text":"Thanks for your visit شكرا لزيارتكم"
}
]
What can i do for correctly convert text to HEX?
UTF-8 is the most widely used encoding on the web. Check Usage of character encodings broken down by ranking
Code
HexManager static class contains helper extension methods to convert from/to hex.
using System;
using System.Text;
public static class HexManager
{
public static String ToHex(this byte[] data)
{
StringBuilder ret = new StringBuilder(String.Empty);
foreach (byte Value in data)
{
ret.Append(Value.ToString("x2"));
}
return ret.ToString();
}
public static byte[] FromHex(this string data)
{
int Pair = data.Length % 2;
byte[] ret = new byte[data.Length / 2];
if (Pair == 0)
{
for (int i = 0; i < data.Length / 2; i++)
{
ret[i] = Convert.ToByte(data.Substring(i * 2, 2), 16);
}
}
else
{
throw new SystemException("Invalid hex string.");
}
return ret;
}
public static byte[] ToByteArray(this string data)
{
return Encoding.UTF8.GetBytes(data);
}
public static string ToStr(this byte[] data)
{
return Encoding.UTF8.GetString(data);
}
}
public class Example
{
public static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8; //Use Windows Terminal for correct output of UTF-8. No problem on Linux or MacOS Default is UTF-8.
string data = "Purchase Amount مبلغ الشراء";
Console.WriteLine("Original: " + data);
data = data.ToByteArray().ToHex();
Console.WriteLine("Encoded: " + data);
data = data.FromHex().ToStr();
Console.WriteLine("Decoded: " + data);
Console.WriteLine();
Console.WriteLine();
data = "Thanks for your visit شكرا لزيارتكم";
Console.WriteLine("Original: " + data);
data = data.ToByteArray().ToHex();
Console.WriteLine("Encoded: " + data);
data = data.FromHex().ToStr();
Console.WriteLine("Decoded: " + data);
Console.ReadKey();
}
}
Output
On Windows. In console for correct output(arabic codepoints) using UTF-8, I recomend install Windows Terminal.
run wt.exe (Windows terminal)
Inside Windows terminal, run the program.
Magic.
On Linux or MacOS no problem with UTF-8.
PS C:\Users\Megam\source\repos\ConsoleApplication1\ConsoleAppCs\bin\Debug\net5.0> .\ConsoleAppCs.exe
Original: Purchase Amount مبلغ الشراء
Encoded: 507572636861736520416d6f756e742020202020202020202020202020202020202020d985d8a8d984d8ba20d8a7d984d8b4d8b1d8a7d8a1
Decoded: Purchase Amount مبلغ الشراء
Original: Thanks for your visit شكرا لزيارتكم
Encoded: 5468616e6b7320666f7220796f757220766973697420202020202020202020202020d8b4d983d8b1d8a720d984d8b2d98ad8a7d8b1d8aad983d985
Decoded: Thanks for your visit شكرا لزيارتكم
Arabic characters is lies on UTF 8 characters, and for this you initially have to convert it as byte array like this
byte[] bytes = Encoding.UTF8.GetBytes(output);
After that convert it into base64 string or any string you need to convert.
For converting to base64 string
string base64Str = Convert.ToBase64String(bytes);
For getting original bytes from base64 string
byte originalByte = Convert.FromBase64String(base64Str);
For getting UTF8 original output from byte array
string originalResult = Encoding.UTF8.GetString(bytes);
In one line you can get base64 string and revert back as follows
Encode
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(output));
Decode
string OriginalString = Encoding.UTF8.GetString(Convert.FromBase64String(encodedStr));
I have a text which cannot be converted to windows-1251 charset. For example:
中华全国工商业联合会-HelloWorld
I have a method for converting from UTF8 to windows-1251:
static string ChangeEncoding(string text)
{
if (text == null || text == "")
return "";
Encoding win1251 = Encoding.GetEncoding("windows-1251");
Encoding ascii = Encoding.UTF8;
byte[] utfBytes = ascii.GetBytes(text);
byte[] isoBytes = Encoding.Convert(ascii, win1251, utfBytes);
return win1251.GetString(isoBytes);
}
Now it is returning this:
??????????-HelloWorld
I don't want to show chars which was not converted to windows1251 charset correct. In this case I want just:
-HelloWorld
How can I do this?
According to #JeroenMostert suggestion this method helped me:
public static string ChangeEncoding(string text)
{
Encoding win1251 = Encoding.GetEncoding("windows-1251", new EncoderReplacementFallback(string.Empty), new DecoderExceptionFallback());
return win1251.GetString(Encoding.Convert(Encoding.UTF8, win1251, Encoding.UTF8.GetBytes(text)));
}
The text ZIRT which i encrypt by base64 this way
public static string encrypt(string ToEncrypt)
{
return Convert.ToBase64String(Encoding.ASCII.GetBytes(ToEncrypt));
}
after encrypt the text becomes V2tsU1ZB and when i try to decrypt using the below function
public static string decrypt(string cypherString)
{
//return Encoding.ASCII.GetString(Convert.FromBase64String(cypherString));
byte[] data = Convert.FromBase64String(cypherString);
string decodedString = Encoding.UTF8.GetString(data);
return decodedString;
}
then i am getting this text WklSVA but it suppose to be ZIRT
Please tell me what is wrong in my code ?
I am giving more code which fail to decrypt text
private void button1_Click(object sender, EventArgs e)
{
string strTxt = "ZIRT";
string ss = EnryptString(strTxt);
string ss1 = EnryptString(ss);
}
public string DecryptString(string encrString)
{
byte[] b;
string decrypted;
try
{
b = Convert.FromBase64String(encrString);
decrypted = System.Text.ASCIIEncoding.ASCII.GetString(b);
}
catch (FormatException fe)
{
decrypted = "";
}
return decrypted;
}
public string EnryptString(string strEncrypted)
{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted);
string encrypted = Convert.ToBase64String(b);
return encrypted;
}
There is double encoding of the strings that explain the incorrect result. You are also using different text encodings when encrypting and decrypting. ASCII vs UTF8, this should be the same.
The following example provides the result I would expect:
byte[] b = System.Text.ASCIIEncoding.UTF8.GetBytes("test abc");
string base64Encoded = Convert.ToBase64String(b);
b = Convert.FromBase64String(base64Encoded);
Console.WriteLine( System.Text.ASCIIEncoding.UTF8.GetString(b));
// "test abc"
As mentioned in the comments, this is not encryption, but encoding.
I have two methods, where I need to convert string to base64 at begin and reverse this operation at the end. Problem is when my input string lenght is not divisible by 4 an conversion method throws exception.
public class Hashing
{
public string Encrypt(string encrypted)
{
byte[] byteData = Convert.FromBase64String(encrypted);
byte[] byteResult = Encrypt(byteData); // pt.1
return Convert.ToBase64String(byteResult);
}
public string Decrypt(string decrypted)
{
byte[] byteData = Convert.FromBase64String(decrypted);
byte[] byteResult = Decrypt(byteData); //pt.2
return Convert.ToBase64String(byteResult);
}
/*
...
*/
}
class Program
{
static void Main(string[] args)
{
Hashing cryptographyContext = new Hashing();
var cryptoTest = "123456789"; //someStringThatNotGonnaBeConverted;
string enc = cryptographyContext.Encrypt(password);
string dec = cryptographyContext.Decrypt(enc);
Console.WriteLine(dec);
Console.ReadLine();
}
}
Problem is I need base64 format at input of Decrypt and Encrypt methods (these at pt. 1 and 2) And I need returning strings from these methods. Do someone have an idea how to workaround this behaviour?
You are using base-64 incorrectly; base-64 translates:
forwards, arbitrary byte[] to structured string
backwards, structured string to the original byte[]
Conversely, a regular text encoding works the other way:
forwards, arbitrary string to structured byte[]
backwards, structured byte[] to the original string
You are trying to use base-64 to get a byte[] from an arbitrary string, which isn't a thing that it does. For that, you want a regular text encoding, such as UTF-8. Try using Encoding.UTF8.GetBytes() etc instead for one half, and base-64 for the other:
public string Encrypt(string plainText)
{
byte[] byteData = Encoding.UTF8.GetBytes(plainText);
byte[] byteResult = Encrypt(byteData);
return Convert.ToBase64String(byteResult);
}
public string Decrypt(string cipherText)
{
byte[] byteData = Convert.FromBase64String(cipherText);
byte[] byteResult = Decrypt(byteData);
return Encoding.UTF8.GetString(byteResult);
}
import android.util.Base64;
public static String Base64(String str) {
byte[] data = new byte[0];
data = str.getBytes("UTF-8");
String base64 = Base64.encodeToString(data, 0);
return base64;
}
it is a android method to convert base64
public string Base64(string str)
{
byte[] data = new byte[0];
data = System.Text.Encoding.UTF8.GetBytes(str);
string base64 = Convert.ToBase64String(data);
return base64;
}
it is c# method
but both output are different
what can i do for same output??