Rijndael algorithm (How to create our own Key )

淺唱寂寞╮ 提交于 2019-12-03 08:28:56

You can try something like this, based on the RijndaelManaged Class MSDN article that I also recommend you to read.

var plainText = "This will be encrypted.";
var aesAlg = new RijndaelManaged();
aesAlg.Key = new byte[32] { 118, 123, 23, 17, 161, 152, 35, 68, 126, 213, 16, 115, 68, 217, 58, 108, 56, 218, 5, 78, 28, 128, 113, 208, 61, 56, 10, 87, 187, 162, 233, 38 };
aesAlg.IV = new byte[16] { 33, 241, 14, 16, 103, 18, 14, 248, 4, 54, 18, 5, 60, 76, 16, 191};
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {
        swEncrypt.Write(plainText);
    }
}

return msEncrypt.ToArray();

What do you mean by cannot provide the key of our own? Here's an example on how you do it.

public static string Encrypt(string Text, byte[] key, byte[] VectorBytes){
    try{
        byte[] TextBytes = Encoding.UTF8.GetBytes(Text);        
        RijndaelManaged rijKey = new RijndaelManaged();
        rijKey.Mode = CipherMode.CBC; 
        ICryptoTransform encryptor = rijKey.CreateEncryptor(key,VectorBytes); 
        MemoryStream memoryStream = new MemoryStream(); 
        cryptoStream.Write(TextBytes, 0, TextBytes.Length); 
        cryptoStream.FlushFinalBlock(); 
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close(); 
        string cipherText = Convert.ToBase64String(cipherTextBytes); 
        return cipherText;
    } 
    catch (Exception e){
        MessageBox.Show("Falsches Passwort "+ e.Message.ToString());
        string t = "";
        return t;
    }
}

The key property of the Rijndael instance takes a byte[] as the key. Make sure you set it to an array with a valid size for the algorithm.

Link to msdn: http://msdn.microsoft.com/en-us/library/system.security.cryptography.symmetricalgorithm.key.aspx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!