Iterate through registry keys and read registry values - c#

I want to iterate through the values of a specific path and read them.
I tried this
Code updated
RegistryKey key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Internet Explorer\IntelliForms\Storage2", true);
var names = key.GetValueNames();
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine(names[i]);
byte[] test = ObjectToByteArray(key.GetValue(names[i]));
var value = Convert.ToBase64String(test);
Console.WriteLine(value);
};
Normally the string value should be an encrypted binary.
Update: So as #Peter Lillevold suggested I had to convert the array of bytes into a string.
To do so, I created this small function to convert the object key.GetValue into an array of bytes
public static byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
return null;
BinaryFormatter Binaryform = new BinaryFormatter();
MemoryStream MemStream = new MemoryStream();
Binaryform.Serialize(MemStream, obj);
return MemStream.ToArray();
}
and then converted to a string as #Peter suggested.
So after the convertion of the array of bytes it is supposed to return me a string of binary.
What I get is some weird combination of letters and digits but it is not binary.
Any help on this?

You get "System.Byte[]" because you take an instance of byte[] and calls ToString() on it. This will not convert the content of the byte array into text, for that you would use something like Convert.ToBase64String or Encoding.UTF8.GetString. More discussion on the topic in this SO question.

Related

Why isn't the encoded key equal to the original key?

Language: C#, Framework: .NET Core 3.1
I am using encryption based on AES.
Research:
Key Format AES
Gilles: An AES key is just a bunch of bits with no structure.
The Key and IV need to be stored since they are randomly generated each time and they are required for Encryption and Decryption.
I need to store it as a string for particular reasons, so I want to be able to convert a byte array to a string and backwards if needed using encoding.
The conversion happens using UTF-8 encoding.
My problem:
I've put a breakpoint in my code and the contents of the byte array are clearly different from the original array. I've tried switching to other encoding formats but this also failed. In a nutshell, the data changed and this would result in being unable to decrypt a message because the AES key and IV would be incorrect.
Update:
The UTF-8 conversion doesn't work when keyBytes doesn't contain valid utf8 data and the encoder will generate fallback data which causes the problem.
Example:
using (Aes myAes = Aes.Create())
{
bool valid = false;
byte[] keyBytes = myAes.Key;
Encoding utf8WithoutBom = new UTF8Encoding(true);
string key = utf8WithoutBom.GetString(keyBytes);
byte[] outputBytes = utf8WithoutBom.GetBytes(key);
if (myAes.Key.Length == outputBytes.Length) {
for (int i = 0; i < myAes.Key.Length; i++) {
if (outputBytes[i] == keyBytes[i]) {
valid = true;
}
else {
valid = false;
break;
}
}
}
if (valid == true) {
Console.WriteLine("Succes");
}
else {
Console.WriteLine("Error");
throw new Exception("The keys do not match.");
}
}
Result:
- Output: byte[] with a size between 50~54 Error
- Desired Output: byte[32] with the same data as the original array Succes
Question: Why are the contents of the output byte array different from the original byte array?
The conversion from byte[] -> string -> byte[] will only work when the initial byte array contains a valid utf8 content. Not every 32 byte array does that.
If the original array contains invalid data, the byte[] -> string conversion will already return some fallback data and a second conversion will convert those fallback values to their corresponding bytes.
If you want to encode an arbitrary byte array into a string, use Base64 or some other general data encoding, but not utf8.

c# - how to best save and load an enum

I am trying to serialize an enum object within a class. Currently I am going to be using a binary reader and writer to serialize/de-serialize.
My enum is called SelectionType and has a few possible values.
In my serialize method I write the toString value of the enum object I want to save.
I then dont know what to do with the string to turn this back into an enum when I read the string. I dont really want to have a hard coded case for each possible value.
I basically want to say; SelectionType newenumobject = SelectionType.String // where string is the value read from the file.
ANy help would be greatly appreciated:
here is what I have:
public override void Serialize(Stream stream)
{
System.Diagnostics.Debug.WriteLine("in level select serialize");
using (BinaryWriter writer = new BinaryWriter(stream))
{
//Debug.WriteLine("the type is" + SelectionType.ToString());
writer.Write(SelectionType.ToString());
// Write out the full name of all the types in our stack so we can
// recreate them if needed.
//byte[] bytes = new byte[SelectionType.ToString().Length * sizeof(char)];
//System.BitConverter.GetBytes(mSlectionType);
//writer.Write(bytes, 0, bytes.Length);
}
}
public override void Deserialize(Stream stream)
{
using (BinaryReader reader = new BinaryReader(stream))
{
while (reader.BaseStream.Position < reader.BaseStream.Length)
{
// read a line from our file
string line = reader.ReadString();
// if it isn't blank, we can create a screen from it
if (!string.IsNullOrEmpty(line))
{
Debug.WriteLine("line is" + line);
Type screenType = Type.GetType(line);
//SelectionType selection = Enum.Parse(screenType, line, false);
}
}
// char[] chars = new char[bytes.Length / sizeof(char)];
//System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
//new string(chars);
}
If you care about file size and read/write speed, you should save the underlying value of the enumeration rather than converting it to a string.
// be sure to use the correct backing type for your enum (default is 32-bit int)
writer.Write((int)SelectionType);
//...
selection = (SelectionType)reader.ReadInt32()
You can just use Enum.Parse.
Here is an example: http://dotnetfiddle.net/0e1Ika
var myValue = MyEnum.Value3;
var stringRepresentation = myValue.ToString();
var intRepresentation = (int)myValue;
Console.WriteLine("String-Value: \"{0}\"", stringRepresentation);
Console.WriteLine("Int-Value: {0}", intRepresentation);
var parsedFromString = (MyEnum)Enum.Parse(typeof(MyEnum), stringRepresentation);
var parsedFromInt = (MyEnum)Enum.Parse(typeof(MyEnum), intRepresentation.ToString());
Console.WriteLine("Parsed from string: {0}", parsedFromString);
Console.WriteLine("Parsed from int: {0}", parsedFromInt);
Hope that helps.
Best regards,
Chris
ps: uh, seems #dave-bish was faster :)
if you know the type of the enum, you can use Enum.Parse
var myValue = (EnumType)Enum.Parse(typeof(EnumType), "StringValue");
[Edit]
I see you have it commented out in your example - Why didn't this work for you?

Convert object to byte

I want to convert an object, to a byte with silverlight.
So, first I found this : convert object(i.e any object like person, employee) to byte[] in silverlight
But this is not working(any of the answers), the dll proto seems not to be good.
Plus, i tried this:
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Address));
StringBuilder stringBuilder = new StringBuilder();
using (StringWriter writer = new StringWriter(stringBuilder))
{
serializer.Serialize(writer, address);
}
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] data = encoding.GetBytes(stringBuilder.ToString());
But I got a result in the byte.
What I receive is an object byte[0] , and I just want to verify his lenght is 0 or more.
I cannot do tihs with an object, and that's why I tried to convert it. But the byte in result is different from byte[0]
How can I do what I want? Just a comparison to 0.
After reading again your question, if the object is already a byte[] simply cast it:
object yourObject = xxx();
byte[] data = (byte[])yourObject;
bool hasData = data != null && data.Length > 0;
If you like there is also the MemoryStream object which convert object to byte[] and byte[] to object

Converting byte[] to an object

I'm trying to convert an object which I have in a byte[] to an object.
I've tried using this code I found online:
object byteArrayToObject(byte[] bytes)
{
try
{
MemoryStream ms = new MemoryStream(bytes);
BinaryFormatter bf = new BinaryFormatter();
//ms.Position = 0;
return bf.Deserialize(ms,null);
}
catch
{
return null;
}
}
SerializationException: "End of Stream encountered before parsing was
completed.".
I've tried it with the ms.Position = 0 line uncommented of course too...
bytes[] is only 8 bytes long, each byte isn't null.
Suggestions?
[edit]
The byte[] was written to a binary file from a c++ program using something along the lines of
void WriteToFile (std::ostream& file,T* value)
{
file.write(reinterpret_cast<char*>(value), sizeof(*T))
}
Where value may be a number of different types.
I can cast to some objects okay from the file using BitConverter, but anything BitConverter doesn't cover I can't do..
As was stated by cdhowie, you will need to manually deserialize the encoded data. Based on the limited information available, you may either want an array of objects or an object containing an array. It looks like you have a single long but there is no way to know from your code. You will need to recreate your object in its true form so take the below myLong as a simple example for a single long array. Since it was unspecified I'll assume you want a struct containing an array like:
public struct myLong {
public long[] value;
}
You could do the same thing with an array of structs, or classes with minor changes to the code posted below.
Your method will be something like this: (written in the editor)
private myLong byteArrayToObject(byte[] bytes) {
try
{
int len = sizeof(long);
myLong data = new myLong();
data.value = new long[bytes.Length / len];
int byteindex = 0;
for (int i = 0; i < data.value.Length; i++) {
data.value[i] = BitConverter.ToInt64(bytes,byteindex);
byteindex += len;
}
return data;
}
catch
{
return null;
}
}

object returned from webservice call gets mangle with additional bytes in my conversion function

Concise...object returned from webservice call gets mangle with additional bytes in my conversion function.
Basically I have a webreference that I send an XDocument to
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] baXml = encoding.GetBytes(xdoc.ToString());
object o = MEF_Test.NewSubmission("*********", "*********", baXml);
The transmission is successful and I get back what I assume is the xml document and I am trying to go back to an XDocument. I convert my object to a byte array
Byte[] baResponse = ObjectToByteArray(o);
I put this function in at the bottom but it may be where there error is at
The object I get back is 10492 characters but gets bigger by 28 bytes to the size of 10520 after conversion
string ss = Encoding.UTF8.GetString(baResponse);
string ss1 = ss.Substring(28);
XDocument xSubmissionResponse = XDocument.Parse(ss1);
In the screenshot you can see the extra characters and I attempt to get past them by getting the substring past them. The string then looks good but then throws an exception about a hexadecimal value 0x0B further ahead in the string.
Can anyone give this a look? Thanks.
--Screenshot with as much info as possible
I don't have the reputation to stick the image in I hope the link works.
private static byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
o is already an array of bytes (as seen in the debugger). Deserializing it again makes no sense. Just cast object o to byte[] and then run the Encoding.GetString method on it.

Categories

Resources