public static byte[] HandleSessionKey(byte[] sessionKey, byte[] sharedSecret) { byte[] iv = new byte[16]; new SecureRandom().NextBytes(iv); TwofishEngine engine = new TwofishEngine(); CtrBlockCipher blockCipher = new CtrBlockCipher(engine); PaddedBufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, new ZeroBytePadding()); KeyParameter secret = new KeyParameter(sharedSecret); ParametersWithIV key = new ParametersWithIV(secret, iv); bufferedBlockCipher.Init(true, key); byte[] result = new byte[iv.Length + sessionKey.Length]; bufferedBlockCipher.ProcessBytes(sessionKey, 0, sessionKey.Length, result, 16); Array.Copy(iv, result, iv.Length); int pos = 0; while (pos < sessionKey.Length) { int length = blockCipher.ProcessBlock(sessionKey, pos, result, pos + iv.Length); pos += length; } return(result); }
public static byte[] HandleUser(byte[] cipher, byte[] secretKey) { TwofishEngine engine = new TwofishEngine(); CtrBlockCipher blockCipher = new CtrBlockCipher(engine); KeyParameter secret = new KeyParameter(secretKey); ParametersWithIV key = new ParametersWithIV(secret, cipher, 0, 16); int cipherLength = cipher.Length; int blockSize = engine.GetBlockSize(); int fraction = cipherLength % blockSize; cipherLength += blockSize - fraction; byte[] input = new byte[cipherLength]; Array.Copy(cipher, input, cipher.Length); blockCipher.Init(false, key); byte[] result = new byte[cipherLength - 16]; int pos = 0; while (pos < cipher.Length - 16) { int length = blockCipher.ProcessBlock(input, pos + 16, result, pos); pos += length; } return(result); }