備忘録

備忘録

C# で Blowfish で暗号化、複合する方法

Ⅰ. はじめに

タイトルの通り「C# で Blowfish で暗号化、複合する方法」です。

Ⅱ. やり方

1. 必要なパッケージをNuGetからインストールする
Install-Package Portable.BouncyCastle
2. サンプルプログラムを書く
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;

private static byte[] Blowfish(byte[] key, byte[] iv, byte[] bytes, bool forEncryption)
{
  // Blowfish
  // Mode = CBC
  // PaddingMode = Zero
  var cbcBlockCipher = new CbcBlockCipher(new BlowfishEngine());
  var cipher = new PaddedBufferedBlockCipher(cbcBlockCipher, new ZeroBytePadding());
  cipher.Init(forEncryption, new ParametersWithIV(new KeyParameter(key), iv));

  var resultBytes = new byte[cipher.GetOutputSize(bytes.Length)];

  var length = cipher.ProcessBytes(bytes, 0, bytes.Length, resultBytes, 0);
  cipher.DoFinal(resultBytes, length);

  return resultBytes;
}

static void Main(string[] args)
{
  // key (64 bits)
  var key = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
  // iv (64 bits)
  var iv = new byte[] { 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };

  var str = "Hello World!";

  // 暗号化
  var encryptedBytes = Blowfish(key, iv, Encoding.UTF8.GetBytes(str), true);
  Console.WriteLine(BitConverter.ToString(encryptedBytes));

  // 複合
  var decryptedBytes = Blowfish(key, iv, encryptedBytes, false);
  Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes));
}

実行結果

DD-78-3D-30-DC-E2-9F-0D-81-BD-9C-36-C0-B9-6B-35
Hello World!