Click here to Skip to main content
13,193,829 members (48,371 online)
Click here to Skip to main content
Add your own
alternative version


44 bookmarked
Posted 20 Feb 2007

Stream Based Encryption for .NET

, 6 Feb 2009
Rate this:
Please Sign up or sign in to vote.
A symmetric stream-based encryption method in C# based on a rolling cipher and mod-257 multiplications


The .NET Framework defines several good symmetric encryption algorithms: DES, Rijndael, and so on. For 'block work' (encrypting a file, the contents of a text box and the like), these algorithms are excellent. However when manipulating streams of unknown length, such as a TCP socket, they have a major drawback: they require data in multibyte blocks. If you require 8 bytes and you have only received 6 so far, you can't provide any information to the data consumer at all.

For such a stream based environment, an algorithm which takes each byte by itself and produces an encoded/decoded byte is useful. Because there is less linkage between bytes, such a method is cryptographically weaker (so I don't recommend running your online bank this way!), but for amateur use all that is really required is that a simple look at the transferred data reveals nothing.

Like all symmetric algorithms, the security is completely lost if the key is not kept secure. You should always transmit keys for important secure channels in a secure way, either by both parties knowing the key through offline sources or by a public key encrypted exchange process. In the new version of my Sockets library which uses this encryption method (link pending), the key exchange uses RSA, which is easy to do in .NET.


The algorithm is coded as a pair of classes implementing the ICryptoTransform interface. They are in the RedCorona.Cryptography namespace. A simple example of how to use them would be:

void EncryptionTest(string text, byte[] key){
 byte[] plain = Encoding.UTF8.GetBytes(text);
 BaseCrypto enc = new SimpleEncryptor(key), dec = new SimpleDecryptor(key);
 byte[] cipher = enc.TransformFinalBlock(plain, 0, plain.Length);
 byte[] plain2 = dec.TransformFinalBlock(cipher, 0, cipher.Length);
 // plain and plain2 should now be byte-for-byte equal

Note that there is no inbuilt checking; if you attempt to decrypt bad data, or decrypt with the wrong key, you will generate nonsense results. I recommend that you insert some form of checksum or identifying bytes into your input so you can detect when decryption is going wrong.

The Algorithm

Encryption of an individual byte takes advantage of the useful fact that 257 is a prime number, and thus ([1..256]×key) mod 257 is a one-to-one (and therefore reversible) mapping for any key in [1..256]. Multiplication in mod space is a good way to generate well dispersed cipher-data. The simplest version of the algorithm would be:

cipher-byte: (((plain-byte+1)×(key-byte+1)) mod 257)-1

I will call this operation mul257, hence this simplistic algorithm would be:

cipher-byte: mul257(plain-byte, key-byte)

However this is vulnerable to the plain text containing zeroes at known locations, which will be quite common in computer data. (Zeroes – which become 1s for the multiplication – result in the cipher-text being equal to the key, so if the location of plain-text zeroes is known, parts of the key can be determined trivially.) Thus the version as implemented is:

cipher-byte: mul257(plain-byte+key-byte, key-byte)

Now the cipher-text is equal to the key when byte(plain-byte+key-byte) is zero, which cannot be known without knowing the key. Decryption is simply:

plain-byte: mul257(cipher-byte, key-byte')-key-byte

... where x' is the 257-complement of x, i.e. xx' mod 257 = 1. (These numbers are stored in a lookup table.)

Obviously a one-byte key is trivial to break by brute force and is not sufficient. Thus my algorithm uses a 'rolling cipher'; rather like the German Enigma machine, the key byte changes each time a new byte is encoded. The 'encryption key' which you pass to the class is a byte vector of arbitrary length. Each time a new byte is encrypted, after the encryption has been done the key byte is modified to become:

new-key-byte: mul257(mul257(key-byte, keyvec[keypos++]), cipher-byte+plain-byte)

Using the cipher-byte produces a better dispersion of keys than just using the plain byte, but the plain byte must be included for this multiplication to have any security value as the cipher byte is (obviously) available to a cracker. The key vector wraps once the end is reached. An initial key byte is generated as the sum (mod 256) of the key vector, thus changing any byte of the key, even if it's not used at all in the encryption, produces a completely different byte stream.

Because the encryption depends on earlier characters, this algorithm is not suitable for use when some of the data may be lost or out of sequence. That is, the value of encrypt(plaintext) will be different depending on what has been passed to encrypt in the past.

However, because it processes each byte in turn it is suitable where the data may be unpredictably broken up, as long as it is in sequence. That is:

encrypt(a,b),encrypt(c) == encrypt(a),encrypt(b,c) 


Since the code is so small (3 KB), here it is in easily C&P'able form. Please remember to credit me and link back to this article if you use it!

// Stream based encryption
// new SimpleEncryptor(key);

// (C) Richard Smith 2005-7
// You can use this for free and give it to people as much as you like
// as long as you leave a credit to me :).

using System;
using System.Security.Cryptography;

namespace RedCorona.Cryptography {
  // Cryptographic classes
  public abstract class BaseCrypto : ICryptoTransform {
    public int InputBlockSize { get { return 1; } }
    public int OutputBlockSize { get { return 1; } }
    public bool CanTransformMultipleBlocks { get { return true; } }
    public bool CanReuseTransform { get { return true; } }    
    protected byte[] key;
    protected byte currentKey;
    protected int done = 0, keyinx = 0;
    protected BaseCrypto(byte[] key){
      if(key.Length == 0) throw new ArgumentException("Must provide a key");
      this.key = key;
      currentKey = 0;
      for(int i = 0; i < key.Length; i++) currentKey += key[i];
    protected abstract byte DoByte(byte b);
    public int TransformBlock(byte[] from, int frominx, int len, byte[] to, int toinx){
      for(int i = 0; i < len; i++){      
        to[toinx + i] = DoByte(from[frominx + i]);
      return len;
    public byte[] TransformFinalBlock(byte[] from, int frominx, int len){
      byte[] to = new byte[len];
      TransformBlock(from, frominx, len, to, 0);
      return to;
    protected void BumpKey(){
      keyinx = (keyinx + 1) % key.Length;
      currentKey = Multiply257(key[keyinx], currentKey);
    protected static byte Multiply257(byte a, byte b){
       return (byte)((((a + 1) * (b + 1)) % 257) - 1);
    protected static byte[] complements = {
    protected static byte Complement257(byte b){ return complements[b]; }
    public void Dispose(){} // for IDisposable
  public class SimpleEncryptor : BaseCrypto {
    public SimpleEncryptor(byte[] key) : base(key) {}
    protected override byte DoByte(byte b){
      byte b2 = Multiply257((byte)(b+currentKey), currentKey);
      currentKey = Multiply257((byte)(b+b2), currentKey);
      return b2;
  public class SimpleDecryptor : BaseCrypto {
    public SimpleDecryptor(byte[] key) : base(key) {}
    protected override byte DoByte(byte b){
      byte b2 = (byte)(Multiply257(b, Complement257(currentKey)) - currentKey);
      currentKey = Multiply257((byte)(b+b2), currentKey);
      return b2;


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


About the Author

United Kingdom United Kingdom
I'm a recent graduate (MSci) from the University of Cambridge, no longer studying Geology. Programming is a hobby so I get to write all the cool things and not all the boring things Smile | :) . However I now have a job in which I have to do a bit of work with a computer too.

You may also be interested in...

Comments and Discussions

QuestionSystem.Security.Cryptography.CryptoStream Pin
Qwertie20-Oct-12 7:40
memberQwertie20-Oct-12 7:40 
AnswerRe: System.Security.Cryptography.CryptoStream Pin
BobJanova20-Oct-12 8:13
memberBobJanova20-Oct-12 8:13 
GeneralConverting a block cipher to a stream cipher Pin
supercat96-Feb-09 11:51
membersupercat96-Feb-09 11:51 
There are a variety of methods for converting a block cipher to a stream cipher. Many of them require initializing a stream by sending an 'initialization vector' equal in size to the encryption data block, but that is not generally a problem.

Encryption schemes where the prefix property holds at the byte level [i.e., if 'a' is a collection of bytes and 'b' is a single byte, encrypt(a+b) will be encrypt(a) plus one byte] are apt to be very susceptible to known plaintext attacks. They may protect data from adversaries who don't really want it, but they would yield quickly to any serious attack.

I would suggest reading[^] for more information, looking especially at cipher-feedback mode or output-feedback mode.
GeneralRe: Converting a block cipher to a stream cipher Pin
BobJanova7-Feb-09 0:00
memberBobJanova7-Feb-09 0:00 streams Pin
Alejandro Castanaza6-Feb-09 6:20
memberAlejandro Castanaza6-Feb-09 6:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web03 | 2.8.171018.2 | Last Updated 6 Feb 2009
Article Copyright 2007 by BobJanova
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid