2014-01-11 150 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); 

    } 

正如你”但注意到,存储你的盐和你的密码是非常糟糕的形式!这只是一个展示如何开始的例子。仔细阅读维基百科和其他文章,直到你完全理解这些原则!