Convert SQLite Blob to Hex to string - c#

I'm writing a console app that will grab some data from a Chrome extension and email me a report. The data is stored as JSON in the localstorage file, which is a sqlite database. If I copy the hex and convert it online at http://string-functions.com/hex-string.aspx it converts to the JSON properly. But, no matter how I try to do it in C#, it looks like this:
Here's my main portion of code:
static void Main(string[] args)
{
var dbLocation = ConfigurationManager.AppSettings["dbLocation"];
using (var connection = new SQLiteConnection(string.Format("Data Source={0};Version=3;", dbLocation)))
{
connection.Open();
var response = connection.Query<string>("SELECT hex(value) FROM ItemTable WHERE key = 'state'").Single();
var json = ConvertHex(response);
//var response = JsonConvert.DeserializeObject<ChromeData>(json);
}
}
For the ConvertHex function here's everything I have tried, all of which have the same result. These are pulled from various other StackOverflow answers.
public static string ConvertHex(String hexString)
{
try
{
string ascii = string.Empty;
for (int i = 0; i < hexString.Length; i += 2)
{
String hs = string.Empty;
hs = hexString.Substring(i, 2);
uint decval = System.Convert.ToUInt32(hs, 16);
char character = System.Convert.ToChar(decval);
ascii += character;
}
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}
private static string HexString2Ascii(string hexString)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= hexString.Length - 2; i += 2)
{
sb.Append(Convert.ToString(Convert.ToChar(Int32.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.HexNumber))));
}
return sb.ToString();
}
public static byte[] FromHex(string hex)
{
hex = hex.Replace("-", "");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
}
return raw;
}
static string HexStringToString(string hexString)
{
if (hexString == null || (hexString.Length & 1) == 1)
{
throw new ArgumentException();
}
var sb = new StringBuilder();
for (var i = 0; i < hexString.Length; i += 2)
{
var hexChar = hexString.Substring(i, 2);
sb.Append((char)Convert.ToByte(hexChar, 16));
}
return sb.ToString();
}
Any help is appreciated. Thanks!

Try below code.
Change the try block of ConvertHex as said below.
Look into comments for the details.
public static string ConvertHex(String hexString)
{
try
{
//DECLARE A VARIABLE TO RETURN
string ascii = string.Empty;
//SPLIT THE HEX STRING BASED ON SPACE (ONE SPACE BETWEEN TWO NUMBERS)
string[] hexSplit = hexString.Split(' ');
//LOOP THROUGH THE EACH HEX SPLIT
foreach (String hex in hexSplit)
{
// CONVERT THE NUMBER TO BASE 16
int value = Convert.ToInt32(hex, 16);
// GET THE RESPECTIVE CHARACTER
string stringValue = Char.ConvertFromUtf32(value);
char charValue = (char)value;
//APPEND THE STRING
ascii += charValue;
}
//RETURN THE STRING
return ascii;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
return string.Empty;
}

Related

HttpContext.Session.TryGetValue gives nonsense [duplicate]

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);
}

Decode GSM 7 bit in C#

I need to decode GSM 7 bit to ascii string in c# so that I googled and found lots of different posts about it, this post is one of them but It is not a c#.
Can anyone please share a c# code that can decode GSM 7-bit Character to ASCII string.
Thanks.
class GSM7BitDecoder
{
// Basic Character Set
private const string BASIC_SET =
"#£$¥èéùìòÇ\nØø\rÅåΔ_ΦΓΛΩΠΨΣΘΞ\x1bÆæßÉ !\"#¤%&'()*+,-./0123456789:;<=>?" +
"¡ABCDEFGHIJKLMNOPQRSTUVWXYZÄÖÑܧ¿abcdefghijklmnopqrstuvwxyzäöñüà";
// Basic Character Set Extension
private const string EXTENSION_SET =
"````````````````````^```````````````````{}`````\\````````````[~]`" +
"|````````````````````````````````````€``````````````````````````";
string[] BASIC_SET_ARRAY = BASIC_SET.Select(x => x.ToString()).ToArray();
string[] EXTENSION_SET_ARRAY = EXTENSION_SET.Select(x => x.ToString()).ToArray();
enum circle { Start=1, Complete=8 }
string GetChar(string bin)
{
try
{
if (Convert.ToInt32(bin, 2).Equals(27))
return EXTENSION_SET_ARRAY[Convert.ToInt32(bin, 2)];
else
return BASIC_SET_ARRAY[Convert.ToInt32(bin, 2)];
}
catch { return string.Empty; }
}
public string DecodeGSM7bit(string strGsm7bit)
{
var suffix = string.Empty;
var septet = string.Empty;
var CurSubstr = string.Empty;
var counter = 1;
List<string> septets = new List<string>();
List<string> sectets = new List<string>();
//Prepare Octets
var octets = Enumerable.Range(0, strGsm7bit.Length / 2).Select(i =>
{
return Convert.ToString(Convert.ToInt64(strGsm7bit.Substring(i * 2, 2), 16), 2).PadLeft(8,'0');
}).ToList();
for (var index=0; index < octets.Count; index = index +1)
{
//Generate Septets
septet = octets[index].Substring(counter);
CurSubstr = octets[index].Substring(0, counter);
if (counter.Equals((int)circle.Start))
septets.Add(septet);
else
septets.Add(septet + suffix);
//Organize Sectets
sectets.Add(GetChar(septets[index]));
suffix = CurSubstr;
counter++;
//Reset counter when the circle is complete.
if (counter == (int)circle.Complete)
{
counter = (int)circle.Start;
sectets.Add(GetChar(suffix));
}
}
return string.Join("", sectets);
}

How to convert Quoted-Print String

I'm working on French String in .NET
Decoding a Mail body , I receive "Chasn=C3=A9 sur illet"
I would like to get "Chasné sur illet"
and i don't find any solution aver 2 days web search.
C# ou VB.NET
Can anyone helps me ?
thanks
Or the easiest of all, just use the QuotedPrintableDecoder from my MimeKit library:
static string DecodeQuotedPrintable (string input, string charset)
{
var decoder = new QuotedPrintableDecoder ();
var buffer = Encoding.ASCII.GetBytes (input);
var output = new byte[decoder.EstimateOutputLength (buffer.Length)];
int used = decoder.Decode (buffer, 0, buffer.Length, output);
var encoding = Encoding.GetEncoding (charset);
return encoding.GetString (output, 0, used);
}
Note that the other answers above assume the decoded content will be ASCII or UTF-8, but that isn't necessarily the case. You'll need to get the charset parameter from the Content-Type header of the MIME part that you are decoding.
Of course... if you don't know how to get that info, you could simply use my awesome MailKit library to get the MIME part from IMAP and have it do all of this work for you.
This is UTF8 encoding.
Using this post:
http://www.dpit.co.uk/decoding-quoted-printable-email-in-c/
Here is the code (don't forget to accept the answer if helped):
using System;
using System.Text;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(DecodeQuotedPrintable("Chasn=C3=A9 sur illet"));
Console.ReadKey();
}
static string DecodeQuotedPrintable(string input)
{
var occurences = new Regex(#"(=[0-9A-Z][0-9A-Z])+", RegexOptions.Multiline);
var matches = occurences.Matches(input);
foreach (Match m in matches)
{
byte[] bytes = new byte[m.Value.Length / 3];
for (int i = 0; i < bytes.Length; i++)
{
string hex = m.Value.Substring(i * 3 + 1, 2);
int iHex = Convert.ToInt32(hex, 16);
bytes[i] = Convert.ToByte(iHex);
}
input = input.Replace(m.Value, Encoding.UTF8.GetString(bytes));
}
return input.Replace("=rn", "");
}
}
}
From : https://stackoverflow.com/a/36803911/6403521
My solution :
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual("La Bouichère", quotedprintable("La Bouich=C3=A8re", "utf-8"));
Assert.AreEqual("Chasné sur illet", quotedprintable("Chasn=C3=A9 sur illet", "utf-8"));
Assert.AreEqual("é è", quotedprintable("=C3=A9 =C3=A8", "utf-8"));
}
private string quotedprintable(string pStrIn, string encoding)
{
String strOut = pStrIn.Replace("=\r\n", "");
// Find the first =
int position = strOut.IndexOf("=");
while (position != -1)
{
// String before the =
string leftpart = strOut.Substring(0, position);
// get the QuotedPrintable String in a ArrayList
System.Collections.ArrayList hex = new System.Collections.ArrayList();
// The first Part
hex.Add(strOut.Substring(1 + position, 2));
// Look for the next parts
while (position + 3 < strOut.Length && strOut.Substring(position + 3, 1) == "=")
{
position = position + 3;
hex.Add(strOut.Substring(1 + position, 2));
}
// In the hex Array, we have two items
// Convert using the GetEncoding Function
byte[] bytes = new byte[hex.Count];
for (int i = 0; i < hex.Count; i++)
{
bytes[i] = System.Convert.ToByte(new string(((string)hex[i]).ToCharArray()), 16);
}
string equivalent = System.Text.Encoding.GetEncoding(encoding).GetString(bytes);
// Part of the orignal String after the last QP Symbol
string rightpart = strOut.Substring(position + 3);
// Re build the String
strOut = leftpart + equivalent + rightpart;
// find the new QP Position
position = leftpart.Length + equivalent.Length;
if (rightpart.Length == 0)
{
position = -1;
}
else
{
position = strOut.IndexOf("=", position + 1);
}
}
return strOut;
}
We had an issue with this method - that it is VERY slow.
The following enhanced performance A LOT
public static string FromMailTransferEncoding(this string messageText, Encoding enc, string transferEncoding)
{
if (string.IsNullOrEmpty(transferEncoding))
return messageText;
if ("quoted-printable".Equals(transferEncoding.ToLower()))
{
StringBuilder sb = new StringBuilder();
string delimitorRegEx = #"=[\r][\n]";
string[] parts = Regex.Split(messageText, delimitorRegEx);
foreach (string part in parts)
{
string subPart = part;
Regex occurences = new Regex(#"(=[0-9A-Z][0-9A-Z])+", RegexOptions.Multiline);
MatchCollection matches = occurences.Matches(subPart);
foreach (Match m in matches)
{
byte[] bytes = new byte[m.Value.Length / 3];
for (int i = 0; i < bytes.Length; i++)
{
string hex = m.Value.Substring(i * 3 + 1, 2);
int iHex = Convert.ToInt32(hex, 16);
bytes[i] = Convert.ToByte(iHex);
}
subPart = occurences.Replace(subPart, enc.GetString(bytes), 1);
}
sb.Append(subPart);
}
return sb.ToString();
}
return messageText;
}
static string ConverFromHex(string source)
{
string target = string.Empty;
int startPos = source.IndexOf('=', 0);
int prevStartPos = 0;
while (startPos >= 0)
{
// concat with substring from source
target += source.Substring(prevStartPos, startPos - prevStartPos);
// next offset
startPos++;
// update prev pos
prevStartPos = startPos;
// get substring
string hexString = source.Substring(startPos, 2);
// get int equiv
int hexNum = 0;
if (int.TryParse(hexString, System.Globalization.NumberStyles.AllowHexSpecifier, System.Globalization.CultureInfo.InvariantCulture, out hexNum))
{
// add to target string
target += (char)hexNum;
// add hex length
prevStartPos += 2;
}
// next occurence
startPos = source.IndexOf('=', startPos);
}
// add rest of source
target += source.Substring(prevStartPos);
return target;
}

Name of Encryption

i was going through encryption today and my colleague told me a simpler/custom way to do it, what i did is listed down there, so can you please tell me what type of encryption or hashign is that? he told me that this is the mixture of some sort of hashing and encryption. Sorry for stupid question i am new here. :)
the below method takes a string (password in my case). reverses it and makes a dictionary (adding dictionary items are listed below) and matches the keys and values and return encrypted data.
public static string Encrypt(string source)
{
string enCrypted = "";
try
{
source = Reverse(source);
Dictionary<char, char> sourceTable = AddDictionaryItems();
char[] sourceArray = source.ToCharArray();
StringBuilder encryptedData = new StringBuilder();
foreach (char chr in sourceArray)
{
KeyValuePair<char, char> Pair;
Pair = sourceTable.First(tuple => tuple.Key == chr);
encryptedData.Append(Pair.Value);
}
enCrypted=encryptedData.ToString();
}
catch (Exception ex)
{
}
return enCrypted;
}
the below method adds items into dictionary, items are basically based on ascii codes. i loop through all asciis and then corresponding charachters are added in the dictionary. but the real trick is that when adding an item in the dictionary. e.g., when i add 'A' in dictionary as a key, then its value would be 'D'. the variable "jump" specifies the difference between key and value. so if my password is 'ABC' it would return 'DEF' or 'FED' if i reverse that thing.
public static Dictionary<char, char> AddDictionaryItems()
{
Dictionary<char, char> dc = new Dictionary<char, char>();
try
{
int initial = 33;
int jump = 3;
int final = 127 - jump;
for (int ascii = initial; ascii < final; ascii++)
{
dc.Add((char)ascii, (char)(ascii + jump));
}
for (int ascii = final; ascii < final + jump; ascii++)
{
dc.Add((char)ascii, (char)(initial));
initial++;
}
}
catch (Exception ex)
{
throw ex;
}
return dc;
}
That would be a Substitution Cipher, however unless you are making this for fun, do not use this method for anything that requires security. 1000's of people crack this encryption method every day for fun (check your local newspaper, it likely has one too, it is usually next to the crossword).
guys i have tailored my code
public static string Reverse(string str)
{
char[] charArray = str.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
public static string Encrypt(string source)
{
string prefix = Guid.NewGuid().ToString();
string infix = Guid.NewGuid().ToString();
string postfix = Guid.NewGuid().ToString();
int length = source.Length;
string firstHalf = source.Substring(0, length / 2);
string secondHalf = source.Substring(length / 2);
string ConcatedPassword = prefix + firstHalf + infix + secondHalf + postfix;
string enCrypted = "";
try
{
ConcatedPassword = Reverse(ConcatedPassword);
Dictionary<char, char> sourceTable = AddDictionaryItems();
char[] sourceArray = ConcatedPassword.ToCharArray();
StringBuilder encryptedData = new StringBuilder();
foreach (char chr in sourceArray)
{
KeyValuePair<char, char> Pair;
Pair = sourceTable.First(tuple => tuple.Key == chr);
encryptedData.Append(Pair.Value);
}
enCrypted = encryptedData.ToString();
}
catch (Exception ex)
{
}
return enCrypted;
}
public static string Decrypt(string source)
{
string deCrypted = "";
try
{
source = Reverse(source);
Dictionary<char, char> sourceTable = AddDictionaryItems();
char[] sourceArray = source.ToCharArray();
StringBuilder decryptedData = new StringBuilder();
foreach (char chr in sourceArray)
{
KeyValuePair<char, char> Pair;
Pair = sourceTable.First(tuple => tuple.Value == chr);
decryptedData.Append(Pair.Key);
}
deCrypted = decryptedData.ToString();
string prefixRemoved = deCrypted.Remove(0, 36);
string postfixRemoved = prefixRemoved.Remove(prefixRemoved.Length - 36);
string infixRemoved = postfixRemoved.Remove((postfixRemoved.Length - 36) / 2, 36);
deCrypted = infixRemoved;
}
catch (Exception ex)
{
}
return deCrypted;
}
public static Dictionary<char, char> AddDictionaryItems()
{
Dictionary<char, char> dc = new Dictionary<char, char>();
try
{
int initial = 33;
int jump = 10;
int final = 127 - jump;
for (int ascii = initial; ascii < final; ascii++)
{
dc.Add((char)ascii, (char)(ascii + jump));
}
for (int ascii = final; ascii < final + jump; ascii++)
{
dc.Add((char)ascii, (char)(initial));
initial++;
}
}
catch (Exception ex)
{
}
return dc;
}
protected void Page_Load(object sender, EventArgs e)
{
string password = "$Om3P#55w0r6";
string encrypted = Encrypt(password);
string decrypted = Decrypt(encrypted);
}
the encryption is not secure but its a start. i hope it helps someone writing his own method from the scratch.

Appending Strings in Java/C# without using StringBuffer.Append or StringBuilder.Append

at a recent interview I attended, the programming question that was asked was this. Write a function that will take as input two strings. The output should be the result of concatenation.
Conditions: Should not use StringBuffer.Append or StringBuilder.Append or string objects for concatenation;that is, they want me to implement the pseudo code implementation of How StringBuilder or StringBuffer's Append function works.
This is what I did:
static char[] AppendStrings(string input, string append)
{
char[] inputCharArray = input.ToCharArray();
char[] appendCharArray = append.ToCharArray();
char[] outputCharArray = new char[inputCharArray.Length + appendCharArray.Length];
for (int i = 0; i < inputCharArray.Length; i++)
{
outputCharArray[i] = inputCharArray[i];
}
for (int i = 0; i < appendCharArray.Length; i++)
{
outputCharArray[input.Length + i] = appendCharArray[i];
}
return outputCharArray;
}
While this is a working solution, is there a better way of doing things?
is LINQ legal? strings are just can be treated as an enumeration of chars, so they can be used with LINQ (even though there is some cost involved, see comments):
string a = "foo";
string b = "bar";
string c = new string(a.AsEnumerable().Concat(b).ToArray());
or with your method signature:
static char[] AppendStrings(string input, string append)
{
return input.AsEnumerable().Concat(append).ToArray();
}
You can call CopyTo:
char[] output = new char[a.Length + b.Length];
a.CopyTo(0, output, 0, a.Length);
b.CopyTo(0, output, a.Length, b.Length);
return new String(output);
If they don't like that, call .ToCharArray().CopyTo(...).
You can also cheat:
return String.Join("", new [] { a, b });
return String.Format("{0}{1}", a, b);
var writer = new StringWriter();
writer.Write(a);
writer.Write(b);
return writer.ToString();
I would've done something like the following (argument checking omitted for brevity)
public static string Append(string left, string right) {
var array = new char[left.Length + right.Length];
for (var i = 0; i < left.Length; i++) {
array[i] = left[i];
}
for (var i = 0; i < right.Length; i++) {
array[i + left.Length] = right[i];
}
return new string(array);
}
In Java you can just use concat which does not use StringBuilder or StringBuffer.
String a = "foo";
String b = "bar";
String ab = a.concat(b);
The source for String.concat(String) from Oracle's JDK.
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
char buf[] = new char[count + otherLen];
getChars(0, count, buf, 0);
str.getChars(0, otherLen, buf, count);
return new String(0, count + otherLen, buf);
}
java default support "+" for append string
String temp="some text";
for(int i=0;i<10;i++)
{
temp=temp+i;
}
Or
temp=temp+" some other text"

Categories

Resources