How do I decode a base64 encoded string? - c#

I am trying to "decode" this following Base64 string:
OBFZDTcPCxlCKhdXCQ0kMQhKPh9uIgYIAQxALBtZAwUeOzcdcUEeW0dMO1kbPElWCV1ISFFKZ0kdWFlLAURPZhEFQVseXVtPOUUICVhMAzcfZ14AVEdIVVgfAUIBWVpOUlAeaUVMXFlKIy9rGUN0VF08Oz1POxFfTCcVFw1LMQNbBQYWAQ==
This is what I know about the string itself:
The original string is first passed through the following code:
private static string m000493(string p0, string p1)
{
StringBuilder builder = new StringBuilder(p0);
StringBuilder builder2 = new StringBuilder(p1);
StringBuilder builder3 = new StringBuilder(p0.Length);
int num = 0;
Label_0084:
while (num < builder.Length)
{
int num2 = 0;
while (num2 < p1.Length)
{
if ((num == builder.Length) || (num2 == builder2.Length))
{
MessageBox.Show("EH?");
goto Label_0084;
}
char ch = builder[num];
char ch2 = builder2[num2];
ch = (char)(ch ^ ch2);
builder3.Append(ch);
num2++;
num++;
}
}
return m0001cd(builder3.ToString());
}
The p1 part in the code is supposed to be the string "_p0lizei.".
It is then converted to a Base64 string by the following code:
private static string m0001cd(string p0)
{
string str2;
try
{
byte[] buffer = new byte[p0.Length];
str2 = Convert.ToBase64String(Encoding.UTF8.GetBytes(p0));
}
catch (Exception exception)
{
throw new Exception("Error in base64Encode" + exception.Message);
}
return str2;
}
The question is, how do I decode the Base64 string so that I can find out what the original string is?

Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encoding and decoding the text. All you have to do is reverse m0001cd:
string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));
string result = m000493(p0, "_p0lizei.");
// result == "gaia^unplugged^Ta..."
with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

// Decode a Base64 string to a string
public static string DecodeBase64(string value)
{
if(string.IsNullOrEmpty(value))
return string.Empty;
var valueBytes = System.Convert.FromBase64String(value);
return System.Text.Encoding.UTF8.GetString(valueBytes);
}

Related

How to parse a string that contains multiple tokens and multiple delimiters in C#?

The string (aka Message) I am trying to parse out looks like this. (It also looks exactly like this when you paste it in Notepad
"CorrelationId: b99fb632-78cf-4910-ab23-4f69833ed2d9
Request for API: /api/acmsxdsreader/readpolicyfrompolicyassignment Caller:C2F023C52E2148C9C1D040FBFAC113D463A368B1 CorrelationId: b99fb632-78cf-4910-ab23-4f69833ed2d9 RequestedSchemas: {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}VoicePolicy, {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}OnlineVoiceRoutingPolicy, TenantId: 7a205197-8e59-487d-b9fa-3fc1b108f1e5"
I would like to make 5 separate functions that return each of the specific values which would be like GetCorrelationId, GetRFAPI, GetCaller, GetRqSchema, and GetTenantId and extract out their corresponding values.
How would I do this in C# without using Regex?
Below is the code I have made for the caller (and this method is the same for all other 4 functions) but I have been advised that regex is slow and should not be used by my mentor and the method I have below doesn't even work anyway. Also, my biggest problem with trying to use the regex is that there are multiple delimiters in the message like ',' ' ' and ': ' and ':'
string parseCaller(string message)
{
var pattern = #"Caller:(.*)";
var r = new Regex(pattern).Match(message);
var caller = r.Groups[1].Value;
return caller;
}
Expected result should be:
GetCorrelationId(message) RETURNS b99fb632-78cf-4910-ab23-4f69833ed2d9
GetRFAPI(message) RETURNS /api/acmsxdsreader/readpolicyfrompolicyassignment
GetRqSchema(message) RETURNS {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}VoicePolicy, {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}OnlineVoiceRoutingPolicy
GetCaller(message) RETURNS C2F023C52E2148C9C1D040FBFAC113D463A368B1
GetTenantId(message) RETURNS 7a205197-8e59-487d-b9fa-3fc1b108f1e5
I would approach this a little differently and create a class that has properties for each value you want to parse from the string. Then we can create a static Parse method that creates an instance of the class from an input string, which sets all the properties for you.
If the string always has the same items (CorrelationId, RequestForAPI, Caller, etc) in the same order, we can utilize a simple helper method to GetValueBetween two headers.
The code is pretty simple:
class MessageData
{
public string CorrelationId { get; set; }
public string RequestForAPI { get; set; }
public string RequestedSchemas { get; set; }
public string Caller { get; set; }
public string TennantId { get; set; }
public static MessageData Parse(string input)
{
return new MessageData
{
CorrelationId = GetValueBetween(input, "CorrelationId:", "Request for API:"),
RequestForAPI = GetValueBetween(input, "Request for API:", "Caller:"),
Caller = GetValueBetween(input, "Caller:", "CorrelationId:"),
RequestedSchemas = GetValueBetween(input, "RequestedSchemas:", "TenantId:"),
TennantId = GetValueBetween(input, "TenantId:", null),
};
}
private static string GetValueBetween(string input, string startDelim, string endDelim)
{
if (input == null) return string.Empty;
var start = input.IndexOf(startDelim);
if (start == -1) return string.Empty;
start += startDelim.Length;
var length = endDelim == null
? input.Length - start
: input.IndexOf(endDelim, start) - start;
if (length < 0) length = input.Length - start;
return input.Substring(start, length).Trim();
}
}
And now we can just call MessageData.Parse(inputString), and we have a class with all it's properties set from the input string:
private static void Main()
{
var message = #"CorrelationId: b99fb632-78cf-4910-ab23-4f69833ed2d9
Request for API: /api/acmsxdsreader/readpolicyfrompolicyassignment Caller:C2F023C52E2148C9C1D040FBFAC113D463A368B1 CorrelationId: b99fb632-78cf-4910-ab23-4f69833ed2d9 RequestedSchemas: {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}VoicePolicy, {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}OnlineVoiceRoutingPolicy, TenantId: 7a205197-8e59-487d-b9fa-3fc1b108f1e5";
var messageData = MessageData.Parse(message);
// Now we can access any property
Console.WriteLine(messageData.CorrelationId);
Console.WriteLine(messageData.RequestForAPI);
Console.WriteLine(messageData.RequestedSchemas);
Console.WriteLine(messageData.Caller);
Console.WriteLine(messageData.TennantId);
Console.ReadKey();
}
Based on these specifications in your question:
How would I do this in C# without using Regex?
and
I would like to make 5 separate functions
You can try the below. It's really simple, as you can study your string and use IndexOf and SubString functions appropriately:
using System;
class ParseTest
{
static string GetCorrelationId(string message)
{
int i = message.IndexOf(": ") + 2; //length of ": "
int j = message.IndexOf("Request");
return message.Substring(i, j-i).Trim();
}
static string GetRFAPI(string message)
{
int i = message.IndexOf("API: ") + 5; //length of "API: "
int j = message.IndexOf("Caller");
return message.Substring(i, j-i).Trim();
}
static string GetCaller(string message)
{
int i = message.IndexOf("Caller:") + 7; //length of "Caller: "
int j = message.IndexOf(" CorrelationId");
return message.Substring(i, j-i).Trim();
}
static string GetRqSchema(string message)
{
int i = message.IndexOf("RequestedSchemas:") + 17; //length of "RequestedSchemas:"
int j = message.IndexOf(", TenantId:");
return message.Substring(i, j-i).Trim();
}
static string GetTenantId(string message)
{
int i = message.IndexOf("TenantId:") + 9; //length of "TenantId: "
return message.Substring(i).Trim();
}
static void Main()
{
string m = #"CorrelationId: b99fb632-78cf-4910-ab23-4f69833ed2d9
Request for API: /api/acmsxdsreader/readpolicyfrompolicyassignment Caller:C2F023C52E2148C9C1D040FBFAC113D463A368B1 CorrelationId: b99fb632-78cf-4910-ab23-4f69833ed2d9 RequestedSchemas: {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}VoicePolicy, {urn:schema:Microsoft.Rtc.Management.Policy.Voice.2008}OnlineVoiceRoutingPolicy, TenantId: 7a205197-8e59-487d-b9fa-3fc1b108f1e5";
Console.WriteLine(GetCorrelationId(m));
Console.WriteLine(GetRFAPI(m));
Console.WriteLine(GetCaller(m));
Console.WriteLine(GetRqSchema(m));
Console.WriteLine(GetTenantId(m));
}
}
You can run it here.
EDIT: Of course you can modify this to use get-only properties, as some other answerers have tried to do.
If, on the other hand, you want to write a parser (this is kind of lazy one 😂), then that's another matter for your researching pleasure.
Here's a more robust solution if you don't know if the order of these elements returned from the API will change in the future:
private string GetRFAPI(string str)
{
return GetSubstring(str, "Request for API: ", ' ', 1);
}
private string GetCaller(string str)
{
return GetSubstring(str, "Caller:", ' ', 1);
}
private string GetCorrelationId(string str)
{
return GetSubstring(str, "CorrelationId: ", ' ', 1);
}
private string GetTenantId(string str)
{
return GetSubstring(str, "TenantId: ", ' ', 1);
}
private string GetRequestedSchemas(string str)
{
return GetSubstring(str, "RequestedSchemas: ", ',', 2);
}
private string GetSubstring(string str, string pattern, char delimiter, int occurrence)
{
int start = str.IndexOf(pattern);
if (start < 0)
{
return null;
}
for (int i = start + pattern.Length, counter = 0; i < str.Length; i++, counter++)
{
if ((str[i] == delimiter && --occurrence == 0) || i == str.Length - 1)
{
return str.Substring(start + pattern.Length, counter).Trim();
}
}
return null;
}

exception Convert ToInt32 dans c#

I have this code but but when I run the program gives me this error System.FormatException: Input string was not in a correct format'.
public static void Main(string[] args)
{
string a =TextFormater("Teste teste ");
Console.WriteLine(a);
}
public static string TextFormater(string ChaineTextArea)
{
string val = string.Empty;
string Valreturn = string.Empty;
int result;
for (int i = 0; i <= ChaineTextArea.Length; i++)
{
val = ChaineTextArea.Substring(i, 1);
var chars = val.ToCharArray();
result = Convert.ToInt32(val);
if (result != 13)
{
Valreturn= val;
}
else
{
Valreturn= "<br>" + val;
}
}
return Valreturn;
}
Your input is not a valid format for converting to Integer. However if you need the ASCII value of those characters, that can be arranged by this
string input = "Teste teste ";
var values = Encoding.ASCII.GetBytes(input);
foreach(var item in values)
{
Console.WriteLine(item);
}
Console.ReadLine();
Hope that will help.
is not valid format I corrected by this code and is working
val = ChaineTextArea.Substring(i, 1);
char []chars = val.ToCharArray();
result = Convert.ToInt32(chars[0]);
I am not sure what you are trying to achieve. If you are trying to convert string to int then it is invalid conversion but you think if the val maybe int or string then try to use int.TryParse
Try it to convert int.Parse(val)
or
Int32.TryParse(val, out number);

A really long string have to be converted to numeric form. What datatype can be used appropriately?

My program is to decode string into number and perform some operations over this number.
The below program works fine for small string. What is the better way to handle large paragraphs (as input in this case)?!
public static void Main()
{
///<summary>Encoded String- Checking divisibility</summary>
Console.WriteLine("Enter Lowercase Latin letters ( 'a'-'i' )");
string originalString = Convert.ToString(Console.ReadLine());
bool chkValue = Regex.IsMatch(originalString, #"^[a-i]+$");
if(!chkValue)
{
return;
}
char[] originalchars = originalString.ToCharArray();
long decodedNumber=0;
StringBuilder decoded = new StringBuilder();
//int stringLength = originalString.Length;
for (int i = 0; i < originalchars.Length; i++)
{
decoded.Append(Convert.ToInt32(originalchars[i] - 96));
}
Console.WriteLine(decoded);
string decodedString = decoded.ToString();
bool parseResult = long.TryParse(decodedString ,out decodedNumber);
if (parseResult == true)
{
if (decodedNumber % 6 == 0)
Console.WriteLine("YES");
else
Console.WriteLine("NO");
}
Console.ReadLine();
}
As Steve mentioned, BigInteger fixed my problem.

String Utilities in C#

I'm learning about string utilities in C#, and I have a method that replaces parts of a string.
Using the replace method I need to get an output such as
"Old file name: file00"
"New file name: file01"
Depending on what the user wants to change it to.
I am looking for help on making the method (NextImageName) replace only the digits, but not the file name.
class BuildingBlock
{
public static string ReplaceOnce(string word, string characters, int position)
{
word = word.Remove(position, characters.Length);
word = word.Insert(position, characters);
return word;
}
public static string GetLastName(string name)
{
string result = "";
int posn = name.LastIndexOf(' ');
if (posn >= 0) result = name.Substring(posn + 1);
return result;
}
public static string NextImageName(string filename, int newNumber)
{
if (newNumber > 9)
{
return ReplaceOnce(filename, newNumber, (filename.Length - 2))
}
if (newNumber < 10)
{
}
if (newNumber == 0)
{
}
}
The other "if" statements are empty for now until I find out how to do the first one.
The correct way to do this would be to use Regular Expressions.
Ideally you would separate "file" from "00" in "file00". Then take "00", convert it to an Int32 (using Int32.Parse()) and then rebuild your string with String.Format().
public static string NextImageName(string filename, int newNumber)
{
string oldnumber = "";
foreach (var item in filename.ToCharArray().Reverse())
if (char.IsDigit(item))
oldnumber = item + oldnumber ;
else
break;
return filename.Replace(oldnumber ,newNumber.ToString());
}
public static string NextImageName(string filename, int newNumber)
{
int i = 0;
foreach (char c in filename) // get index of first number
{
if (char.IsNumber(c))
break;
else
i++;
}
string s = filename.Substring(0,i); // remove original number
s = s + newNumber.ToString(); // add new number
return s;
}

How can you remove duplicate characters in a string?

I have to implements a function that takes a string as an input and finds the non-duplicate character from this string.
So an an example is if I pass string str = "DHCD" it will return "DHC"
or str2 = "KLKLHHMO" it will return "KLHMO"
A Linq approach:
public static string RemoveDuplicates(string input)
{
return new string(input.ToCharArray().Distinct().ToArray());
}
It will do the job
string removedupes(string s)
{
string newString = string.Empty;
List<char> found = new List<char>();
foreach(char c in s)
{
if(found.Contains(c))
continue;
newString+=c.ToString();
found.Add(c);
}
return newString;
}
I should note this is criminally inefficient.
I think I was delirious on first revision.
For arbitrary length strings of byte-sized characters (not for wide characters or other encodings), I would use a lookup table, one bit per character (32 bytes for a 256-bit table). Loop through your string, only output characters that don't have their bits turned on, then turn the bit on for that character.
string removedupes(string s)
{
string t;
byte[] found = new byte[256];
foreach(char c in s)
{
if(!found[c]) {
t.Append(c);
found[c]=1;
}
}
return t;
}
I am not good with C#, so I don't know the right way to use a bitfield instead of a byte array.
If you know that your strings are going to be very short, then other approaches would offer better memory usage and/or speed.
void removeDuplicate()
{
string value1 = RemoveDuplicateChars("Devarajan");
}
static string RemoveDuplicateChars(string key)
{
string result = "";
foreach (char value in key)
if (result.IndexOf(value) == -1)
result += value;
return result;
}
It sounds like homework to me, so I'm just going to describe at a high level.
Loop over the string, examining each character
Check if you've seen the character before
if you have, remove it from the string
if you haven't, note that you've now seen that character
this is in C#. validation left out for brevity. primitive solution for removing duplicate chars from a given string
public static char[] RemoveDup(string s)
{
char[] chars = new char[s.Length];
int unique = 0;
chars[unique] = s[0]; // Assume: First char is unique
for (int i = 1; i < s.Length; i++)
{
// add char in i index to unique array
// if char in i-1 != i index
// i.e s = "ab" -> a != b
if (s[i-1] != s[i]
chars[++unique] = s[i];
}
return chars;
}
My answer in java language.
Posting here so that you might get a idea even it is in Java language.Algorithm would remain same.
public String removeDup(String s)
{
if(s==null) return null;
int l = s.length();
//if length is less than 2 return string
if(l<2)return s;
char arr[] = s.toCharArray();
for(int i=0;i<l;i++)
{
int j =i+1; //index to check with ith index
int t = i+1; //index of first repetative char.
while(j<l)
{
if(arr[j]==arr[i])
{
j++;
}
else
{
arr[t]=arr[j];
t++;
j++;
}
}
l=t;
}
return new String(arr,0,l);
}
you may use HashSet:
static void Main()
{
string textWithDuplicates = "aaabbcccggg";
Console.WriteLine(textWithDuplicates.Count());
var letters = new HashSet<char>(textWithDuplicates);
Console.WriteLine(letters.Count());
foreach (char c in letters) Console.Write(c);
}
class Program
{
static void Main(string[] args)
{
bool[] doesExists = new bool[256];
String st = Console.ReadLine();
StringBuilder sb = new StringBuilder();
foreach (char ch in st)
{
if (!doesExists[ch])
{
sb.Append(ch);
doesExists[ch] = true;
}
}
Console.WriteLine(sb.ToString());
}
}
Revised version of the first answer i.e: You don't need ToCharArray() function for this to work.
public static string RemoveDuplicates(string input)
{
return new string(input.Distinct().ToArray());
}
char *remove_duplicates(char *str)
{
char *str1, *str2;
if(!str)
return str;
str1 = str2 = str;
while(*str2)
{
if(strchr(str, *str2)<str2)
{
str2++;
continue;
}
*str1++ = *str2++;
}
*str1 = '\0';
return str;
}
char* removeDups(const char* str)
{
char* new_str = (char*)malloc(256*sizeof(char));
int i,j,current_pos = 0,len_of_new_str;
new_str[0]='\0';
for(i=0;i<strlen(str);i++)
{
len_of_new_str = strlen(new_str);
for(j=0;j<len_of_new_str && new_str[j]!=str[i];j++)
;
if(j==len_of_new_str)
{
new_str[len_of_new_str] = str[i];
new_str[len_of_new_str+1] = '\0';
}
}
return new_str;
}
Hope this helps
String str="AABBCANCDE";
String newStr="";
for( int i=0; i<str.length(); i++)
{
if(!newStr.contains(str.charAt(i)+""))
newStr= newStr+str.charAt(i);
}
System.out.println(newStr);
// Remove both upper-lower duplicates
public static string RemoveDuplicates(string key)
{
string Result = string.Empty;
foreach (char a in key)
{
if (Result.Contains(a.ToString().ToUpper()) || Result.Contains(a.ToString().ToLower()))
continue;
Result += a.ToString();
}
return Result;
}
var input1 = Console.ReadLine().ToLower().ToCharArray();
var input2 = input1;
var WithoutDuplicate = input1.Union(input2);
Console.WriteLine("Enter String");
string str = Console.ReadLine();
string result = "";
result += str[0]; // first character of string
for (int i = 1; i < str.Length; i++)
{
if (str[i - 1] != str[i])
result += str[i];
}
Console.WriteLine(result);
I like Quintin Robinson answer, only there should be some improvements like removing List, because it is not necessarry in this case.
Also, in my opinion Uppercase char ("K") and lowercase char ("k") is the same thing, so they should be counted as one.
So here is how I would do it:
private static string RemoveDuplicates(string textEntered)
{
string newString = string.Empty;
foreach (var c in textEntered)
{
if (newString.Contains(char.ToLower(c)) || newString.Contains(char.ToUpper(c)))
{
continue;
}
newString += c.ToString();
}
return newString;
}
Not sure how optimal it is:
public static string RemoveDuplicates(string input)
{
var output = string.Join("", input.ToHashSet());
return output;
}
Below is the code to remove duplicate chars from a string
var input = "SaaSingeshe";
var filteredString = new StringBuilder();
foreach(char c in input)
{
if(filteredString.ToString().IndexOf(c)==-1)
{
filteredString.Append(c);
}
}
Console.WriteLine(filteredString);
Console.ReadKey();
namespace Demo { class Program {
static void Main(string[] args) {
string myStr = "kkllmmnnouo";
Console.WriteLine("Initial String: "+myStr);
// var unique = new HashSet<char>(myStr);
HashSet<char> unique = new HashSet<char>(myStr);
Console.Write("New String after removing duplicates: ");
foreach (char c in unique)
Console.Write(c);
} } }
this works for me
private string removeDuplicateChars(String value)
{
return new string(value.Distinct().ToArray());
}

Categories