2010-01-05 49 views
1

我試圖加密一個電子郵件正文存儲在數據庫,並且爲了避免未經授權的人閱讀它也避免SQL注入攻擊。對稱算法異常

1-您認爲如何加密電子郵件?
2-爲什麼它不起作用?無論如何,我想學習加密文本。

SymmetricAlgorithm symAlgo = SymmetricAlgorithm.Create(); 
    // I will not use the default keys, although I think they are random enough. 
    symAlgo.GenerateKey(); 
    symAlgo.GenerateIV(); 

    byte[] key = symAlgo.Key; 
    byte[] iv = symAlgo.Key; 


    ICryptoTransform crypto = symAlgo.CreateEncryptor(); 
    byte[] block = UtilityMA.StringUtil.ConvertUTF16StringToByteArray(HTMLBody); 
    byte[] cipherText = new byte[block.Length + 32]; 

    crypto.TransformBlock(block, 0, block.Length, cipherText, 0); 


    symAlgo.Clear(); 
    crypto.Dispose(); 

crypto.TransformBlock火災例外
System.ArgumentException了未處理由用戶代碼 消息= 「值是無效的」。 源= 「mscorlib程序」 棧跟蹤

: 在System.Security.Cryptography.RijndaelManagedTransform.TransformBlock(字節[] INPUTBUFFER,的Int32 inputOffset,的Int32 inputCount,字節[] OutputBuffer中,的Int32 outputOffset)按 在Demo.BLL.Contact .History.SendEmail(String HTMLBody,Int32 Record_Id)in C:\ Documents and Settings \ Administrator \ My Documents \ Visual Studio 2008 \ Projects \ BLL \ BLL \ Contact \ History.cs:line 35 at _Default.BtnSend_Click(Object sender ,EventArgs e)位於c:\ Documents and Settings \ Administrator \ My Documents \ Visual Studio 2008 \ Projects \ Demos \ ContactDemo \ Contact.aspx.cs:line 46 at System.Web.UI.WebControls.Button.OnClick(EventArgs e) 在System.Web.UI.WebControls.Button.RaisePostBackEven噸(字符串eventArgument) 在System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(字符串eventArgument) 在System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,字符串eventArgument) 在System.Web.UI.Page.RaisePostBackEvent(NameValueCollection中POSTDATA) 在System.Web.UI.Page.ProcessRequestMain(布爾includeStagesBeforeAsyncPoint,布爾includeStagesAfterAsyncPoint) 的InnerException:

回答

0

試試這個。

SymmetricAlgorithm symAlgo = SymmetricAlgorithm.Create(); 
// I will not use the default keys, although I think they are random enough. 
symAlgo.GenerateKey(); 
symAlgo.GenerateIV(); 

byte[] key = symAlgo.Key; 
byte[] iv = symAlgo.Key; 

byte[] cipherText; 

using(ICryptoTransform crypto = symAlgo.CreateEncryptor()) 
{ 
    byte[] block = UtilityMA.StringUtil.ConvertUTF16StringToByteArray(HTMLBody); 
    cipherText = crypto.TransformFinalBlock(block, 0, block.Length) 
} 

symAlgo.Clear(); 
2

1)加密是好的,但你會在哪裏存儲鍵?如果密鑰比數據更安全,這只是保護。是的,它確實添加了一層針對SQL注入的保護,但是您應該通過使用參數化語句來消除SQL注入的可能性。 2)它可能會失敗,因爲SymmetricAlgorithm是一個抽象基類,你需要實例化一個具體的類,比如RijndaelManaged.Create();此外,您應該使用TransformFinalBlock()而不是TransformBlock(),而Encoding.UTF8.GetBytes()而不是UtilityMA.StringUtil.ConvertUTF16StringToByteArray()。

下面是關於如何encypt文章/解密: http://www.sharpdeveloper.net/content/archive/2007/06/27/encryption-for-dummies-in-net.aspx