With RC2 encryption, we use a 128-bit key and a 64-bit IV value. The two modes supported are ECB (without salt) and CBC (with salt). The block size is 64 bits (eight bytes), and thus the output cipher will be in multiples of eight bytes. In this case we will use PKCS7 padding, and which fills the input data with a value that is equal to the number of padding bytes.
RC2 Encryption with C# |
Coding
We can implement with:
public string rc2_block(string mode, string message) { byte[] encrypted; string plaintext; var rc2 = new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; if (mode == "CBC") rc2.Mode = CipherMode.CBC; else if (mode == "CFB") rc2.Mode = CipherMode.CFB; else if (mode == "CTS") rc2.Mode = CipherMode.CTS; else if (mode == "ECB") rc2.Mode = CipherMode.ECB; else if (mode == "OFB") rc2.Mode = CipherMode.OFB; rc2.GenerateIV(); rc2.GenerateKey(); ICryptoTransform encryptor = rc2.CreateEncryptor(); ICryptoTransform decryptor = rc2.CreateDecryptor(); using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { swEncrypt.Write(message); } encrypted = msEncrypt.ToArray(); } } using (MemoryStream msDecrypt = new MemoryStream(encrypted)) { using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(csDecrypt)) { plaintext = srDecrypt.ReadToEnd(); } } } string str1 = "Message: " + message; str1 = str1 + "\nIV " + BitConverter.ToString(rc2.IV).Replace("-", string.Empty); str1 = str1 + "\nKey " + BitConverter.ToString(rc2.Key).Replace("-", string.Empty); str1 = str1 + "\nMode: " + mode; str1 = str1 + "\n\nCipher: " + BitConverter.ToString(encrypted).Replace("-", string.Empty); str1 = str1 + "\nCipher: " + Convert.ToBase64String(encrypted); str1 = str1 + "\nDecrypted: " + plaintext; return (str1); }
A sample run shows:
== RC2 Encryption == Message: qwerty Key: 11210203040506070001020304050607 IV: 0001020304050607 Mode: CBC Encrypted Data: 4FD12F64A64AB15B Decrypted Data: qwerty
Presentation
Here is an outline: