I found the below code online, but in its original state, the encryption was not using any padding (Padding.None), and was encrypting in blocks of 8. I wasn't able to get this code to properly encrypt / decrypt data so I was forced to have it encrypt the full length of the text. Is there something fundamentally wrong with what I have done? If so, could someone please show me the proper way to encrypt text in blocks of 8?

I think this question is hard at the limit between Stack Overflow and Cryptography stack exchange ... I'm not sure on which side of the limit. (Thomas' answer is clearly on "our" side of the limit.)
–
Paŭlo EbermannAug 9 '11 at 14:28

Hi @Evan, welcome to Crypto.SE! FYI, probably only a fraction of cryptographers here are skilled at reading C# code and understanding what cryptographic operations the code wil do. So, in the future, if you are able to translate this into a specification of what the code is doing (e.g., in mathematical notation), it is possible that this might facilitate a broader range of responses. Either way, thanks for participating!
–
D.W.Aug 11 '11 at 2:26

1 Answer
1

3DES is a block cipher which processes "blocks" of 64 bits. A block cipher is not sufficient to encrypt a message, defined as a sequence of potentially many bytes. Hence the use of a mode of operation which organizes things; this may imply some padding, and an Initialization Vector.

TripleDESCryptoServiceProvider can do all that: you specify the key, the chaining mode, the padding and the IV, and then you call CreateEncryptor() (or CreateDecryptor()) which returns an ICryptoTransform instance, on which you call TransformBlock() and TransformFinalBlock() to process all your data. You can process the data by chunks (you call TransformBlock() several times, and finally TransformFinalBlock() once).

The code you show is trying to do the opposite of what you seek: it uses TripleDESCryptoServiceProvider to process a single block, without any chaining or padding (hence the use of ECB and no padding).

Note that:

ECB is known to be a weak chaining mode (it leaks quite a lot of information on typical input data).

Secure modes of operation (e.g. CBC) need an appropriate IV: in the case of CBC, it must be chosen randomly and uniformly with a cryptographically strong random generator, and it must never be reused (the point of the IV is that you can reuse the same key for several messages, as long as each message has its own IV). The IV is normally transmitted along with the encrypted message (in the clear), since the decryptor will need it.

Ciphers process bytes. A "string" is a sequence of characters, thus a conversion step is needed. I assume that your StringToByte() method (which you do not show) does that. Beware of charsets: you want the conversion to always operate the same way, regardless of how the local machine was configured.