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;
}
'
不是答案,但第一功能可以通过'字节[] keyBytes = File.ReadAllBytes( “yourKeyFile”)替换;',和用于键部位,[MSDN](https://msdn.microsoft。 com/en-us/library/system.security.cryptography.symmetricalgorithm.legalkeysizes(v = vs.110).aspx)说它必须<= 32个字节。你没有任何选择,只能使用其他密钥文件或使用该文件或更改加密方法的子范围。 – Sakura