使用c#将密钥文件扩展名读取为字节,并将其传递给加密算法

时间:2016-02-29 06:27:30

标签: c# rijndael

我正在使用二进制阅读器来读取我的.key文件。我得到的输出是37字节数组。但是我的指定算法只需要16个字节。当我将参数传递给加密算法(用于加密的Rijindael托管类)时,我得到“指定密钥大小对此算法无效”错误。客户端建议的密钥文件和算法。

将.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 个答案:

答案 0 :(得分: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());
    }

如果它仍然不起作用,可能是由于你的&#34; rijAlg&#34;的初始化错误。元件。 试着看看: decrpyt .Net Encrypted string in iOS 它有一个适用于我的加密加密。