Blowfish ExampleWith CBC we split the message into blocks and encrypt each block. The input from the first stage is the IV (Initialisation Vector), and the input to the following stages is the output from the previous stage. In this example we will use Blowfish to encrypt, using CBC. [Theory] Encrypted (Base-64) Encrypted (Hex) Decrypted |
Try an example
- Word is "fred", key is "bert" and IV of 1, gives "1AC9C54C951E180E0000000000000000". blowfishcbc
- Word is "fred", key is "bert" and IV of 2, gives "D27FA68C6AC794200000000000000000". blowfishcbc
Presentation
Blog
A related blog is here
Code Used
using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Crypto.Paddings; public string BlowFishEncryptionCBC(bool encrypt, string plain, string key, string iv) { int i = 0; try { try { i = System.Convert.ToInt32(iv); } catch { } CbcBlockCipher cipher = new CbcBlockCipher(new BlowfishEngine()); int blocksize = cipher.GetBlockSize(); byte [] iv_vector = new byte[blocksize]; byte[] key_byte = new byte[blocksize]; byte[] input_buffer = new byte[2*blocksize]; byte[] output_buffer = new byte[2*blocksize]; byte[] temp = BitConverter.GetBytes(i); for (int val = 0; val < temp.Length; val++) iv_vector[val] = temp[val]; temp = System.Text.Encoding.ASCII.GetBytes(key); for (int val = 0; val < temp.Length; val++) key_byte[val] = temp[val]; if (encrypt == true) temp = System.Text.Encoding.ASCII.GetBytes(plain); else temp = StrToByteArray(plain); for (int val = 0; val < temp.Length; val++) input_buffer[val] = temp[val]; ICipherParameters paramkey = new KeyParameter(key_byte); ICipherParameters param = new ParametersWithIV(paramkey,iv_vector); cipher.Init(encrypt, param); cipher.ProcessBlock(input_buffer, 0, output_buffer, 0); // Return Hex string for encryption if (encrypt) return Global.ByteToString(output_buffer); // Return string for decrypt UTF8Encoding encoding = new UTF8Encoding(); string str= encoding.GetString(output_buffer); str = str.Replace("\0", string.Empty); return (str); } catch (Exception ex) { encrypted = ex.Message; } return encrypted; } public static byte[] StrToByteArray(string str) { Dictionary<string, byte> hexindex = new Dictionary<string, byte>(); for (byte i = 0; i < 255; i++) hexindex.Add(i.ToString("X2"), i); List<byte> hexres = new List<byte>(); for (int i = 0; i < str.Length; i += 2) hexres.Add(hexindex[str.Substring(i, 2)]); return hexres.ToArray(); }