rijndael encryption - only part of the string is decrypted

后端 未结 3 453
温柔的废话
温柔的废话 2021-01-14 21:06

Only part of the string is getting decrypted, i think it has to do with my encoding.

Here is what happens:

        string s = \"The brown fox jumped          


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-14 21:57

    I solved my issue by using base64 string for the encryption - i may look at other options but i only needed these methods for a small amount of data, here is the final code:

    public static string EncryptString(string stringToEncrypt, string encryptionKey)
    {
        string encrypted = String.Empty;
        byte[] key = Encoding.Unicode.GetBytes(encryptionKey);
    
        RijndaelManaged RMCrypto = new RijndaelManaged();
        RMCrypto.Padding = PaddingMode.PKCS7;
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
    
        byte[] encryptedString = Encoding.ASCII.GetBytes(stringToEncrypt);
        cs.Write(encryptedString, 0, encryptedString.Length);
        cs.FlushFinalBlock();
        cs.Close();
    
        //encrypted = Encoding.ASCII.GetString(ms.ToArray());
        return Convert.ToBase64String(ms.ToArray());
    }
    
    public static string DecryptString(string stringToDecrypt, string encryptionKey)
    {
        string decrypted = String.Empty;
        byte[] key = Encoding.Unicode.GetBytes(encryptionKey);
        byte[] data = Convert.FromBase64String(stringToDecrypt);
    
        RijndaelManaged RMCrypto = new RijndaelManaged();
        RMCrypto.Padding = PaddingMode.PKCS7;
        MemoryStream ms = new MemoryStream();
        CryptoStream cs = new CryptoStream(ms, RMCrypto.CreateDecryptor(key, key), CryptoStreamMode.Write);
        cs.Write(data, 0, data.Length);
        cs.FlushFinalBlock();
        cs.Close();
    
        decrypted = Encoding.ASCII.GetString(ms.ToArray());
    
        return decrypted;
    }
    

提交回复
热议问题