Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Covert String to Byte[]

Status
Not open for further replies.

Triacona

Technical User
Jun 11, 2009
462
0
0
GB
Dear All,
Please help this is driving me mad!
Thanks in advance :)
Code:
try
            {
                
                var emailAddr = "etpienaar@yahoo.com";
                byte[] emailAddrByteArr = new byte[emailAddr.Length];
                string[] emailAddStArr = new string[]{"e","t","p","i","e","n","a","a","r","@","y","a","h","o","o",".","c","o","m"};
                //string[] emailAddStArr = new string[emailAddr.Length];
                char[] emailCharArr = emailAddr.ToCharArray();
                

                for (int i = 0; i < emailAddr.Length; i++)
                {
                    //Console.WriteLine(emailCharArr[i]);
                    Console.WriteLine(emailAddStArr[i]);
                    emailAddrByteArr[i] =  byte.Parse(emailAddStArr[i]);

                }
I get the following error:
[error]
Input string was not in a correct format.
[/error]
I have also tried the following:
Code:
//emailAddrByteArr = Array.ConvertAll(emailAddStArr, s => Convert.ToByte(s, 8));
                
                //emailAddrByteArr = Encoding.ASCII.GetBytes(emailAddr);
                //Encoding srcEncoding = Encoding.Unicode;
                //Encoding dstEncoding = Encoding.UTF8;
                //emailAddrByteArr = Encoding.Convert(srcEncoding,dstEncoding,emailAddrByteArr);

Please help, thanks.

Thank you,

Kind regards

Triacona
 
Hi Triacona,

I think you are overcomplicating things.
A string already _is_ a character array. No need to define a string array first and then trying to convert to char array.

All you need to do is something along the line of this:
Code:
var emailAddrByteArr = System.Text.Encoding.Unicode.GetBytes(emailAddr);

Best,
MakeItSo

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Thanks MakeItSo.
I will give that a go...

Thank you,

Kind regards

Triacona
 
Hi MakeItSo,

I have tried that and I get the following error :
Error said:
Length of the data to decrypt is invalid.
Basically here is all the code:
It is to encrypt an object
Code:
#region Symemetrically Encrypting Data and Decrypting Data
            //
            #region Encrypt and Decrypt using AesManaged Class
            //
            #region Create an Rfc2898DeriveBytes object passing password and salt into constructor
            //
            var password = "Pa$$w0rd";
            var salt = "S@lt";
            var rfcDevBytes = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));
            //
            #endregion Create an Rfc2898DeriveBytes object passing password and salt into constructor
            //
            #region Create Instance of AesManaged class ( encryption class )
            var aesManAlgorithm = new AesManaged();
            #endregion Create Instance of AesManaged class ( encryption class )
            //
            #region Generate Secret Key and IV from Rfc2898DeriveBytes object using algoirthm's key size
            //
            var rfcDevBytesKey = rfcDevBytes.GetBytes(aesManAlgorithm.KeySize / 8);
            var rfcDevcBytesIv = rfcDevBytes.GetBytes(aesManAlgorithm.BlockSize / 8);
 #endregion Generate Secret Key and IV from Rfc2898DeriveBytes object using algoirthm's key size
            //
            #region Create MemoryStream object ( instance of ) used to buffer encrypted or unencrypted bytes
            //
            MemoryStream memStream = new MemoryStream();
            //
            #endregion Create MemoryStream object ( instance of ) used to buffer encrypted or unencrypted bytes
            //
            #region Create Encryptor and Decryptor objects, accepting the secret key and IV as parameters
            // create encryptor object
            var algorithm = aesManAlgorithm.CreateEncryptor(rfcDevBytesKey, rfcDevcBytesIv);
            algorithm = aesManAlgorithm.CreateDecryptor(rfcDevBytesKey, rfcDevcBytesIv);
            var cryptoStream = new CryptoStream(memStream, algorithm, CryptoStreamMode.Write);
            try
            {
                
                var emailAddr = "etpienaar@yahoo.com";                
                var emailAddrByteArr = Encoding.Unicode.GetBytes(emailAddr);
                var bytesToTransform = emailAddrByteArr;
                cryptoStream.Write(bytesToTransform, 0, bytesToTransform.Length);
                cryptoStream.FlushFinalBlock();
                cryptoStream.Close();
                memStream.Close();

                #endregion Invoke Close Mehtod on CryptoStream and MemoryStream objects

            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }

Thanks for your help [smile]

Thank you,

Kind regards

Triacona
 
I tried it with a smaller string i.e. 8 bit ( chars ?)
etpienaa
and it gives me the following error:
error said:
Padding is invalid and cannot be removed.

Thank you,

Kind regards

Triacona
 
Getting Bytes and encrypting/decrypting are two different things.
The decryption method expects a Base64 string of encrypted data. Base64 strings are always the length of a multiple of 4, with "=" used as padding for the end of the string, if required. This is what your two error messages say: a) not a multiple of 4, b) not padded with "=".
Next error would be "not a valid Base64 string", probably.

For instance, this is how I encrypt a string (wrote this almost four years ago, so could probably be optimized... :p):
Code:
string encText = Encrypt(myText, secret);
With my Encrypt method looking like this (the one that is called directly is the second Encrypt(), the byte[] in pdb is a sample salt):
Code:
private static byte[] Encrypt(byte[] clearText, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;
            CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(clearText, 0, clearText.Length);
            cs.Close();
            byte[] encryptedData = ms.ToArray();
            return encryptedData;
        }

        public static string Encrypt(string clearText, string Password)
        {
            byte[] clearBytes = System.Text.Encoding.Unicode.GetBytes(clearText);
            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd });
            byte[] encryptedData = Encrypt(clearBytes, pdb.GetBytes(32), pdb.GetBytes(16));
            return Convert.ToBase64String(encryptedData);
        }

In the same fashion, I decrypt encrypted strings like this:
Code:
string clearText = Decrypt(base64Text, secret);

Again, calling the second Decrypt() directly:
Code:
private static byte[] Decrypt(byte[] cipherData, byte[] Key, byte[] IV)
        {
            MemoryStream ms = new MemoryStream();
            Rijndael alg = Rijndael.Create();
            alg.Key = Key;
            alg.IV = IV;
            CryptoStream cs = new CryptoStream(ms, alg.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(cipherData, 0, cipherData.Length);
            cs.Close();
            byte[] decryptedData = ms.ToArray();
            return decryptedData;
        }

        public static string Decrypt(string cipherText, string Password)
        {
            try
            {
                int mod4 = cipherText.Length % 4;
                if (mod4 > 0)
                {
                    cipherText += new string('=', 4 - mod4);
                }
                byte[] cipherBytes = Convert.FromBase64String(cipherText);
                PasswordDeriveBytes pdb = new PasswordDeriveBytes(Password, new byte[] { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd });
                byte[] decryptedData = Decrypt(cipherBytes, pdb.GetBytes(32), pdb.GetBytes(16));
                return System.Text.Encoding.Unicode.GetString(decryptedData);
            }
            catch
            {
                return "";
            }
        }

You'll need [highlight #D3D7CF]using System.Security.Cryptography;[/highlight]

Encryption is not trivial but totally worth - if done properly. :)

Best,
MakeItSo

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Thank you so much [bigsmile] for all your effort.
The blasted text book I am trying to teach myself out of is really bad, with a load of mistakes ( MS Cert 20483, 2013 version ).
I will try this out with the information you have provided.
Thanks again.

Thank you,

Kind regards

Triacona
 
Alrighty.
The accepted answer from here (currently 511 votes) is a very good example, also with a link to a sample solution etc.:
That being said, my above code snippet should already get you started.

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Did you get it to work?

"Knowledge is power. Information is liberating. Education is the premise of progress, in every society, in every family." (Kofi Annan)
Oppose SOPA, PIPA, ACTA; measures to curb freedom of information under whatever name whatsoever.
 
Thanks for all your help [2thumbsup]
Not yet, I have been really busy at work.
I will give it a go over the next few days
Thanks [smile]

Thank you,

Kind regards

Triacona
 
MakeItSo, I fixed it [smile]
See below:
Code:
#region Symemetrically Encrypting Data and Decrypting Data
             //
             #region Encrypt and Decrypt using AesManaged Class
             //
             #region Create an Rfc2898DeriveBytes object passing password and salt into constructor
             //
             string password = "Pa$$w0rd";
             //byte[] salt = "S@lt";//new byte[] { 'S', '@', 'l', 't', '1', '0', '7', '8' }; // this is where it has gone wrong convert to byte array
             var salt = "S@lt";
             var rfcDerBytes = new Rfc2898DeriveBytes(password, Encoding.Unicode.GetBytes(salt));  //Encoding.UTF8.GetBytes(salt));//Encoding.Unicode.GetBytes(salt)); 
             //
             #endregion Create an Rfc2898DeriveBytes object passing password and salt into constructor
             //
             #region Create Instance of AesManaged class ( encryption class )
             AesManaged aesManAlgorithm = new AesManaged();
             #endregion Create Instance of AesManaged class ( encryption class )
             //
             #region Generate Secret Key and IV from Rfc2898DeriveBytes object using algoirthm's key size
             //
             byte[] rfcDevBytesKey = rfcDerBytes.GetBytes(aesManAlgorithm.KeySize / 8); // aesManAlg.Key check...
             //
             #region foreach to check what's in the key // commented out
             //Console.WriteLine("===================RgbKey====================");
             //foreach (var item in rfcDevBytesKey)
             //{
             //    Console.Write("{0}, ",item); 
             //}
             //Console.WriteLine();           
             #endregion foreach to check what's in the key
             //
             byte[] rfcDevcBytesIv = rfcDerBytes.GetBytes(aesManAlgorithm.BlockSize / 8); // should be byte[] as per demo
             //
             #region foreach to check what's in the IV // commented out
             //Console.WriteLine("===================RgbIV===================="); 
             //foreach (var item in rfcDevcBytesIv)
             //{
             //    Console.Write("{0}, ",item);
             //}
             //Console.WriteLine(); 
             #endregion foreach to check what's in the IV
             //
             #endregion Generate Secret Key and IV from Rfc2898DeriveBytes object using algoirthm's key size
             //
             #region Create MemoryStream object ( instance of ) used to buffer encrypted or unencrypted bytes
             //
             MemoryStream memStream = new MemoryStream();
             //
             #endregion Create MemoryStream object ( instance of ) used to buffer encrypted or unencrypted bytes
             //
             #region Create Encryptor and Decryptor objects, accepting the secret key and IV as parameters
             // create encryptor object
             // var algorithmEncrypt = aesManAlgorithm.CreateEncryptor(rgbKey, rgbIv);
             ICryptoTransform transformer = aesManAlgorithm.CreateEncryptor(rfcDevBytesKey, rfcDevcBytesIv);
             //
             #region Create Decryptor when need to decrypt not now book shows 2 different instances
             // create decryptor object
             // var algorithmDecrypt = aesManAlgorithm.CreateDecryptor(rgbKey, rgbIv);
             // algorithm = aesManAlgorithm.CreateDecryptor(rfcDevBytesKey, rfcDevcBytesIv); 
             #endregion
             //
             #endregion Create Encryptor and Decryptor objects, accepting the secret key and IV as parameters
             //
             #region Create CryptoStream object ( instance ) passing bufferStream object, algorithm object and stream mode as parameters
             //
             var cryptoStream = new CryptoStream(memStream, transformer, CryptoStreamMode.Write);
             //
             #endregion Create CryptoStream object ( instance ) passing bufferStream object, algorithm object and stream mode as parameters
             //
             #region Invoke Write and FlushFinalBlock methods on CryptoStream object
             //
             try
             {

                 var emailAddr = "etpienaa";
                 var emailAddrByteArr = Encoding.UTF8.GetBytes(emailAddr);//Encoding.Unicode.GetBytes(emailAddr);

                 #region Attempts at trying to convert to byte array commented out
                 //byte[] emailAddrByteArr = new byte[emailAddr.Length];
                 //string[] emailAddStArr = new string[]{"e","t","p","i","e","n","a","a","r","@","y","a","h","o","o",".","c","o","m"};
                 //string[] emailAddStArr = new string[emailAddr.Length];
                 //char[] emailCharArr = emailAddr.ToCharArray();

                 //for (int i = 0; i < emailAddr.Length; i++)
                 //{
                 //    //Console.WriteLine(emailCharArr[i]);
                 //    Console.WriteLine(emailAddStArr[i]);
                 //    emailAddrByteArr[i] =  byte.Parse(emailAddStArr[i]);

                 //}

                 //Encoding.Unicode.GetBytes()
                 //emailAddrByteArr = Array.ConvertAll(emailAddStArr, s => Convert.ToByte(s, 8));

                 //emailAddrByteArr = Encoding.ASCII.GetBytes(emailAddr);
                 //Encoding srcEncoding = Encoding.Unicode;
                 //Encoding dstEncoding = Encoding.UTF8;
                 //emailAddrByteArr = Encoding.Convert(srcEncoding,dstEncoding,emailAddrByteArr); 
                 #endregion Attempts at trying to convert to byte array

                 #region Other attempts to provide a correct result commented out
                 //emailAddrByteArr = emailAddStArr.Select(s => byte.Parse(s)).ToArray();
                 //emailAddrByteArr = emailAddStArr.Select(s => Byte.Parse(s)).ToArray();
                 //emailAddrByteArr = Array.ConvertAll(emailAddStArr, s => Byte.Parse(s, NumberStyles.HexNumber));


                 //for (int j = 0; j < emailAddr.Length; j++)
                 //{
                 //    emailAddrByteArr[j] = Convert.ToByte(emailAddStArr[j],2);
                 //}

                 //for (int i = 0; i < emailAddr.Length; i++)
                 //{
                 //    emailAddStArr[i] = emailAddr[i].ToString();
                 //}

                 //for (int k = 0; k < emailCharArr.Length; k++)
                 //{
                 //    emailAddStArr[k] = emailCharArr[k].ToString();
                 //}

                 //for (int m = 0; m < emailAddStArr.Length; m++)
                 //{
                 //   // emailAddrByteArr[m] = byte.Parse(emailAddStArr[m].ToString(), NumberStyles.Any); // // doesn't work
                 //    emailAddrByteArr[m] = byte.Parse(emailAddStArr[m], NumberStyles.Any);
                 //    //emailAddrByteArr[m] = emailAddStArr[m];

                 //    //emailAddrByteArr[m] = byte.Parse(emailCharArr[m].ToString(),NumberStyles.HexNumber);
                 //}

                 //int j = 0;
                 //foreach (var item in emailAddStArr)
                 //{
                 //    emailAddrByteArr[j++] = byte.Parse(item);
                 //}

                 //for (int l = 0; l < emailAddStArr.Length; l++)
                 //{
                 //    emailAddrByteArr[l] = byte.Parse(emailAddStArr[l]); 
                 //} // does not work either!!



                 //DeveloperInfo devInfo = new DeveloperInfo(emailAddrByteArr, 1);
                 //foreach (var item in emailAddrByteArr)
                 //{
                 //    Console.WriteLine(item);
                 //}


                 //var bytesToTransform = devInfo.EmailAddress; 
                 #endregion Other attempts to provide a correct result

                 byte[] bytesToTransform = emailAddrByteArr;
                 cryptoStream.Write(bytesToTransform, 0, bytesToTransform.Length);
                 cryptoStream.FlushFinalBlock();
                 byte[] transformedBytes = memStream.ToArray();
                 #region Invoke Close Method on CryptoStream and MemoryStream objects
                 
                 cryptoStream.Close();
                 memStream.Close();

                 for (int i = 0; i < transformedBytes.Length; i++)
                 {
                     Console.WriteLine(transformedBytes[i]);
                 }
                 
                 
                 #endregion Invoke Close Method on CryptoStream and MemoryStream objects




             }
             catch (Exception ex)
             {

                 Console.WriteLine(ex.Message);
             }

Thanks for all your help [thumbsup]

Thank you,

Kind regards

Triacona
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top