Raskolnikov
Raskolnikov

Reputation: 4009

How to do encryption with any key

I am implementing encryption with Rijndael symmetric algorithm. This is working, but I want to change this to work wirh any key. I do not want to generate key, I want to allow user to pick his own key, like his pasword for encryption.

RijndaelManaged myRijndael = new RijndaelManaged();
myRijndael.GenerateKey();
myRijndael.GenerateIV();

var encryptor = new RijndaelManagedEncryption();

var encrypted = encryptor.EncryptSettingValue(myRijndael.Key, "Encrypt this", myRijndael.IV);

For example like this

RijndaelManaged myRijndael = new RijndaelManaged();
myRijndael.GenerateIV();
var key = Convert.FromBase64String("pasword")
var encryptor = new RijndaelManagedEncryption();

var encrypted = encryptor.EncryptSettingValue(key , "Encrypt this", myRijndael.IV);

But if I do this I will get Exception:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Invalid length for a Base-64 char array or string.

If you want see algorithm this is link: https://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=vs.110).aspx

Upvotes: 1

Views: 150

Answers (1)

Andrey Korneyev
Andrey Korneyev

Reputation: 26886

First of all, string "password" is not a valid Base64 string, so you can't convert from it like you want.

And more, you should not get a key for encryption "straightforward" from some string just because it will not generate well-randomized key.

Use Rfc2898DeriveBytes instead something like:

var password = "pasword";
var salt = new byte[] { 0xe3, 0x5c, 0x51, 0x6a, 0x13, 0x55, 0x46, 0xf8, 0x75, 0xba, 0x54, 0xc3, 0x42, 0x5b, 0x70, 0xac };
var key = new Rfc2898DeriveBytes(password, salt).GetBytes(32);

Here salt is some random array of bytes, doesn't matter what it actually will be. It just needed to bring more randomness into key generation and can be any (but the same all the time to ensure you're generating identical keys from identical passwords).

Upvotes: 2

Related Questions