convert integer into encrypted string and vice versa - c#

I want to pass pid as querystring parameter in URL, but instead of int like ?pid=102 or ?pid=493 , I want to pass these pid in encrypted form like ?pid=D109150A13F0EA4 or other encrypted string. I tried build-in Encrypt method but they give long length string like
?pid=F3D165BAF8D84FB17CF8E5B4A04AC9022BFF5F987A6EDC42D109150A13F0EA4D847527287C8013154E2E8A2D8DAB6B686751C079092713C0DDA3E2E932D5892361E1B486FE2F46C2E288EA54F64B8B4C
I want small alpha numeric string like ?pid=D109150A13F0EA4 or similar

Have you tried using Guid?
var g = Guid.NewGuid(productId.ToString());
It will produce a result of 38 characters: 8 hexadecimal digits, followed by three groups of 4 hexadecimal digits each, followed by one group of 12 hexadecimal digits.
An example of a Guid: 6B29FC40-CA47-1067-B31D-00DD010662DA
So it is in fact quite short in comparison with your example. The only drawback of the Guid is that you cannot decrypt it back to int (but you can compare whether two Guids represent the same int value).
In case you need both encryption and decryption, apart from the inbuilt encrypting (I assume you have used the Encrypt method in your above example), there are many additional encryption algorithms available in System.Security.Cryptography namespace, like:
DES , example: 2120357ccd3e0142
Aes , example: 73054ef012f6ea6d47757a37a84381f7
HMACSHA256, example: 6723ace2ec7b0348e1270ccbaab802bfa5c1bbdddd108aece88c739051a8a767

For those things I use a small EncryptDecrypt Class, maybe this help for your approach.
Simle usage like EncryptDecrypt.ToEncrypt(yourstring) and EncryptDecrypt.ToDecrypt(yourEncryptedString). So you should be able to encrypt before add to your querystring. Integer and numbers, etc. you have to convert to string first then.
Hope this helps.
using System;
using System.Security.Cryptography;
using System.IO;
namespace YourNameSpace
{
public class EncryptDecrypt
{
#region Declaration
static readonly byte[] TripleDesKey1 = new byte[] { 15, 11, 7, 21, 34, 32, 33, 5, 23, 13, 23, 41, 43, 41, 7, 19, 91, 91, 47, 7, 37, 13, 19, 41 };
static readonly byte[] TripleDesiv1 = new byte[] { 5, 23, 13, 23, 41, 43, 41, 7 };
#endregion
/// <summary>
/// To Encrypt String
/// </summary>
/// <param name="value">String To Encrypt</param>
/// <returns>Returns Encrypted String</returns>
public static string ToEncrypt(string value)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
{
Key = TripleDesKey1,
IV = TripleDesiv1
};
MemoryStream ms;
if (value.Length >= 1)
ms = new MemoryStream(((value.Length * 2) - 1));
else
ms = new MemoryStream();
ms.Position = 0;
CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(value);
encStream.Write(plainBytes, 0, plainBytes.Length);
encStream.FlushFinalBlock();
encStream.Close();
return Convert.ToBase64String(plainBytes);
}
/// <summary>
/// To Decrypt Data Encrypted From TripleDEC Algoritham
/// </summary>
/// <param name="value">String Value To Decrypt</param>
/// <returns>Return Decrypted Data</returns>
public static string ToDecrypt(string value)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
//System.IO.MemoryStream ms = new System.IO.MemoryStream(((value.Length * 2) - 1));
MemoryStream ms;
if (value.Length >= 1)
ms = new MemoryStream(((value.Length * 2) - 1));
else
ms = new MemoryStream();
ms.Position = 0;
CryptoStream encStream = new CryptoStream(ms, des.CreateDecryptor(TripleDesKey1, TripleDesiv1), CryptoStreamMode.Write);
byte[] plainBytes = Convert.FromBase64String(value);
encStream.Write(plainBytes, 0, plainBytes.Length);
return System.Text.Encoding.UTF8.GetString(plainBytes);
}
}
}

This method is used to generate a random string
private string GetRandomString(int iStringLength)
{
string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!#$?_-";
char[] chars = new char[iStringLength];
Random rd = new Random();
for (int i = 0; i < iStringLength; i++)
{
chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
}
return new string(chars);
}
or use
var gid = Guid.NewGuid(productId.ToString());
Below method encrypts a string. just pass a normal/ random string to encrypt the string.
protected string EncryptString(String strString)
{
UnicodeEncoding uEncode = new UnicodeEncoding();
Byte[] bytstrString = uEncode.GetBytes(strString);
SHA256Managed sha1 = new SHA256Managed();
Byte[] hash = sha1.ComputeHash(bytstrString);
return Convert.ToBase64String(hash);
}

Related

C# AES CFB compatibility with 3rd party C implementation

I have a 3rd party AES library for C (from Lantronix). I wrapped their API from within C#'s managed code as shown below, and it works:
[DllImport("cbx_enc.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
static extern unsafe void VC_blockEncrypt(char* iv, char* key, int length, char* text, int RDkeyLen);
/// <summary>
/// Managed Encrypt Wrapper
/// </summary>
/// <param name="buffer">provides the plain text and receives the same length cipher text</param>
static readonly string key = "abcdef0123456789";
static readonly string iv = "0123456789ABCDEF";
public static void Encrypt(ref byte[] buffer)
{
var keyPtr = Marshal.StringToHGlobalAnsi(key);
var ivPtr = Marshal.StringToHGlobalAnsi(iv);
byte[] temp = new byte[16];
Marshal.Copy(ivPtr, temp, 0, 16);
int index = 0;
for (int i = 0; i < buffer.Length; i++)
{
if (index == 0)
{
Marshal.Copy(temp, 0, ivPtr, 16);
unsafe
{
VC_blockEncrypt((char*) ivPtr, (char*) keyPtr, 0, (char*) ivPtr, 128);
}
Marshal.Copy(ivPtr, temp, 0, 16);
index = 16;
}
temp[16 - index] ^= buffer[i];
buffer[i] = temp[16 - index];
index--;
}
Marshal.FreeHGlobal(ivPtr);
Marshal.FreeHGlobal(keyPtr);
}
Now, when I wrote my own, using System.Security.Cryptography to completely avoid using their unmanaged DLL, my final ciphertext seems to differ from them! I am using the same mode, same key, same iv and same plain text, yet the algorithms are not compatible. Shown below is the property settings for the RijndaelManaged object and the code; am I missing something that causes this incompatibility?
/// <summary>
/// Managed Encrypt
/// </summary>
/// <param name="buffer">provides the plain text and receives the same length cipher text</param>
static readonly string key = "abcdef0123456789";
static readonly string iv = "0123456789ABCDEF";
public static void Encrypt(ref byte[] buffer)
{
using (RijndaelManaged cipher = new RijndaelManaged())
{
cipher.Mode = CipherMode.CFB;
cipher.Key = Encoding.ASCII.GetBytes(key);
cipher.IV = Encoding.ASCII.GetBytes(iv);
cipher.Padding = PaddingMode.None;
cipher.FeedbackSize = 128;
ICryptoTransform encryptor = cipher.CreateEncryptor(cipher.Key, cipher.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (BinaryWriter swEncrypt = new BinaryWriter(csEncrypt))
{
swEncrypt.Write(buffer);
}
buffer = msEncrypt.ToArray();
}
}
}
}
Alternatively, the algorithm that I elucidated from Lantronix architecture looks very straightforward - the API does the encryption, and XORing the output with the plain text is done in the calling-method. Whereas, with .NET library, I don't have such access to the intermediate encrypted output (or is there one?), so that I could XOR the way Lantronix does manually after the encryption...
The end goal is to stop using the unmanaged code, yet should be able to generate the same ciphertext using fully managed .NET code.
Thanks for your help in advance.
p.s. I can provide the 3rd party C library cbx_enc.dll, if you need.
Edit: #Topaco, here are some sample data as requested. Haven’t heard from the vendor as with distributing their DLL; working on it…
Common inputs to CFB:
byte[] buffer = Encoding.ASCII.GetBytes("AAAAAAAAAAAAAABBBBBBBBBBBBBBBBBD"); //plain text
string key = "abcdef0123456789";
string iv = "0123456789ABCDEF";
I/O from the wrapper to the unmanaged DLL:
PlainText Hex: 4141414141414141414141414141424242424242424242424242424242424244
CipherText Hex: C9094F820428E07AE035B6749E18546C62F9D5FD4A78480215DA3625D376A271
I/O from the managed code with FeedbackSize = 128; //CFB128:
PlainText Hex: 4141414141414141414141414141424242424242424242424242424242424244
CipherText Hex: 6A1A5088ACDA505B47192093DD06CD987868BFD85278A4D7D3120CC85FCD3D83
I/O from the managed code with FeedbackSize = 8 //CFB8:
PlainText Hex: 4141414141414141414141414141424242424242424242424242424242424244
CipherText Hex: 6ACA3B1159D38568504248CDFF159C87BB2D3850EDAEAD89493BD91087ED7507
I also did the additional test using ECB to see whether their API behaves like ECB (hence comes the need for external XORing). So, I passed the IV to my ECB code as plain text as shown below, and compared it with their output right before the first XOR – they both don’t match either!
Passed IV as the PlainText to ECB : 30313233343536373839414243444546
CipherText Hex: 2B5B11C9ED9B111A065861D29C478FDA
CipherText Hex from the unmanaged DLL, before the first XOR: 88480EC34569A13BA174F735DF59162E
And finally, here is my ECB implementation for the above test:
static readonly string key = "abcdef0123456789";
static readonly string iv = "0123456789ABCDEF";
public static void Encrypt(ref byte[] buffer)
{
buffer = Encoding.ASCII.GetBytes(iv);
Console.WriteLine($"PlainText: {HexHelper.ToHexString(buffer)}");
var aes = new AesManaged
{
KeySize = 128,
Key = Encoding.ASCII.GetBytes(key),
BlockSize = 128,
Mode = CipherMode.ECB,
Padding = PaddingMode.None,
IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
buffer = encryptor.TransformFinalBlock(buffer, 0, buffer.Length);
Console.WriteLine($"CipherText: {HexHelper.ToHexString(buffer)}");
}
Thanks.
Like to express my thanks all for the help, especially to #Topaco many thanks – your insight in encoding the plain text in HEX as according to the docs helped!
Here is the revised wrapper code; as you can see its cipher now matches the managed code’s cipher! Perfect!!
static readonly string key = "61626364656630313233343536373839"; //"abcdef0123456789";
static readonly string iv = "0123456789ABCDEF";
public static void Encrypt(ref byte[] buffer)
{
Console.WriteLine($"PlainText: {HexHelper.ToHexString(buffer)}");
var keyPtr = Marshal.StringToHGlobalAnsi(key);
var ivPtr = Marshal.StringToHGlobalAnsi(iv);
byte[] temp = new byte[16];
Marshal.Copy(ivPtr, temp, 0, 16);
int index = 0;
for (int i = 0; i < buffer.Length; i++)
{
if (index == 0)
{
Marshal.Copy(temp, 0, ivPtr, 16);
unsafe
{
VC_blockEncrypt((char*) ivPtr, (char*) keyPtr, 0, (char*) ivPtr, 128);
}
Marshal.Copy(ivPtr, temp, 0, 16);
index = 16;
Console.WriteLine($"CipherText BeforeXOR: {HexHelper.ToHexString(temp)}");
}
temp[16 - index] ^= buffer[i];
buffer[i] = temp[16 - index];
index--;
}
Marshal.FreeHGlobal(ivPtr);
Marshal.FreeHGlobal(keyPtr);
Console.WriteLine($"CipherText: {HexHelper.ToHexString(buffer)}");
}
I/O from the revised wrapper code:
PlainText: 4141414141414141414141414141424242424242424242424242424242424244
CipherText: 6A1A5088ACDA505B47192093DD06CD987868BFD85278A4D7D3120CC85FCD3D83
I/O from the managed code:
PlainText: 4141414141414141414141414141424242424242424242424242424242424244
CipherText: 6A1A5088ACDA505B47192093DD06CD987868BFD85278A4D7D3120CC85FCD3D83
Cheers!!

Unexpected encrypted string with AES 256 bit ECB in C#

I am trying to encode a string with AES 256 ECB and padding of zeros with the .Net's System.Security.Cryptography library but the result is not what I expected.
I am testing using this test case that matchs my reciver's code.
My code looks like this:
public static class Util
{
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
private static readonly byte[] KEY = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
private static readonly byte[] IV = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
public static byte[] Encrypt(string original)
{
byte[] encrypted;
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Padding = PaddingMode.Zeros;
aesAlg.Mode = CipherMode.ECB;
aesAlg.KeySize = 256;
// Create the streams used for encryption.
using (ICryptoTransform encryptor = aesAlg.CreateEncryptor(KEY, IV))
using (MemoryStream msEncrypt = new MemoryStream())
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
var bytes = Encoding.ASCII.GetBytes(original);
swEncrypt.Write(bytes);
}
encrypted = msEncrypt.ToArray();
}
}
return encrypted;
}
}
Then, this is my test case is failling, the result array in hexadecimal is 05212CB5430653FA4BD2253D20353903 not 9798D10A63E4E167122C4C07AF49C3A9.
public void TesEncrypt()
{
var array = Util.Encrypt("text to encrypt");
var expected = Util.StringToByteArray("9798D10A63E4E167122C4C07AF49C3A9");
CollectionAssert.AreEqual(expected, array);
}
This:
//Write all data to the stream.
var bytes = Encoding.ASCII.GetBytes(original);
swEncrypt.Write(bytes);
should be
//Write all data to the stream.
swEncrypt.Write(original);
The StreamWriter already takes care of serializing your string to a byte array.
Here's a working fiddle. (I don't have Assert.AreEqual available there, but the first two bytes match your expected output. Oh, and, by the way, Assert.AreEqual is wrong here, you should use CollectionAssert.AreEqual instead.)
I found this bug by noticing that your original code returned the same output, independent of the input. What happens is that the TextWriter.Write(object) overload is called, which calls ToString on your byte array (yielding the string "System.Byte[]") and encrypts that string (instead of your input string).

Rfc2898DeriveBytes for .NET and Java generate different values

I'm trying to use Rfc2898DeriveBytes for Android Java and .NET C# framework to generate key for encryption and decryption process.
The problem is in spite of that the input values are same, I'm getting different keys in .NET and Java.
.NET code:
private void btnRfc2898DeriveBytes_Click(object sender, EventArgs e)
{
byte[] salt = new byte[] { 19, 3, 24, 18, 14, 42, 57, 23 };
Rfc2898DeriveBytes keyGenerator = null;
keyGenerator = new Rfc2898DeriveBytes("somestring", salt, 1000);
txtRfc2898DeriveBytes.Text = System.Text.Encoding.UTF8.GetString(keyGenerator.GetBytes(16));
}
Java Code (used in an android application):
byte[] salt = new byte[] { 19, 3, 24, 18, 14, 42, 57, 23 };
Rfc2898DeriveBytes keyGenerator = null;
try {
keyGenerator = new Rfc2898DeriveBytes("somestring", salt, 1000);
} catch (InvalidKeyException e1) {
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.i("key = ", decodeUTF8(keyGenerator.getBytes(16)));
Java Decode Method:
String decodeUTF8(byte[] bytes) {
private final Charset UTF8_CHARSET = Charset.forName("UTF-8");
return new String(bytes, UTF8_CHARSET);
}
Rfc2898DeriveBytes java class:
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/**
* RFC 2898 password derivation compatible with .NET Rfc2898DeriveBytes class.
*/
public class Rfc2898DeriveBytes {
private Mac _hmacSha1;
private byte[] _salt;
private int _iterationCount;
private byte[] _buffer = new byte[20];
private int _bufferStartIndex = 0;
private int _bufferEndIndex = 0;
private int _block = 1;
/**
* Creates new instance.
* #param password The password used to derive the key.
* #param salt The key salt used to derive the key.
* #param iterations The number of iterations for the operation.
* #throws NoSuchAlgorithmException HmacSHA1 algorithm cannot be found.
* #throws InvalidKeyException Salt must be 8 bytes or more. -or- Password cannot be null.
*/
public Rfc2898DeriveBytes(byte[] password, byte[] salt, int iterations) throws NoSuchAlgorithmException, InvalidKeyException {
if ((salt == null) || (salt.length < 8)) { throw new InvalidKeyException("Salt must be 8 bytes or more."); }
if (password == null) { throw new InvalidKeyException("Password cannot be null."); }
this._salt = salt;
this._iterationCount = iterations;
this._hmacSha1 = Mac.getInstance("HmacSHA1");
this._hmacSha1.init(new SecretKeySpec(password, "HmacSHA1"));
}
/**
* Creates new instance.
* #param password The password used to derive the key.
* #param salt The key salt used to derive the key.
* #param iterations The number of iterations for the operation.
* #throws NoSuchAlgorithmException HmacSHA1 algorithm cannot be found.
* #throws InvalidKeyException Salt must be 8 bytes or more. -or- Password cannot be null.
* #throws UnsupportedEncodingException UTF-8 encoding is not supported.
*/
public Rfc2898DeriveBytes(String password, byte[] salt, int iterations) throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
this(password.getBytes("UTF8"), salt, iterations);
}
/**
* Creates new instance.
* #param password The password used to derive the key.
* #param salt The key salt used to derive the key.
* #throws NoSuchAlgorithmException HmacSHA1 algorithm cannot be found.
* #throws InvalidKeyException Salt must be 8 bytes or more. -or- Password cannot be null.
* #throws UnsupportedEncodingException UTF-8 encoding is not supported.
*/
public Rfc2898DeriveBytes(String password, byte[] salt) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
this(password, salt, 0x3e8);
}
/**
* Returns a pseudo-random key from a password, salt and iteration count.
* #param count Number of bytes to return.
* #return Byte array.
*/
public byte[] getBytes(int count) {
byte[] result = new byte[count];
int resultOffset = 0;
int bufferCount = this._bufferEndIndex - this._bufferStartIndex;
if (bufferCount > 0) { //if there is some data in buffer
if (count < bufferCount) { //if there is enough data in buffer
System.arraycopy(this._buffer, this._bufferStartIndex, result, 0, count);
this._bufferStartIndex += count;
return result;
}
System.arraycopy(this._buffer, this._bufferStartIndex, result, 0, bufferCount);
this._bufferStartIndex = this._bufferEndIndex = 0;
resultOffset += bufferCount;
}
while (resultOffset < count) {
int needCount = count - resultOffset;
this._buffer = this.func();
if (needCount > 20) { //we one (or more) additional passes
System.arraycopy(this._buffer, 0, result, resultOffset, 20);
resultOffset += 20;
} else {
System.arraycopy(this._buffer, 0, result, resultOffset, needCount);
this._bufferStartIndex = needCount;
this._bufferEndIndex = 20;
return result;
}
}
return result;
}
private byte[] func() {
this._hmacSha1.update(this._salt, 0, this._salt.length);
byte[] tempHash = this._hmacSha1.doFinal(getBytesFromInt(this._block));
this._hmacSha1.reset();
byte[] finalHash = tempHash;
for (int i = 2; i <= this._iterationCount; i++) {
tempHash = this._hmacSha1.doFinal(tempHash);
for (int j = 0; j < 20; j++) {
finalHash[j] = (byte)(finalHash[j] ^ tempHash[j]);
}
}
if (this._block == 2147483647) {
this._block = -2147483648;
} else {
this._block += 1;
}
return finalHash;
}
private static byte[] getBytesFromInt(int i) {
return new byte[] { (byte)(i >>> 24), (byte)(i >>> 16), (byte)(i >>> 8), (byte)i };
}
}
Edit:
I also convert it to Hex, but getting different values also.
C# function:
public static String encode(byte[] data)
{
char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
int i = 0, p = 2, l = data.Length;
char[] c = new char[l * 2 + 2];
byte d; c[0] = '0'; c[1] = 'x';
while (i < l)
{
d = data[i++];
c[p++] = lookup[d / 0x10];
c[p++] = lookup[d % 0x10];
}
return new string(c, 0, c.Length);
}
Java method:
final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
int v;
for ( int j = 0; j < bytes.length; j++ ) {
v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
What I'm doing wrong :( ?
Here:
txtRfc2898DeriveBytes.Text = System.Text.Encoding.UTF8.GetString(
keyGenerator.GetBytes(16));
and here:
decodeUTF8(keyGenerator.getBytes(16)
you are using UTF-8 to decode data into a string that isn't UTF-8. Since that does not have a defined output, it is not unreasonable that the two undefined outputs can be different.
Rather than decoding as UTF-8: if you need it as a string, use base-16 (aka "hex") or base-64 to represent the generated bytes. A text encoding (such as UTF-8) is only well-defined when converting string data (in the range of characters supported by that encoding) to/from binary data in that encoding. It is incorrect to "decode" arbitrary binary via a text encoding.
I re-solved the issue, the following code generate same values for me in .NET and Java.
.NET code:
private void btnKey_Click(object sender, EventArgs e)
{
byte[] salt = new byte[] { 172, 137, 25, 56, 156, 100, 136, 211, 84, 67, 96, 10, 24, 111, 112, 137, 3 };
int iterations = 1024;
var rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes("_sOme*ShaREd*SecreT", salt, iterations);
byte[] key = rfc2898.GetBytes(16);
String keyB64 = Convert.ToBase64String(key);
txtRfc2898DeriveBytes.Text = keyB64;
}
Java code:
String password = "_sOme*ShaREd*SecreT";
byte[] salta = new byte[]{-84, -119, 25, 56, -100, 100, -120, -45, 84, 67, 96, 10, 24, 111, 112, -119, 3};
SecretKeyFactory factory = null;
try {
factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
} catch (NoSuchAlgorithmException e2) {
e2.printStackTrace();
}
KeySpec spec = new PBEKeySpec(password.toCharArray(), salta, 1024, 128);
SecretKey tmp = null;
try {
tmp = factory.generateSecret(spec);
} catch (InvalidKeySpecException e2) {
e2.printStackTrace();
}
SecretKeySpec secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Log.i("The secret Key: " , Base64.encodeToString(secret.getEncoded(), 0 ));

Odd Encryption/Decryption Error (C# - AES)

I found the following AES encryption class from another question here. The class (as is) works great, however, I have been trying to modify the class to my liking which is where I have encountered these errors. Please note that it is a binary file that I am trying to encrypt.
First I will explain the changes I am trying to make.
1) I want to change the parameter of the Encrypt function from a string, to a byte array. I thought this would be very simple task (just do a quick File.ReadAllBytes and pass the byte array to the Encrypt function) but this was not the case.
2) I want the decrypt function to return a byte array. Same issue as above, I can't get this to work properly.
I was hoping that someone would be able to give me a working example of encrypting and decrypting a binary file similar to what I have setup below:
private void button1_Click(object sender, EventArgs e)
{
SimpleAES sa = new SimpleAES();
OpenFileDialog ofd = new OpenFileDialog();
string s = string.Empty;
byte[] b = null;
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
b = File.ReadAllBytes(ofd.FileName);
b = sa.Encrypt(ByteToString(b);
}
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData123.exe", b);
}
private void button2_Click(object sender, EventArgs e)
{
SimpleAES sa = new SimpleAES();
byte[] b = File.ReadAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData123.exe");
string s = sa.Decrypt(b);
File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData123.exe");
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\TestData.exe", b);
}
public byte[] StringToByte(string s)
{
Byte[] b = new byte[s.Length];
for (int i = 0; i < s.Length; i++)
{
char c = Convert.ToChar(s.Substring(i, 1));
b[i] = Convert.ToByte(c);
}
return b;
}
public string ByteToString(byte[] input)
{
StringBuilder ss = new System.Text.StringBuilder();
for (int i = 0; i < input.Length; i++)
{
// Convert each byte to char
char c = Convert.ToChar(input[i]);
ss.Append(Convert.ToString(c));
}
return ss.ToString();
}
Here is the AES class I am using:
using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;
public class SimpleAES
{
// Change these keys
private byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 };
private ICryptoTransform EncryptorTransform, DecryptorTransform;
private System.Text.UTF8Encoding UTFEncoder;
public SimpleAES()
{
//This is our encryption method
RijndaelManaged rm = new RijndaelManaged();
//Create an encryptor and a decryptor using our encryption method, key, and vector.
EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);
//Used to translate bytes to text and vice versa
UTFEncoder = new System.Text.UTF8Encoding();
}
/// -------------- Two Utility Methods (not used but may be useful) -----------
/// Generates an encryption key.
static public byte[] GenerateEncryptionKey()
{
//Generate a Key.
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateKey();
return rm.Key;
}
/// Generates a unique encryption vector
static public byte[] GenerateEncryptionVector()
{
//Generate a Vector
RijndaelManaged rm = new RijndaelManaged();
rm.GenerateIV();
return rm.IV;
}
/// ----------- The commonly used methods ------------------------------
/// Encrypt some text and return a string suitable for passing in a URL.
public string EncryptToString(string TextValue)
{
return ByteArrToString(Encrypt(TextValue));
}
/// Encrypt some text and return an encrypted byte array.
public byte[] Encrypt(string TextValue)
{
//Translates our text value into a byte array.
Byte[] bytes = UTFEncoder.GetBytes(TextValue);
//Used to stream the data in and out of the CryptoStream.
MemoryStream memoryStream = new MemoryStream();
/*
* We will have to write the unencrypted bytes to the stream,
* then read the encrypted result back from the stream.
*/
#region Write the decrypted value to the encryption stream
CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
cs.Write(bytes, 0, bytes.Length);
cs.FlushFinalBlock();
#endregion
#region Read encrypted value back out of the stream
memoryStream.Position = 0;
byte[] encrypted = new byte[memoryStream.Length];
memoryStream.Read(encrypted, 0, encrypted.Length);
#endregion
//Clean up.
cs.Close();
memoryStream.Close();
return encrypted;
}
/// The other side: Decryption methods
public string DecryptString(string EncryptedString)
{
return Decrypt(StrToByteArray(EncryptedString));
}
/// Decryption when working with byte arrays.
public string Decrypt(byte[] EncryptedValue)
{
#region Write the encrypted value to the decryption stream
MemoryStream encryptedStream = new MemoryStream();
CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
decryptStream.FlushFinalBlock();
#endregion
#region Read the decrypted value from the stream.
encryptedStream.Position = 0;
Byte[] decryptedBytes = new Byte[encryptedStream.Length];
encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
encryptedStream.Close();
#endregion
return UTFEncoder.GetString(decryptedBytes);
}
/// Convert a string to a byte array. NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
// System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
// return encoding.GetBytes(str);
// However, this results in character values that cannot be passed in a URL. So, instead, I just
// lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
public byte[] StrToByteArray(string str)
{
if (str.Length == 0)
throw new Exception("Invalid string value in StrToByteArray");
byte val;
byte[] byteArr = new byte[str.Length / 3];
int i = 0;
int j = 0;
do
{
val = byte.Parse(str.Substring(i, 3));
byteArr[j++] = val;
i += 3;
}
while (i < str.Length);
return byteArr;
}
// Same comment as above. Normally the conversion would use an ASCII encoding in the other direction:
// System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
// return enc.GetString(byteArr);
public string ByteArrToString(byte[] byteArr)
{
byte val;
string tempStr = "";
for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
{
val = byteArr[i];
if (val < (byte)10)
tempStr += "00" + val.ToString();
else if (val < (byte)100)
tempStr += "0" + val.ToString();
else
tempStr += val.ToString();
}
return tempStr;
}
}
Thank you very much everyone!
Edited the code you provided to work as per the requirements.
private static byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private static byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 221, 112, 79, 32, 114, 156 };
private static RijndaelManaged _rijndaelManaged;
static void Main(string[] args)
{
var allBytes = File.ReadAllBytes("hello.bin");
_rijndaelManaged = new RijndaelManaged { Key = Key, IV = Vector };
byte[] encBytes = Encrypt(allBytes, Key, Vector);
byte[] decBytes = Decrypt(encBytes, Key, Vector);
using (var mstream = new MemoryStream(decBytes))
using (var breader = new BinaryReader(mstream))
{
Console.WriteLine(breader.ReadString());
}
}
private static byte[] Decrypt(byte[] encBytes, byte[] key, byte[] vector)
{
byte[] decBytes;
using (var mstream = new MemoryStream())
using (var crypto = new CryptoStream(mstream, _rijndaelManaged.CreateDecryptor(key, vector), CryptoStreamMode.Write))
{
crypto.Write(encBytes, 0, encBytes.Length);
crypto.FlushFinalBlock();
mstream.Position = 0;
decBytes = new byte[mstream.Length];
mstream.Read(decBytes, 0, decBytes.Length);
}
return decBytes;
}
private static byte[] Encrypt(byte[] allBytes, byte[] key, byte[] vector)
{
byte[] encBytes;
using (var mstream = new MemoryStream())
using (var crypto = new CryptoStream(mstream, _rijndaelManaged.CreateEncryptor(key, vector), CryptoStreamMode.Write))
{
crypto.Write(allBytes, 0, allBytes.Length);
crypto.FlushFinalBlock();
mstream.Position = 0;
encBytes = new byte[mstream.Length];
mstream.Read(encBytes, 0, encBytes.Length);
}
return encBytes;
}
As Eoin explained, all you had to do was remove the line which converted the bytes back to the string. I posted the entire working code as I was not sure whether the input file being a binary file was causing any issues. It doesnt.
Evan,
I think you might be over complicating things here. And without doing any checking, I think the problem lies with your StringToByte & ByteToString methods. You should really be using one of the System.Text.Encoding classes for string->byte conversion (just like the AES Class does)
But if you only need to encrypt a source byte[] to a destination byte[] you can do the following and forget about strings completely.
Change the SimpleAES Encrypt & Decrypt Signatures as follows
public byte[] Encrypt(Byte[] bytes) //Change To take in a byte[]
{
//Translates our text value into a byte array.
//Byte[] bytes = UTFEncoder.GetBytes(TextValue); <-- REMOVE THIS LINE
... do stuff with `bytes`
}
public byte[] Decrypt(byte[] EncryptedValue) //now returns a byte array instead of a string
{
//return UTFEncoder.GetString(decryptedBytes); <-- JUST RETURN THE BYTE[] INSTEAD
return decryptedBytes;
}
So now you just feed it and input byte [] and receive an encrypted byte [] back.
You can verify this in the debugger using.
SimpleAES sa = new SimpleAES();
byte[] plainBytes = new byte[] { 0x01, 0xFF, 0x53, 0xC2};
byte[] encBytes = sa.Encrypt(plainBytes);
byte[] decBytes = sa.Decrypt(encBytes);
//BREAK HERE
//Compare the values of decBytes & plainBytes

Decrypted text from AES encryption has extra spaces

I'm trying to decrypt passwords that were stored in a database from a standard SqlMembershipProvider. In order to do this, I hacked together following console app:
static void Main(string[] args)
{
const string encryptedPassword = #"wGZmgyql4prPIr7t1uaxa+RBRJC51qOPBO5ZkSskUtUCY1aBpqNifQGknEfWzky4";
const string iv = #"Jc0RhfDog8SKvtF9aI+Zmw==";
var password = Decrypt(encryptedPassword, iv);
Console.WriteLine(password);
Console.ReadKey();
}
public static string Decrypt(string toDecrypt, string iv)
{
var ivBytes = Convert.FromBase64String(iv);
const string decryptKey = "DECRYPTION_KEY_HERE";
var keyArray = StringToByteArray(decryptKey);
var toEncryptArray = Convert.FromBase64String(toDecrypt);
var rDel = new AesCryptoServiceProvider() { Key = keyArray, IV = ivBytes};
var cTransform = rDel.CreateDecryptor();
var resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
return Encoding.UTF8.GetString(resultArray);
}
public static byte[] StringToByteArray(String hex)
{
var numberChars = hex.Length;
var bytes = new byte[numberChars / 2];
for (var i = 0; i < numberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
This does indeed decrypt the text, however instead of the resulting text being something like "Password1", it's "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0P\0a\0s\0s\0w\0o\0r\0d\01\0" which writes to the console as a bunch of spaces, then "P a s s w o r d 1". Any ideas what I'm doing wrong?
I suspect that part of the problem might be that the original password was encoded as UTF-16 before encryption, and you're decoding it as UTF-8. Try changing the final line of your Decrypt method:
return Encoding.Unicode.GetString(resultArray);
That doesn't explain all those spurious leading zeros though. Very strange...
EDIT...
Actually, I seem to remember that SqlMembershipProvider prefixes the password bytes with a 16-byte salt before encryption, in which case you'll probably be able to get away with something like this:
return Encoding.Unicode.GetString(resultArray, 16, resultArray.Length - 16);
But that still doesn't explain why those 16 bytes are all zeros rather than a bunch of random values...

Categories