Windows form c#, encryption and adding additional character - c#

How do I encrypt passwords in such a way that it not only changes the characters of the password but also add extra characters. For example a password as "ABC" would become "12345" instead of "123". Another way is that for each character, the key shift is different. Below are my codes.
class CipherMachine
{
static private List<char> Charset =
new List<char>("PQOWIEURYTLAKSJDHFGMZNXBCV"
+ "olpikmujnyhbtgvrfcedxwszaq"
+ "1597362480"
+ "~!##$%^&*()_+"
+ "PQOWIEURYTLAKSJDHFGMZNXBCV"
+ "olpikmujnyhbtgvrfcedxwszaq"
+ "1597362480"
+ "~!##$%^&*()_+");
static private int Key = 39;
//static private int Length = 0;
static public string Encrypt(string plain)
{
string cipher = "";
foreach (char i in plain)
{
cipher += Charset.ElementAt(Charset.IndexOf(i) + Key);
//cipher += Charset.ElementAt(Charset.IndexOf(i) + Length);
}
return cipher;
}
static public string Decrypt(string cipher)
{
string plain = "";
foreach (char i in cipher)
{
plain += Charset.ElementAt(Charset.LastIndexOf(i) - Key);
//plain += Charset.ElementAt(Charset.LastIndexOf(i) - Length);
}
return plain;
}
}
}
Lines that are commented out are what I thought I could do but it turned out wrong.

You have made the string double length so that the + Key and - Key works, but you ought to have one string of all characters and then WRAP the index (so that if the index goes beyond the length of the string, it wraps back to the beginning). You can achieve this with the % modulus operator:
static private List<char> Charset =
new List<char>("PQOWIEURYTLAKSJDHFGMZNXBCV"
+ "olpikmujnyhbtgvrfcedxwszaq"
+ "1597362480"
+ "~!##$%^&*()_+");
int length = Charset.Count();
// to encrypt
int key = 24;
char unencryptedChar = 'P';
int unencryptedIndex = Charset.IndexOf(unencryptedChar);
int encryptedIndex = (unencryptedIndex + key) % length;
char encryptedChar = Charset.ElementAt(encryptedIndex);
// to unencrypt
int encryptedIndex = Charset.IndexOf(encryptedChar);
int unencryptedIndex = (encryptedIndex - key + length) % length;
char unencryptedChar = Charset.ElementAt(unencryptedIndex);
When you subtract the key in the second part, the index goes negative, and modulus won't work properly on a negative, so we add the length (though this only works if the key is smaller than the length).

Related

XOR String Decryption give me as output below 0 Error. How can I bypass it?

I am currently trying to encrypt strings that can be decrypted. Since I am just starting with this topic I have a problem which arises from the calculation of the XOR and I would like to know if there is a way around this or if there is another type of encryption where this does not occur.
My problem is that I want to encrypt a string that is 30 characters long but the password is only 15 characters. Since you can't divide below 0 to decrypt the string there is no way to undo it.
Is there another type of encryption and decryption that does not have this problem?
Or can you trick the XOR so that it works anyway?
Would be nice if someone could help me :)
My Code:
To Encrypt String:
public static string XOREncrypt(string text, string password)
{
string strKey = password;
string strIn = text;
string sbOut = String.Empty;
for (int i = 0; i < strIn.Length; i++)
{
sbOut += String.Format("{0:00}", strIn[i] ^ strKey[i % strKey.Length]);
}
return sbOut;
}
To Decrypt
public static string XORDecrypt(string text, string password)
{
string strKey = password;
string strIn = text;
string sbOut = String.Empty;
for (int i = 0; i < strIn.Length; i += 2)
{
byte code = Convert.ToByte(strIn.Substring(i, 2));
sbOut += (char)(code ^ strKey[(i / 2) % strKey.Length]);
}
return sbOut;
}
You should convert your strings to bytes first and do the XOR on the individual bytes.
byte[] bytes = Encoding.UFT8.GetBytes(text);
And to convert back again
string text = Encoding.UTF8.GetString(bytes);

Include all printable characters in caesar cipher (ascii 32-126)

I'm looking to make a caesar cipher that includes common ASCII printable characters (character code 32-126).
My current code:
private static char Cipher(char ch, int key)
{
if (!char.IsLetter(ch))
return ch;
char offset = char.IsUpper(ch) ? 'A' : 'a';
return (char)((((ch + key) - offset) % 26) + offset);
}
public static string Encipher(string input, int key)
{
string output = string.Empty;
foreach (char ch in input)
output += Cipher(ch, key);
return output;
}
public static string Decipher(string input, int key) {return Encipher(input, 26 - key);}
(source: https://www.programmingalgorithms.com/algorithm/caesar-cipher/)
I assume I need to at least change
if (!char.IsLetter(ch)) *and* return Encipher(input, 26 - key);
to
if (char.IsControl(ch)) *and* return Encipher(input, 94 - key);
and change the modulo 26 to 94(?) but what else needs to be done? I assume the random number generator (this is for a one time pad implementation) needs to be changed as well, to 0-93 (or maybe 95??). However, testing this gave me errors and didn't make the output the same as the input. Maybe I need to make a isLetter check as well, so the isUpper check doesn't fail for non letters. What else am I missing?
private static char Cipher(char ch, int key)
{
if (char.IsControl(ch))
return ch;
char offset = ' ';
return (char)((((ch + key) - offset) % 95) + offset);
}
public static string Encipher(string input, int key)
{
string output = string.Empty;
foreach (char ch in input)
output += Cipher(ch, key);
return output;
}
public static string Decipher(string input, int key)
{
return Encipher(input, 95 - key);
}

C# Base64 encoding / decoding fails when using custom encrypted password

Im currently writing a program that is encrypting a password (using a custom method), and then encoding the password to Base64 using the To/FromBase64Transform classes. The problem is, when i encode my encrypted password, I am unable to decode it back to its proper encrypted state. The Base64Helper class is just a wrapper for the To/FromBase64Transform classes.
My Test Code:
static void Main(string[] args)
{
bool Worked = false;
string Password = "testing";
Console.WriteLine("Password: " + Password);
// == Encode then decode 64 test. DecPass64 should equal password == //
// Encodes to Base64 using ToBase64Transform
string EncPass64 = Base64Helper.EncodeString(Password);
// Decodes a Base64 string using FromBase64Transform
string DecPass64 = Base64Helper.DecodeString(EncPass64);
// Test if base 64 ecoding / decoding works
Worked = (Password == DecPass64);
Console.WriteLine();
Console.WriteLine("Base64 Pass Encoded: " + EncPass64);
Console.WriteLine("Base64 Pass Decoded: " + DecPass64);
Console.WriteLine("Base64 Encode to Base64 Decode Worked? : " + Worked); // True
// gspassenc uses XOR to switch passwords back and forth between encrypted and decrypted
string GsEncodedPass = gspassenc(Password);
string GsDecodedPass = gspassenc(GsEncodedPass);
Worked = (Password == GsDecodedPass);
// GsDecodedPass should equal the original Password
Console.WriteLine();
Console.WriteLine("GsPass Encoded: " + GsEncodedPass);
Console.WriteLine("GsPass Decoded: " + GsDecodedPass);
Console.WriteLine("GsEncode to GsDecode Worked? : " + Worked); // True
// Bas64 encode the encrypted password. Then decode the base64. B64_GsDecodedPass should equal
// the GsEncoded Password... But it doesn't for some reason!
string B64_GsEncodedPass = Base64Helper.EncodeString(GsEncodedPass);
string B64_GsDecodedPass = Base64Helper.DecodeString(B64_GsEncodedPass);
Worked = (B64_GsDecodedPass == GsEncodedPass);
// Print results
Console.WriteLine();
Console.WriteLine("Base64 Encoded GsPass: " + B64_GsEncodedPass);
Console.WriteLine("Base64 Decoded GsPass: " + B64_GsDecodedPass);
Console.WriteLine("Decoded == GS Encoded Pass? : " + Worked); // False
// Stop console from closing till we say so
Console.Read();
}
private static int gslame(int num)
{
int c = (num >> 16) & 0xffff;
int a = num & 0xffff;
c *= 0x41a7;
a *= 0x41a7;
a += ((c & 0x7fff) << 16);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
a += (c >> 15);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
return a;
}
private static string gspassenc(string pass)
{
int a = 0;
int num = 0x79707367; // gspy
int len = pass.Length;
char[] newPass = new char[len];
for (int i = 0; i < len; ++i)
{
num = gslame(num);
a = num % 0xFF;
newPass[i] = (char)(pass[i] ^ a);
}
return new String(newPass);
}
And the result is:
Any help will be much appreciated!
UPDATE: Here is my Base64Helper Class:
class Base64Helper
{
public static string DecodeString(string encoded)
{
return Encoding.ASCII.GetString(Convert.FromBase64String(encoded));
}
public static string EncodeString(string decoded)
{
return Convert.ToBase64String(Encoding.ASCII.GetBytes(decoded));
}
}
It's because of the way you are interfering with the Unicode "Chars" of the string with the encoding algorithm and then constructing a String using those "Chars" which then might not form a valid Unicode stream.
When converting from your String to a Byte array and back again, you need to decide which encoding to use....and you can't arbitrarily change the byte stream (via your encryption routine) and expect it to produce a valid string when being converted back.
I've modified your code to show some string to byte[] conversion steps...you can adjust these depending on your need.
static void Main(string[] args)
{
bool Worked = false;
string Password = "testing";
Console.WriteLine("Password: " + Password);
// == Encode then decode 64 test. DecPass64 should equal password == //
// Encodes to Base64 using ToBase64Transform
string EncPass64 = Base64Helper.EncodeString(Password);
// Decodes a Base64 string using FromBase64Transform
string DecPass64 = Base64Helper.DecodeString(EncPass64);
// Test if base 64 ecoding / decoding works
Worked = (Password == DecPass64);
Console.WriteLine();
Console.WriteLine("Base64 Pass Encoded: " + EncPass64);
Console.WriteLine("Base64 Pass Decoded: " + DecPass64);
Console.WriteLine("Base64 Encode to Base64 Decode Worked? : " + Worked); // True
// gspassenc uses XOR to switch passwords back and forth between encrypted and decrypted
byte [] passwordbytes = Encoding.UTF8.GetBytes(Password);
byte [] bytes_GsEncodedPass = gspassenc(passwordbytes);
string GsEncodedPass = Encoding.UTF8.GetString(bytes_GsEncodedPass);
byte[] bytes_GsDecodedPass = gspassenc(bytes_GsEncodedPass);
string GsDecodedPass = Encoding.UTF8.GetString(bytes_GsDecodedPass);
Worked = (Password == GsDecodedPass);
// GsDecodedPass should equal the original Password
Console.WriteLine();
Console.WriteLine("GsPass Encoded: " + GsEncodedPass);
Console.WriteLine("GsPass Decoded: " + GsDecodedPass);
Console.WriteLine("GsEncode to GsDecode Worked? : " + Worked); // True
// Bas64 encode the encrypted password. Then decode the base64. B64_GsDecodedPass should equal
// the GsEncoded Password... But it doesn't for some reason!
string B64_GsEncodedPass = Convert.ToBase64String(bytes_GsEncodedPass);
byte []bytes_B64_GsDecodedPass = Convert.FromBase64String(B64_GsEncodedPass);
string B64_GsDecodedPass = Encoding.UTF8.GetString(bytes_B64_GsDecodedPass);
Worked = (B64_GsDecodedPass == GsEncodedPass);
// Print results
Console.WriteLine();
Console.WriteLine("Base64 Encoded GsPass: " + B64_GsEncodedPass);
Console.WriteLine("Base64 Decoded GsPass: " + B64_GsDecodedPass);
Console.WriteLine("Decoded == GS Encoded Pass? : " + Worked); // False
// Stop console from closing till we say so
Console.Read();
}
private static int gslame(int num)
{
int c = (num >> 16) & 0xffff;
int a = num & 0xffff;
c *= 0x41a7;
a *= 0x41a7;
a += ((c & 0x7fff) << 16);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
a += (c >> 15);
if (a < 0)
{
a &= 0x7fffffff;
a++;
}
return a;
}
private static byte[] gspassenc(byte [] pass)
{
int a = 0;
int num = 0x79707367; // gspy
int len = pass.Length;
byte[] newPass = new byte[len];
for (int i = 0; i < len; ++i)
{
num = gslame(num);
a = num % 0xFF;
newPass[i] = (byte)(pass[i] ^ a);
}
return newPass;
}
}

PHP Equivalent to C# GetBytesFromUTF8

I am trying to create a php function thats will allow me access to a dotnet single sign on system and I am hung up on finding a php equivalent to GetBytesFromUTF8, I have tried ord and mb_string to no avail. Any ideas for a php equivalent to the C# GetBytesFromUTF8?
//Function to Create the SSO function SSO($key,$uid){ $lenth=32; $aZ09 = array_merge(range('A', 'Z'), range('a', 'z'),range(0, 9)); $randphrase ='';
for($c=0;$c < $lenth;$c++) {
$randphrase .= $aZ09[mt_rand(0,count($aZ09)-1)];
}
//Append key onto phrase end
$randkey=$randphrase.$key;
//Number of Bytes is string (THIS IS THE PROBLEM, ITS JUST ADDING THE STRING LENGTH)
$bytevalue=mb_strlen($randkey, 'latin1');
// SHA512 Hash
//$toencode= utf8_encode($bytevalue);
$output = hash("sha512", $bytevalue);
//base 64 encode the hash
$sso = base64_encode($output);
$length = mb_strlen($sso);
$characters = 2;
$start = $length - $characters;
$last2 = substr($sso , $start ,$characters);
//$startitup = APIClient::Create('http://my.staging.dosespot.com/LoginSingleSignOn.aspx','SingleSignOnCode=$ssocode');
// Yes, Strip the extra ==
if($last2 == "=="){$ssocode = substr($sso,0,-2);}
// No, just pass the value to the next step
else{$ssocode=$sso;}
//Use first 22 charecters of random.
$shortphrase=substr($randphrase,0,22);
//Append uid & key onto shortened phrase end
$uidv=$uid.$shortphrase.$key;
//Number of Bytes is string
$idbytevalue=mb_strlen($uidv, 'latin1');
//$idbytevalue= strBytes(utf8_encode($uidv));
// SHA512 Hash
$idencode= utf8_encode($idbytevalue);
$idoutput = hash("sha512", $idencode);
// Base64 Encode of hash
$idssoe = base64_encode($idoutput);
//Determine if we need to strip the zeros
$idlength = mb_strlen($idssoe);
$idcharacters = 2;
$idstart = $idlength - $idcharacters;
$idlast2 = substr($idssoe , $idstart ,$idcharacters);
if($idlast2 == "=="){$ssouidv = substr($idssoe,0,-2);}
// No, just pass the value to the next step
else{$ssouidv=$idssoe;}
return array($ssocode, $ssouidv);
}
I am trying to replicate this c#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DoseSpot.EncryptionLibrary
{
public class EncodingUtility
{
public enum encodingOptions : int
{
ASCII = 0,
UTF7,
UTF8,
UTF32,
Unicode,
Base64String
}
public static string GetString(byte[] data, encodingOptions eo)
{
switch (eo)
{
case encodingOptions.ASCII:
return ToASCII(data);
case encodingOptions.Unicode:
return ToUnicode(data);
case encodingOptions.Base64String:
return ToBase64String(data);
case encodingOptions.UTF7:
return ToUTF7(data);
case encodingOptions.UTF32:
return ToUTF32(data);
case encodingOptions.UTF8:
default:
return ToUTF8(data);
}
}
public static byte[] GetBytes(string message, encodingOptions eo)
{
switch (eo)
{
case encodingOptions.ASCII:
return FromASCII(message);
case encodingOptions.Unicode:
return FromUnicode(message);
case encodingOptions.Base64String:
return FromBase64String(message);
case encodingOptions.UTF7:
return FromUTF7(message);
case encodingOptions.UTF32:
return FromUTF32(message);
case encodingOptions.UTF8:
default:
return FromUTF8(message);
}
}
protected static string ToBase64String(byte[] data)
{
return Convert.ToBase64String(data);
}
protected static string ToUnicode(byte[] data)
{
return unicode.GetString(data);
}
protected static string ToASCII(byte[] data)
{
return ascii.GetString(data);
}
protected static string ToUTF7(byte[] data)
{
return utf7.GetString(data);
}
protected static string ToUTF8(byte[] data)
{
return utf8.GetString(data);
}
protected static string ToUTF32(byte[] data)
{
return utf32.GetString(data);
}
protected static byte[] FromBase64String(string originalString)
{
return Convert.FromBase64String(originalString);
}
protected static byte[] FromUnicode(string originalString)
{
return unicode.GetBytes(originalString);
}
protected static byte[] FromASCII(string originalString)
{
return ascii.GetBytes(originalString);
}
protected static byte[] FromUTF7(string originalString)
{
return utf7.GetBytes(originalString);
}
protected static byte[] FromUTF8(string originalString)
{
return utf8.GetBytes(originalString);
}
protected static byte[] FromUTF32(string originalString)
{
return utf32.GetBytes(originalString);
}
public static Encoding getEncoding(encodingOptions eo)
{
switch (eo)
{
case encodingOptions.ASCII:
return ascii;
case encodingOptions.UTF7:
return utf7;
case encodingOptions.UTF8:
return utf8;
case encodingOptions.UTF32:
return utf32;
case encodingOptions.Unicode:
default:
return unicode;
}
}
private static ASCIIEncoding ascii = new ASCIIEncoding();
private static UTF8Encoding utf8 = new UTF8Encoding();
private static UTF7Encoding utf7 = new UTF7Encoding();
private static UTF32Encoding utf32 = new UTF32Encoding();
private static UnicodeEncoding unicode = new UnicodeEncoding();
}
}
public static class EncryptionCommon
{
public static int KeyLength = 32;
public static int PhraseLength = 32;
public static string CreatePhrase()
{
return Randomizer.RandomNumberOfLettersAll(PhraseLength);
}
public static string CreateKey()
{
return Randomizer.RandomNumberOfLetters(KeyLength);
}
public static string Encrypt(string Phrase, string MyKey)
{
byte[] data = EncodingUtility.GetBytes(Phrase + MyKey, EncodingUtility.encodingOptions.UTF8);
byte[] result = new SHA512Managed().ComputeHash(data);
string tempString = EncodingUtility.GetString(result, EncodingUtility.encodingOptions.Base64String);
if (tempString.Substring(tempString.Length - 2).ToString().Equals("=="))
tempString = tempString.Substring(0, tempString.Length - 2);
return tempString;
}
public static string EncryptUserId(string Phrase, int UserId, string MyKey)
{
string UserPhrase = UserId.ToString();
if (Phrase.Length > 22)
UserPhrase += Phrase.Substring(0, 22);
else
UserPhrase += Phrase;
return Encrypt(UserPhrase, MyKey);
}
public static bool VerifyKey(string key, string combinedPhraseAndEncryptedString)
{
Dictionary<string, string> myDict = SplitStringIntoPhraseAndHash(combinedPhraseAndEncryptedString);
string phrase = myDict["phrase"];
string providedEncryptedPhrase = myDict["encryptedString"];
string testEncryptedPhrase = Encrypt(phrase, key);
if (providedEncryptedPhrase.Equals(testEncryptedPhrase))
return true;
else
return false;
}
public static Dictionary<string, string> SplitStringIntoPhraseAndHash(string stringToSplit)
{
Dictionary<string, string> myResult = new Dictionary<string, string>();
if (stringToSplit != null && stringToSplit.Trim().Length >= PhraseLength)
{
string phraseFound = stringToSplit.Substring(0, PhraseLength);
string encryptedString = stringToSplit.Substring(PhraseLength);
myResult.Add("phrase", phraseFound);
myResult.Add("encryptedString", encryptedString);
}
return myResult;
}
public static string CreatePhraseEncryptedCombinedString(string phrase, string key)
{
string toReturn = phrase;
toReturn += Encrypt(phrase, key);
return toReturn;
}
}
I am trying to replicate this C# process in PHP to no avail.
HOW TO CREATE THE CORRECT SINGLESIGNONCODE:
1. You have been provided a key (in UTF-8)
2. Create a random phrase 32 characters long in UTF-8
a. Create32CharPhrase
3. Append the key to the phrase
a. Create32CharPhrase + Key
4. Get the value in Bytes from UTF-8 String
a. GetBytesFromUTF8(Create32CharPhrase + Key)
5. Use SHA512 to hash the byte value you just received
SHA512Hash(GetBytesFromUTF8(Create32CharPhrase + Key))
6. Get a Base64String out of the hash that you created
GetBase64String(SHA512Hash(GetBytesFromUTF8(Create32CharPhrase + Key)))
7. If there are two = signs at the end, then remove them.
RemoveExtraEqualsSigns(GetBase64String(SHA512Hash(GetBytesFromUTF8(Create32CharPhrase
+ Key))))
The Second part of the function...
HOW TO CREATE THE CORRECT SINGLESIGNONUSERIDVERIFY:
1. Grab the first 22 characters of the phrase from step 1
2. Append to the UserId string the 22 characters grabbed from step one
3. (UserId) + (first 22 characters of phrase)
4. Append the key to the string created in 2b
(UserId) +(first 22 characters of phrase) + key
5. Get the Byte value of the string
GetBytesFromUTF8((UserId) + (first 22 characters of phrase) + key)
6. Use SHA512 to hash the byte value you just received
SHA512Hash(GetBytesFromUTF8((UserId) + (first 22 characters of phrase) + key))
7. Get a Base64String out of the hash that you created
8. GetBase64String(SHA512Hash(GetBytesFromUTF8((UserId) + (first 22 characters of phrase) +
key)))
9. If there are two = signs at the end, then remove them.
RemoveExtraEqualsSigns(GetBase64String(SHA512Hash(GetBytesFromUTF8((UserId) + (first 22
characters of phrase) + key))))
Taken out of an edit to the original post
PHP SSO for ASP service
function SSO($key,$uid){
$lenth=32;
$aZ09 = array_merge(range('A', 'Z'), range('a', 'z'),range(0, 9));
$randphrase ='';
for($c=0;$c < $lenth;$c++) {
$randphrase .= $aZ09[mt_rand(0,count($aZ09)-1)];
}
//echo "Key: ".$key."<br/>";
//echo "Phrase: ".$randphrase."<br/>";
//Append key onto phrase end
$randkey=$randphrase.$key;
// SHA512 Hash
$toencode= utf8_encode($randkey);
// Pass 3rd, optional parameter as TRUE to output raw binary data
$output = hash("sha512", $toencode, true);
//base 64 encode the hash binary data
$sso = base64_encode($output);
$length = mb_strlen($sso);
$characters = 2;
$start = $length - $characters;
$last2 = substr($sso , $start ,$characters);
// Yes, Strip the extra ==
if($last2 == "==")
{$ssocode = substr($sso,0,-2);}
// No, just pass the value to the next step
else{$ssocode=$sso;}
// Prepend the random phrase to the encrypted code.
$ssocode = $randphrase.$ssocode;
//echo "SSO: ".$ssocode."<br/>";
//Use first 22 charecters of random.
$shortphrase=substr($randphrase,0,22);
//Append uid & key onto shortened phrase end
$uidv=$uid.$shortphrase.$key;
// SHA512 Hash
$idencode= utf8_encode($uidv);
// Pass 3rd, optional parameter as TRUE to output raw binary data
$idoutput = hash("sha512", $idencode, true);
// Base64 Encode of hash binary data
$idssoe = base64_encode($idoutput);
//Determine if we need to strip the zeros
$idlength = mb_strlen($idssoe);
$idcharacters = 2;
$idstart = $idlength - $idcharacters;
$idlast2 = substr($idssoe , $idstart ,$idcharacters);
if($idlast2 == "==")
{$ssouidv = substr($idssoe,0,-2);}
// No, just pass the value to the next step
else{$ssouidv=$idssoe;}
//echo "SSOID: ".$ssouidv;
return array($ssocode, $ssouidv);
}

Writing values to the registry with C#

I'm in the process of creating a C# application which will monitor changes made to the registry and write them back to the registry next time the user logs on.
So far I've got it monitoring changes, reporting them, writing the hive, key and value to a text file. I'm now at the point where I need to take them values out of the file and place them back into the registry. Now I've looked at various tutorials but none have been able to answer the question/problem I have, so for example the registry key I wish to change is:
HKEY_USERS\S-1-5-21-2055990625-1247778217-514451997-41655\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Outlook\0a0d020000000000c000000000000046 the value of 01020402 and the contents contained within that
What I want to be able to do is write back to that and change the value as appropriate. I currently have 3 strings, one contains the key location, one the value and the final is the contents of the value, although I could easily change the string manipulation to get and not get whatever I need or don't need. So if someone could provide me with a way to write to that it would be appreciated.
P.S so you know, that paticular value is a binary value that I converted to string for storage. If you require any further information please let me know.
Any help would be appreciated....thanks
EDIT Code I'm currently using:
public class reg
{
public void write(string key, string valueName, string value)
{
Byte[] byteValue = System.Text.Encoding.UTF8.GetBytes(value);
Registry.SetValue(key, valueName, value, RegistryValueKind.Binary);
}
}
I'm guessing you just need to find the right class to use to write to the registry. Using this class makes it relatively simple. Is this all you're looking for?
string key = #"HKEY_CLASSES_ROOT\.sgdk2";
string valueName = string.Empty; // "(Default)" value
string value = "sgdk2file";
Microsoft.Win32.Registry.SetValue(key,valueName, value,
Microsoft.Win32.RegistryValueKind.String);
To convert a hex string into binary data:
static byte[] HexToBin(string hex)
{
var result = new byte[hex.Length/2];
for (int i = 0; i < hex.Length; i += 2)
{
result[i / 2] = byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
}
return result;
}
If you need to see these bytes as hexadecimal again, you can use code like this:
static string BytesToHex(byte[] bytes)
{
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("x2"));
}
return sb.ToString();
}
As this code demonstrates, the bytes represented as hex 0e, ff and 10 get converted to binary 00001110, 11111111 and 00010000 respectively.
static void Main(string[] args)
{
byte[] bytes = HexToBin("0eff10");
Console.WriteLine(BytesToBinaryString(bytes));
}
static byte[] HexToBin(string hex)
{
var result = new byte[hex.Length / 2];
for (int i = 0; i < hex.Length; i += 2)
{
result[i / 2] = byte.Parse(hex.Substring(i, 2), System.Globalization.NumberStyles.HexNumber);
}
return result;
}
static string BytesToBinaryString(byte[] bytes)
{
var ba = new System.Collections.BitArray(bytes);
System.Text.StringBuilder sb = new StringBuilder();
for (int i = 0; i < ba.Length; i++)
{
int byteStart = (i / 8) * 8;
int bit = 7 - i % 8;
sb.Append(ba[byteStart + bit] ? '1' : '0');
if (i % 8 == 7)
sb.Append(' ');
}
return sb.ToString();
}
So you have a string that you need to convert to binary and write to the registry? Does this work?
string valueString = "this is my test string";
byte[] value = System.Text.Encoding.ASCII.GetBytes(valueString);
Microsoft.Win32.Registry.SetValue(keyName, valueName, valueString, Microsoft.Win32.RegistryValueKind.Binary);

Categories