2014-01-11 149 views
-1

我想了解爲什麼直接下面的代碼不需要你生成一個IV密鑰?代碼爲:Rijndael加密密鑰

http://msdn.microsoft.com/en-us/library/sb7w85t6(v=vs.85).aspx

Dim key As RijndaelManaged = Nothing 

Try 
    ' Create a new Rijndael key. 
    key = New RijndaelManaged() 

我看到這個樣本代碼,但需要你manaually產生兩個鍵?

代碼爲:

http://msdn.microsoft.com/en-us/library/System.Security.Cryptography.RijndaelManaged(v=vs.110).aspx

Class RijndaelExample 

    Public Shared Sub Main() 
     Try 

      Dim original As String = "Here is some data to encrypt!" 

      ' Create a new instance of the RijndaelManaged 
      ' class. This generates a new key and initialization 
      ' vector (IV). 
      Using myRijndael As New RijndaelManaged() 

       myRijndael.GenerateKey() 
       myRijndael.GenerateIV() 

我也打算硬編碼的鑰匙插入源(我知道這是不是最安全的)......實際上,我怎麼存儲這些..它看起來每次應用程序打開時都會生成一個新的密鑰。

回答

0

你是對的,因爲它會在你每次運行時創建一個新的密鑰和IV。相反,你應該創建自己的哈希(這是用來對數據進行加密,並從您的密碼和「鹽」派生 - 見http://en.wikipedia.org/wiki/Salt_(cryptography)

例如,

SymmetricAlgorithm m_encryption; 
    RSACryptoServiceProvider m_rsa; 
    Rfc2898DeriveBytes m_hash; 

    string password = "Pa55w0rd"; 
    string salt = "this is my salt. There are many like it, but this one is mine."; 

    public void SetupEncryption() 
    { 


     m_encryption = new RijndaelManaged(); 
     m_hash = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt)); 

     m_encryption.Key = m_hash.GetBytes(m_encryption.KeySize/8); 
     m_encryption.IV = m_hash.GetBytes(m_encryption.BlockSize/8); 

    } 

正如你」但注意到,存儲你的鹽和你的密碼是非常糟糕的形式!這只是一個展示如何開始的例子。仔細閱讀維基百科和其他文章,直到你完全理解這些原則!