From fd9e0cbb0b03c030cc098c58bbf68e533ff08186 Mon Sep 17 00:00:00 2001 From: Peter Dettman Date: Tue, 15 Aug 2023 09:46:51 +0700 Subject: Explicitly set IV to zeros when no ParametersWithIV --- crypto/src/crypto/modes/CbcBlockCipher.cs | 15 +++++++++------ crypto/src/crypto/parameters/ParametersWithIV.cs | 8 ++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crypto/src/crypto/modes/CbcBlockCipher.cs b/crypto/src/crypto/modes/CbcBlockCipher.cs index 8e2b3c2a4..0423af242 100644 --- a/crypto/src/crypto/modes/CbcBlockCipher.cs +++ b/crypto/src/crypto/modes/CbcBlockCipher.cs @@ -1,6 +1,7 @@ using System; using Org.BouncyCastle.Crypto.Parameters; +using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Modes { @@ -56,19 +57,21 @@ namespace Org.BouncyCastle.Crypto.Modes if (parameters is ParametersWithIV ivParam) { - byte[] iv = ivParam.GetIV(); - - if (iv.Length != blockSize) + if (ivParam.IVLength != blockSize) throw new ArgumentException("initialisation vector must be the same length as block size"); - Array.Copy(iv, 0, IV, 0, iv.Length); + ivParam.CopyIVTo(IV, 0, blockSize); - parameters = ivParam.Parameters; + parameters = ivParam.Parameters; + } + else + { + Arrays.Fill(IV, 0x00); } Reset(); - // if null it's an IV changed only. + // if null it's an IV changed only (key is to be reused). if (parameters != null) { cipher.Init(encrypting, parameters); diff --git a/crypto/src/crypto/parameters/ParametersWithIV.cs b/crypto/src/crypto/parameters/ParametersWithIV.cs index c5f04aab1..d33b18c37 100644 --- a/crypto/src/crypto/parameters/ParametersWithIV.cs +++ b/crypto/src/crypto/parameters/ParametersWithIV.cs @@ -72,6 +72,14 @@ namespace Org.BouncyCastle.Crypto.Parameters m_iv = new byte[ivLength]; } + public void CopyIVTo(byte[] buf, int off, int len) + { + if (m_iv.Length != len) + throw new ArgumentOutOfRangeException(nameof(len)); + + Array.Copy(m_iv, 0, buf, off, len); + } + public byte[] GetIV() { return (byte[])m_iv.Clone(); -- cgit 1.4.1