diff --git a/crypto/src/crypto/engines/BlowfishEngine.cs b/crypto/src/crypto/engines/BlowfishEngine.cs index e38f4e8f6c..a7d688d6e1 100644 --- a/crypto/src/crypto/engines/BlowfishEngine.cs +++ b/crypto/src/crypto/engines/BlowfishEngine.cs @@ -308,6 +308,8 @@ public sealed class BlowfishEngine private byte[] workingKey; + private bool useLittleEndian = false; + public BlowfishEngine() { S0 = new uint[SBOX_SK]; @@ -317,7 +319,7 @@ public BlowfishEngine() P = new uint[P_SZ]; } - /** + /** * initialise a Blowfish cipher. * * @param forEncryption whether or not we are for encryption. @@ -325,7 +327,7 @@ public BlowfishEngine() * @exception ArgumentException if the parameters argument is * inappropriate. */ - public void Init( + public void Init( bool forEncryption, ICipherParameters parameters) { @@ -347,6 +349,8 @@ public bool IsPartialBlockOkay get { return false; } } + public bool UseLittleEndian { get => useLittleEndian; set => useLittleEndian = value; } + public int ProcessBlock( byte[] input, int inOff, @@ -505,8 +509,18 @@ private void EncryptBlock( byte[] dst, int dstIndex) { - uint xl = Pack.BE_To_UInt32(src, srcIndex); - uint xr = Pack.BE_To_UInt32(src, srcIndex+4); + uint xl; + uint xr; + if (useLittleEndian) + { + xl = Pack.LE_To_UInt32(src, srcIndex); + xr = Pack.LE_To_UInt32(src, srcIndex + 4); + } + else + { + xl = Pack.BE_To_UInt32(src, srcIndex); + xr = Pack.BE_To_UInt32(src, srcIndex + 4); + } xl ^= P[0]; @@ -518,8 +532,16 @@ private void EncryptBlock( xr ^= P[ROUNDS + 1]; - Pack.UInt32_To_BE(xr, dst, dstIndex); - Pack.UInt32_To_BE(xl, dst, dstIndex + 4); + if (useLittleEndian) + { + Pack.UInt32_To_LE(xr, dst, dstIndex); + Pack.UInt32_To_LE(xl, dst, dstIndex + 4); + } + else + { + Pack.UInt32_To_BE(xr, dst, dstIndex); + Pack.UInt32_To_BE(xl, dst, dstIndex + 4); + } } /** @@ -533,10 +555,21 @@ private void DecryptBlock( byte[] dst, int dstIndex) { - uint xl = Pack.BE_To_UInt32(src, srcIndex); - uint xr = Pack.BE_To_UInt32(src, srcIndex + 4); - - xl ^= P[ROUNDS + 1]; + uint xl; + uint xr; + + if (useLittleEndian) + { + xl = Pack.LE_To_UInt32(src, srcIndex); + xr = Pack.LE_To_UInt32(src, srcIndex + 4); + } + else + { + xl = Pack.BE_To_UInt32(src, srcIndex); + xr = Pack.BE_To_UInt32(src, srcIndex + 4); + } + + xl ^= P[ROUNDS + 1]; for (int i = ROUNDS; i > 0 ; i -= 2) { @@ -546,8 +579,16 @@ private void DecryptBlock( xr ^= P[0]; - Pack.UInt32_To_BE(xr, dst, dstIndex); - Pack.UInt32_To_BE(xl, dst, dstIndex + 4); - } + if (useLittleEndian) + { + Pack.UInt32_To_LE(xr, dst, dstIndex); + Pack.UInt32_To_LE(xl, dst, dstIndex + 4); + } + else + { + Pack.UInt32_To_BE(xr, dst, dstIndex); + Pack.UInt32_To_BE(xl, dst, dstIndex + 4); + } + } } }