2016-02-29 55 views
1

我使用的是二進制閱讀器來閱讀我的.key文件。我得到的輸出是37字節數組。但是我指定的算法只需要16個字節。當我將參數傳遞給加密算法(用於加密的Rijindael託管類)時,我得到了「指定的密鑰大小對此算法無效」錯誤。客戶端提供的密鑰文件和算法。閱讀密鑰文件的擴展到使用C#字節,並把它傳遞給加密算法

代碼.key文件轉換爲字節是

public static byte[] ConvertFileToByteArray(string fileName) 
{ 
    byte[] returnValue = null; 
    using (FileStream fr = new FileStream(fileName, FileMode.Open)) 
    { 
     using (BinaryReader br = new BinaryReader(fr)) 
     { 
      returnValue = br.ReadBytes((int)fr.Length); 

     } 
    }  
    return returnValue; 
} 

加密算法是(塊和密鑰大小下面提到是等於16個字節或128位)

' static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV) 
{  
    if (plainText == null || plainText.Length <= 0) 
     throw new ArgumentNullException("plainText"); 
    if (Key == null || Key.Length <= 0) 
     throw new ArgumentNullException("Key"); 
    if (IV == null || IV.Length <= 0) 
     throw new ArgumentNullException("IV"); 
    byte[] encrypted;  
    using (RijndaelManaged rijAlg = new RijndaelManaged()) 
    { 
     rijAlg.BlockSize = 0x80; 
     rijAlg.KeySize = 0x80; 
     rijAlg.Key = Key; 
     rijAlg.GenerateIV(); 
     rijAlg.Mode = CipherMode.CBC; 
     rijAlg.Padding = PaddingMode.PKCS7; 

     // Create a decrytor to perform the stream transform. 
     ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);   
     using (MemoryStream msEncrypt = new MemoryStream()) 
     { 
      using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 
      { 
       using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
       {       
        swEncrypt.Write(plainText); 
       } 
       encrypted = msEncrypt.ToArray(); 
      } 
     } 
    }  
    return encrypted; 
} 

'

+1

不是答案,但第一功能可以通過'字節[] keyBytes = File.ReadAllBytes( 「yourKeyFile」)替換;',和用於鍵部位,[MSDN](https://msdn.microsoft。 com/en-us/library/system.security.cryptography.symmetricalgorithm.legalkeysizes(v = vs.110).aspx)說它必須<= 32個字節。你沒有任何選擇,只能使用其他密鑰文件或使用該文件或更改加密方法的子範圍。 – Sakura

回答

0

你需要寫長度在msEncrypt如下:

using (MemoryStream msEncrypt = new MemoryStream()) 
    { 
     // prepend the IV 
     msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int)); 
     msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length); 
     using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) 
     { 
      using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) 
      { 
       //Write all data to the stream. 
       swEncrypt.Write(plainText); 
      } 
     } 
     outStr = Convert.ToBase64String(msEncrypt.ToArray()); 
    } 

如果它仍然不起作用,這可能是由於「rijAlg」元素的初始化錯誤。 試着看看: decrpyt .Net Encrypted string in iOS 它有一個工作加密已爲我工作。

相關問題