stringToHex and hexToString C# anf Android Java - c#

here are the whole story:
(1) I have string "123";
(2) Encrypt to "????g*Ox*??D#?\v" using EncryptFromBase64;
(3) Converted to hex string using ConvertStringToHex
Here is the C# code.
public string ConvertStringToHex(string asciiString)
{
string hex = "";
foreach (char c in asciiString)
{
int value = Convert.ToInt32(c);
// Convert the decimal value to a hexadecimal value in string form.
hex += String.Format("{0:X2}", value);
}
return hex;
}
public string ConvertHexToString(string HexValue)
{
string StrValue = "";
while (HexValue.Length > 0)
{
StrValue += System.Convert.ToChar(System.Convert.ToUInt32(HexValue.Substring(0, 2), 16)).ToString();
HexValue = HexValue.Substring(2, HexValue.Length - 2);
}
return StrValue;
}
public string Encrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.ASCII.GetString(newClearData);
}
public string EncryptFromBase64(string encryptedBase64)
{
if (encryptedBase64.Length < 1) return "";
byte[] bytes = Encoding.ASCII.GetBytes(encryptedBase64);
return Encrypt(bytes);
}
(4)The hex string is then transported to Android request command to C# web service and converted back to string. using convertHexToString
(5) Decryt using decryptAsBase64. There is padding exception.
Here is the android code.
public String decryptAsBase64(String clearData) {
if(clearData.length() < 1) return "";
byte[] encryptedData = clearData.getBytes();
byte[] decryptedData = decryptAsBase64(encryptedData);
String str = Base64.encodeBytes(decryptedData);
str = str.replace("+", "%2B");
return str;
}
public byte[] decryptAsBase64(byte[] clearData) {
byte[] decryptedData =decrypt(clearData);
try {
return Base64.decode(decryptedData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return decryptedData;
}
public byte[] decrypt(byte[] clearData) {
byte[] decryptedData;
try {
decryptedData = aesCipher_Decoder.doFinal(clearData);
} catch (IllegalBlockSizeException e) {
Log.e(TAG, "Illegal block size", e);
return null;
} catch (BadPaddingException e) {
Log.e(TAG, "Bad padding", e);
return null;
}
return decryptedData;
}
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
}
return sb.toString();
}
The string converted back "????g*Ox*??D#?" is incorrect.
Anything wrong with my code?

You're grabbing the hex characters in pairs in your convertHexToString() method, but your {0:X} format string doesn't necessarily output 2 hex digits per character. If you want to make sure each character is represented by 2 hex digits, then use this format string instead:
{0:X2}

The problem was resolved. The error is in the encryption and decryption codes. The following code
public string Encrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
return Encoding.ASCII.GetString(newClearData);
}
should be
public string Encrypt(byte[] encryptedData)
{
byte[] newClearData = rijndaelEncryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
// return Encoding.ASCII.GetString(newClearData);
return Convert.ToBase64String(newClearData);
}
In the android decryption code. The code
public String decryptAsBase64(String clearData) {
if(clearData.length() < 1) return "";
byte[] encryptedData = clearData.getBytes();
byte[] decryptedData = decryptAsBase64(encryptedData);
String str = Base64.encodeBytes(decryptedData);
str = str.replace("+", "%2B");
return str;
}
should be
public String decryptAsBase64(String clearData) {
if(clearData.length() < 1) return "";
byte[] encryptedData = null;
try {
encryptedData = Base64.decode(clearData);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] decryptedData = decrypt(encryptedData);
String str = null;
try {
str = new String(decryptedData, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}

Related

Byte [] to int conversion impossible

And the problem I have, when converting Byte[] to String, I tried with the Encoding.UTF8.GetString and the ncoding.Ascii.GetString but nothing changes ???
I always end up with a string that has backslashes in this form
sRecv = "\\0\\0\\0u0001"
I don't understand....
Sender code
public void SendDatas(int progress)
{
byte[] intBytes = BitConverter.GetBytes(progress);
if (BitConverter.IsLittleEndian)
Array.Reverse(intBytes);
byte[] result = intBytes;
try
{
_socketClient.Send(result, SocketFlags.None);
}
catch
{
MessageBox.Show($"Erreur lors de la transmition des données", "Erreur", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
receive code
public int EcouterReseau(Socket socketClient)
{
string sRecv;
try
{
byte[] data = new byte[1024];
int recv = socketClient.Receive(data);
sRecv = Encoding.Unicode.GetString(data, 0, recv);
}
catch
{
sRecv = "0";
}
int returnValue = int.Parse(sRecv.Remove(0, 7));
return returnValue;
}

Cannot convert from 'System.Collections.Generic.IEnumerable<System.Collection.Generic.List<char>> to string[]

I use this code (found here c sharp helper aes encryption) to encrypt a string and the encrypted string I want to save to a file.
#region "Encrypt Strings and Byte[]"
// Note that extension methods must be defined in a non-generic static class.
// Encrypt or decrypt the data in in_bytes[] and return the result.
public static byte[] CryptBytes(string password, byte[] in_bytes, bool encryptAES)
{
// Make an AES service provider.
AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();
// Find a valid key size for this provider.
int key_size_bits = 0;
for (int i = 4096; i > 1; i--)
{
if (aes_provider.ValidKeySize(i))
{
key_size_bits = i;
break;
}
}
Debug.Assert(key_size_bits > 0);
Console.WriteLine("Key size: " + key_size_bits);
// Get the block size for this provider.
int block_size_bits = aes_provider.BlockSize;
// Generate the key and initialization vector.
byte[] key = null;
byte[] iv = null;
byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);
// Make the encryptor or decryptor.
ICryptoTransform crypto_transform;
if (encryptAES)
{
crypto_transform = aes_provider.CreateEncryptor(key, iv);
}
else
{
crypto_transform = aes_provider.CreateDecryptor(key, iv);
}
// Create the output stream.
using (MemoryStream out_stream = new MemoryStream())
{
// Attach a crypto stream to the output stream.
using (CryptoStream crypto_stream = new CryptoStream(out_stream,
crypto_transform, CryptoStreamMode.Write))
{
// Write the bytes into the CryptoStream.
crypto_stream.Write(in_bytes, 0, in_bytes.Length);
try
{
crypto_stream.FlushFinalBlock();
}
catch (CryptographicException)
{
// Ignore this exception. The password is bad.
}
catch
{
// Re-throw this exception.
throw;
}
// return the result.
return out_stream.ToArray();
}
}
}
// String extensions to encrypt and decrypt strings.
public static byte[] EncryptAES(this string the_string, string password)
{
System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding();
byte[] plain_bytes = ascii_encoder.GetBytes(the_string);
return CryptBytes(password, plain_bytes, true);
}
public static string DecryptAES(this byte[] the_bytes, string password)
{
byte[] decrypted_bytes = CryptBytes(password, the_bytes, false);
System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding();
return ascii_encoder.GetString(decrypted_bytes);
}
public static string CryptString(string password, string in_string, bool encrypt)
{
// Make a stream holding the input string.
byte[] in_bytes = Encoding.ASCII.GetBytes(in_string);
using (MemoryStream in_stream = new MemoryStream(in_bytes))
{
// Make an output stream.
using (MemoryStream out_stream = new MemoryStream())
{
// Encrypt.
CryptStream(password, in_stream, out_stream, true);
// Return the result.
out_stream.Seek(0, SeekOrigin.Begin);
using (StreamReader stream_reader = new StreamReader(out_stream))
{
return stream_reader.ReadToEnd();
}
}
}
}
// Convert a byte array into a readable string of hexadecimal values.
public static string ToHex(this byte[] the_bytes)
{
return ToHex(the_bytes, false);
}
public static string ToHex(this byte[] the_bytes, bool add_spaces)
{
string result = "";
string separator = "";
if (add_spaces) separator = " ";
for (int i = 0; i < the_bytes.Length; i++)
{
result += the_bytes[i].ToString("x2") + separator;
}
return result;
}
// Convert a string containing 2-digit hexadecimal values into a byte array.
public static byte[] ToBytes(this string the_string)
{
List<byte> the_bytes = new List<byte>();
the_string = the_string.Replace(" ", "");
for (int i = 0; i < the_string.Length; i += 2)
{
the_bytes.Add(
byte.Parse(the_string.Substring(i, 2),
System.Globalization.NumberStyles.HexNumber));
}
return the_bytes.ToArray();
}
#endregion // Encrypt Strings and Byte[]
With the code above you will get a list byte with this function it wil be converted to a list char
// Return a string that represents the byte array
// as a series of hexadecimal values separated
// by a separator character.
public static string ToHex(this byte[] the_bytes, char separator)
{
return BitConverter.ToString(the_bytes, 0).Replace('-', separator);
}
I get my data from a list of strings encrypt them like this and want to write them to a file
var encryptedLines = (from line in output
select Helper.ToHex(Encryption.EncryptAES(line, symKey),' ').ToList());
but File.WriteAllLines(fileWrite, encryptedLines); always give me the exception form the title or if i write result it of course just writes down System.Collections.Generic.List`1[System.Char] because it doesnt realy convert the datatype to list string
That beeing said I dont understand why I cant just write all lines of chars to a file?
I tried .ToString() or var result = encryptedLines.Select(c => c.ToString()).ToList();
You may either convert your char list to char array or convert the char list to a string using
listOfChars.Aggregate("", (str, x) => str + x);
The second approach is not recommended as it has a quadratic complexity (check the comments on this answer)
UPDATE:
After the comments by Mr. Lee I checked back again and I find this to be way more efficient:
listOfChars.Aggregate(new StringBuilder(""), (str, x) => str.Append(x));

how to encrypt string in asp.net c# [duplicate]

This question already has answers here:
Encrypting & Decrypting a String in C# [duplicate]
(7 answers)
Closed 6 years ago.
public string EncryptPwd(String strString)
{
int intAscii;
string strEncryPwd = "";
for (int intIndex = 0; intIndex < strString.ToString().Length; intIndex++)
{
intAscii = (int)char.Parse(strString.ToString().Substring(intIndex, 1));
intAscii = intAscii + 5;
strEncryPwd += (char)intAscii;
}
return strEncryPwd;
}
This is my code.Please suggest me it is right way or not.
you can use this code:
Encrypt string with password:
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
and Decrypt String with password:
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Bat dau giai ma chuoi
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
catch (Exception) { Results = DataToDecrypt; }
finally
{
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
}
Do you have a way to decrypt that? Here is another answer on SO
private static readonly UTF8Encoding Encoder = new UTF8Encoding();
public static string Encrypt(string unencrypted)
{
if (string.IsNullOrEmpty(unencrypted))
return string.Empty;
try
{
var encryptedBytes = MachineKey.Protect(Encoder.GetBytes(unencrypted));
if (encryptedBytes != null && encryptedBytes.Length > 0)
return HttpServerUtility.UrlTokenEncode(encryptedBytes);
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
public static string Decrypt(string encrypted)
{
if (string.IsNullOrEmpty(encrypted))
return string.Empty;
try
{
var bytes = HttpServerUtility.UrlTokenDecode(encrypted);
if (bytes != null && bytes.Length > 0)
{
var decryptedBytes = MachineKey.Unprotect(bytes);
if(decryptedBytes != null && decryptedBytes.Length > 0)
return Encoder.GetString(decryptedBytes);
}
}
catch (Exception)
{
return string.Empty;
}
return string.Empty;
}
I agree with all the previous answers (especially share pvv) but in case you really did want a Caesar Cipher (Caesar Cipher is a very weak encryption and should not be used in production), and if this is a learning exercise, then here is some code
string strString = "abcdefghijklmnopqrstuvwxyz";
string enc = String.Join("", strString.ToArray().Select(x =>(char)( 'a' + (x-'a'+5)%26)));
Console.WriteLine(enc);
Or using a for loop like you did
string strEncryPwd = "";
for (int index = 0; index < strString.ToString().Length; index++)
{
int plainChar = strString[index];
int encrypted = 'a' + (plainChar - 'a' + 5) % 26;
strEncryPwd += (char)encrypted;
}
Console.WriteLine(strEncryPwd);

Cipher encryption/decryption in windows phone 7

We want to use Cipher encryption/decryption in windows phone 7. We have done for android using java. But when we try to develop in c# we struggling.
Our Java code:
public AES()
{
try
{
Security.addProvider(new BouncyCastleProvider());
cipher = Cipher.getInstance("AES/ECB/PKCS7Padding", "BC");
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public String doDecrypt(String key, String cipherText)
{
try
{
byte[] raw = key.getBytes(Charset.forName("UTF-8"));
SecretKeySpec skey = new SecretKeySpec(raw, "AES");
cipher.init(Cipher.DECRYPT_MODE, skey );
return new String(cipher.doFinal(Base64.decode(cipherText,Base64.DEFAULT)), Charset.forName("UTF-8"));
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
public String doEncrypt(String key, String plainText)
{
try
{
byte[] raw = key.getBytes(Charset.forName("UTF-8"));
SecretKeySpec skey = new SecretKeySpec(raw, "AES");
cipher.init(Cipher.ENCRYPT_MODE, skey );
return Base64.encodeToString(cipher.doFinal(plainText.getBytes(Charset.forName("UTF-8"))),Base64.DEFAULT);
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
}
return null;
}
}
Here we can encrypt and decryption.
Our C# code is:
public static byte[] EncryptWithAES(string dataToEncrypt, String Key)
{
byte[] encryptedData;
byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(Key);
using (AesManaged aesEnc = new AesManaged())
{
aesEnc.Key = keyBytes;
aesEnc.IV = new byte[16];
//Create encryptor for converting
ICryptoTransform encryptor = aesEnc.CreateEncryptor(aesEnc.Key, aesEnc.IV);
using (MemoryStream memStream = new MemoryStream())
{
using (CryptoStream crypStream = new CryptoStream(memStream, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter srmWriter = new StreamWriter(crypStream))
{
srmWriter.Write(dataToEncrypt);
}
encryptedData = memStream.ToArray();
}
}
}
return encryptedData;
}
But here we receive different output.
Java OP:-
OYbW6pI8mgqU5xOcfG8N92e28T9GUObtcea4XWqU0yQyJRULSLV/yjAzDh8gq9Hgj5K5OubZfdm/
/ts66eQMJYH4TBX0/hN5zPwQbdTWmfVU3dDyU2SyQek5zYcWW+OgnppL9jcMcJZg4pv2+q6x8w==
C# OP:-
OYbW6pI8mgqU5xOcfG8N9wXs2/gWMc6dcUSEoLXm3L5v9Ih9eN63xO31mXmEDLprIzusXaOS1rNNtBPi5I8FG3IukVgicagrkLul1vfa142z+XDULJXFmg5rxPa6iJzXqeZ6x3wxbfI3T/ZqGwxqbg==
We can not get the exact encrypted data like java. Please suggest or provide any links for Cipher encryption/decryption in windows phone 7.
It works for me using LINQPad:
Console.Write(String.Join(" ", EncryptWithAES("hello", "AAECAwQFBgcICQoLDA0ODw==")));
yields:
91 209 208 157 151 41 81 76 99 8 248 231 34 62 204 1
Perhaps it's something specific for Window Phone 7 that is causing it not to work?
Key from https://stackoverflow.com/a/2919565/1185053
Finally I got solution from stackoverflow. I found the solution from here.. It is working fine..
The Solution is:-
Crypt Class:-
public class BCEngine
{
private Encoding _encoding;
private IBlockCipher _blockCipher;
private PaddedBufferedBlockCipher _cipher;
private IBlockCipherPadding _padding;
Pkcs7Padding pkcs = new Pkcs7Padding();
public BCEngine(IBlockCipher blockCipher, Encoding encoding)
{
_blockCipher = blockCipher;
_encoding = encoding;
}
public string Encrypt(string plain, string key)
{
byte[] result = BouncyCastleCrypto(true, _encoding.GetBytes(plain), key);
return Convert.ToBase64String(result);
}
public string Decrypt(string cipher, string key)
{
byte[] result = BouncyCastleCrypto(false, Convert.FromBase64String(cipher), key);
return _encoding.GetString(result, 0, result.Length);
}
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, string key)
{
try
{
_cipher = _padding == null ? new PaddedBufferedBlockCipher(_blockCipher) : new PaddedBufferedBlockCipher(_blockCipher, _padding);
byte[] keyByte = _encoding.GetBytes(key);
_cipher.Init(forEncrypt, new KeyParameter(keyByte));
return _cipher.DoFinal(input);
}
catch (Org.BouncyCastle.Crypto.CryptoException ex)
{
throw new CryptoException(ex.Message);
}
}
public string AESEncryption(string plain, string key)
{
return Encrypt(plain, key);
}
public string AESDecryption(string cipher, string key)
{
return Decrypt(cipher, key);
}
public BCEngine()
{
_blockCipher = new AesEngine();
_encoding = Encoding.UTF8;
pkcs = new Pkcs7Padding();
_padding = pkcs;
}
}
Now I can Call from anywhere to encrypt/decrypt the text.
Example:-
public partial class AesExample : PhoneApplicationPage
{
public AesExample()
{
InitializeComponent();
string key = "b09f72a0lkb1lktb";
string plainText = "Text To Encrypt";
BCEngine bcEngine = new BCEngine();
string encryptedString= bcEngine.Encrypt(plainText, key);
Console.WriteLine("\n\nEncrypted String==> " + encryptedString);
BCEngine bcEnginenew = new BCEngine();
string decryptedString = bcEnginenew.Decrypt(encryptedString, key);
Console.WriteLine("\n\nDecrypted String==> " + decryptedString);
}
}

C# SHA-2 (512) Base64 encoded hash

Looking for a way to do the following in C# from a string.
public static String sha512Hex(byte[] data)
Calculates the SHA-512 digest and returns the value as a hex string.
Parameters:
data - Data to digest
Returns:
SHA-512 digest as a hex string
private static string GetSHA512(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);
SHA512Managed hashString = new SHA512Managed();
string encodedData = Convert.ToBase64String(message);
string hex = "";
hashValue = hashString.ComputeHash(UE.GetBytes(encodedData));
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
Would System.Security.Cryptography.SHA512 be what you need?
var alg = SHA512.Create();
alg.ComputeHash(Encoding.UTF8.GetBytes("test"));
BitConverter.ToString(alg.Hash).Dump();
Executed in LINQPad produces:
EE-26-B0-DD-4A-F7-E7-49-AA-1A-8E-E3-C1-0A-E9-92-3F-61-89-80-77-2E-47-3F-88-19-A5-D4-94-0E-0D-B2-7A-C1-85-F8-A0-E1-D5-F8-4F-88-BC-88-7F-D6-7B-14-37-32-C3-04-CC-5F-A9-AD-8E-6F-57-F5-00-28-A8-FF
To create the method from your question:
public static string sha512Hex(byte[] data)
{
using (var alg = SHA512.Create())
{
alg.ComputeHash(data);
return BitConverter.ToString(alg.Hash);
}
}
Got this to work. Taken from here and modified a bit.
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
Better memory management:
public static string SHA512Hash(string value)
{
byte[] encryptedBytes;
using (var hashTool = new SHA512Managed())
{
encryptedBytes = hashTool.ComputeHash(System.Text.Encoding.UTF8.GetBytes(string.Concat(value)));
hashTool.Clear();
}
return Convert.ToBase64String(encryptedBytes);
}

Categories