Click here to Skip to main content
Licence CPOL
First Posted 17 Jul 2002
Views 103,228
Bookmarked 38 times

A C# implementation of the Twofish cipher

By | 17 Jul 2002 | Article
An article on integrating a C# implementation of the Twofish cipher into the .NET framework.

Preface

This article is about using the .NET framework to create an encryption provider and integrate it using the same mechanism provided by the .NET platform. This article is not about the Twofish cipher itself but is used as an example cipher that can can be integrated in such a manner.

Introduction

The .NET framework supports various encryption providers such as the AES winner Rijndael. But it is possible to use the same framework to add custom encryption providers and use them in the same manner as the .NET provided ones. It is not necessary to just use it for encryption as the same framework can also be used for any form of encoding mechanism such as compression or MIME encoding. Also these transformations can be connected together via the streams so that it is possible to cascade these transformations i.e. memory -> compress -> encrypt -> encode, in a very simple manner. This technique will be familiar to people who have used Crypto++. For this purpose the .NET framework provides a base class SymmetricAlgorithm and an interface ICryptoTransform.

Investigation

To investigate how the .NET framework used the SymmetricAlgorithm class and ICryptoTransform interface I created a simple class XOR which does a byte by byte eXclusiveOR on a block of data. A very basic and very poor encryption system but it at least lets one work out if we are using the supplied classes and interfaces correctly. I have also included this in the install but it is just a bunch of methods/properties and lots of trace statements.

Discovery

byte[] ICryptoTransform.TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount); - This method does not like when you return null, throws an exception, when there is no data to return. You will usually have this case when this method is called but inputCount is 0, instead you have to return new byte[0]. This is not documented in the help files (yet).

public virtual SymmetricAlgorithm.CipherMode Mode {get; set;} - The framework does not use this property itself to implement the various cipher modes - you must read this property when you are transforming data and act accordingly.

Twofish

Now armed with the new found knowledge I proceeded to implement the Twofish cipher in C#. I based my implementation on the reference C implementation of the Twofish cipher which can be found at Counterpane Internet Security as I do not think the optimised C implementation would port as well. I have tested the code so that it works in EBC mode and I have also implemented CBC mode as well.

Cascade

As I mentioned before it is possible to cascade these transforms such that with one call you can compress -> encrypt -> encode. In the install I have shown how one may cascade the Twofish cipher and the .NET provided Base64 transforms FromBase64Transform and ToBase64Transform. I haven't shown the compression step as I have yet to implement that transform.

Twofish fish = new Twofish();
System.IO.MemoryStream ms = new System.IO.MemoryStream();

// create an encoder
ICryptoTransform encode = new ToBase64Transform();

//create Twofish Encryptor from this instance
ICryptoTransform encrypt = fish.CreateEncryptor( Key, IV);
// both Key and IV are byte[] types 

// we have to work backwards defining the last link in the chain first
CryptoStream cryptostreamEncode = new CryptoStream( ms, encode, 
                                                    CryptoStreamMode.Write);
CryptoStream cryptostream = new CryptoStream( cryptostreamEncode, encrypt, 
                                              CryptoStreamMode.Write);
// or we could do this as we don't need to use cryptostreamEncode
CryptoStream cryptostream = new 
  CryptoStream(new CryptoStream( ms,encode, CryptoStreamMode.Write), 
  encrypt, CryptoStreamMode.Write);

Outstanding Issues

  • I have not created any random key or IV mechanism that would normally be implemented in the GenerateIV() and GenerateKey() overrides.
  • Need further testing to test the CBC mode and to add other cipher modes.
  • Integrate a compression algorithm into a class that supports ICryptoTransform interface
  • Optimise the code. As I mentioned before I am not too sure how to go about optimising C# code so any tips appreciated.
  • The uninstall does not remove any produced files due to compilation.

History

First revision - 17 July 2002

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shaun Wilde

Architect

United Kingdom United Kingdom

Member

All articles are supplied as-is, as a howto on a particular task that worked for me in the past. None of the articles are supposed to be out-of-the-box freeware controls and nor should they be treated as such. Caveat emptor.
 
Been involved in programming from the early '80s. First on my Spectrum, then an Amstrad. Did lots of Fortran while at University before becoming involved in Forth, Prolog, Pascal, Occam, C and eventually C++. Eventually started programming on the Windows platform using Borland’s OWL framework, during my postgraduate years. When I started work in '94, I learnt MFC followed by COM and ATL and never looked back. Now working exclusively in .NET, working on WinForms, ASP.NET and the Compact Framework using C# and VB.NET. Using every bit of the .NET framework I can such as WebServices and writing my own controls for my .NET Portal, and for the Compact Framework. Still lots I don't know, but the end of the universe hasn't happened yet - I wonder if I'll have time?
 
I was a permanent employee for a number of companies until Dec 2000 before going independent after the DotCom I ws involved with went DotBomb. Now supplying consulting services to various institutions in London and surrounding regions i.e. UK Smile | :) .
 
Now living and working in Australia, trying to be involved in the local .NET and Agile communities. Also maintaining an open source code coverage tool called PartCover whilst thinking of developing a new one.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralBug in Mono PinmemberMember 19455687:37 10 Oct '09  
GeneralRe: Bug in Mono PinmemberShaun Wilde10:46 26 Oct '10  
GeneralMore or less bug in TransformBlock PinmemberSvante Seleborg4:21 12 Oct '07  
GeneralRe: More or less bug in TransformBlock PinmemberShaun Wilde5:06 12 Oct '07  
GeneralRe: More or less bug in TransformBlock PinmemberSvante Seleborg5:15 12 Oct '07  
GeneralRe: More or less bug in TransformBlock PinmemberShaun Wilde2:58 13 Oct '07  
GeneralRe: More or less bug in TransformBlock PinmemberSvante Seleborg9:57 13 Oct '07  
GeneralRe: More or less bug in TransformBlock PinmemberShaun Wilde11:35 13 Oct '07  
GeneralRe: More or less bug in TransformBlock PinmemberSvante Seleborg0:53 14 Oct '07  
GeneralNice topic PinmemberVahe Karamian14:20 13 Feb '07  
GeneralRe: Nice topic PinmemberShaun Wilde21:46 17 Feb '07  
GeneralI met some problem Pinmemberpdwolf20:14 18 May '03  
GeneralRe: I met some problem PinmemberShaun Wilde9:09 19 May '03  
GeneralRe: I met some problem Pinmemberfind_ananth6:48 26 Oct '10  
GeneralRe: I met some problem PinmemberShaun Wilde10:49 26 Oct '10  
GeneralQuestion Pinmemberbfadi20:32 26 Mar '03  
GeneralRe: Question PinmemberShaun Wilde21:37 26 Mar '03  
GeneralRe: Question Pinmemberbfadi0:19 27 Mar '03  
GeneralRe: Question PinmemberShaun Wilde1:38 27 Mar '03  
QuestionRjindael broken? PinmemberShaun Wilde4:47 17 Sep '02  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 18 Jul 2002
Article Copyright 2002 by Shaun Wilde
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid