Search code examples
c#.netencryptionopensslbouncycastle

How to use custom chaining modes in .Net with OpenSSL?


I need to implement custom chaining mode for encryption. I need to use symmetric block cipher (AES, 3DES, DES, IDEA). The problem I encounter is, the libraries/wrappers I found do not allow it.

BouncyCastle has those as Enum: Mode = CipherMode.CBC, so I do not see - how I can use my own. System.Security.Cryptography seem to do same way.

Is there any .NET library or wrapper, that allows custom made chaining modes?

Right now only idea I have got is to encrypt every block using CBC with IV full of zero bits and implement my chaining mode on top of it, but it does not seems as good idea.


Solution

  • I don't know of any library that supports a chaining callback, it sort of goes against the black-box-ness of most cryptographic API.

    The way to accomplish your goal is to encrypt using ECB, since that is "just apply the encryption algorithm to this data". For example, to do CBC:

    private byte[] _iv;
    private ICryptoTransform _encryptor;
    
    private void EncryptBlock(byte[] input, byte[] output)
    {
        byte[] buf = (byte[])input.Clone();
    
        for (int i = 0; i < buf.Length; i++)
        {
            buf[i] ^= _iv[i];
        }
    
        _encryptor.TransformBlock(buf, 0, buf.Length, output, 0);
        Buffer.BlockCopy(out, 0, _iv, 0, output.Length);
    }
    

    (all sorts of error checking omitted)

    Given somewhere you initialized things as

    using (Aes aes = Aes.Create())
    {
        aes.Mode = CipherMode.ECB;
        aes.Key = key;
        _encryptor = aes.CreateEncryptor();
        _decryptor = aes.CreateDecryptor();
    }
    

    (etc).