0

I am trying to encrypt a string with AES 128 encryption, using CBC mode, with Zero Padding. Sadly, i do not know how to do this, as many attempts have gone unsuccessful. I have code in C# and was wondering whether anyone can help me getting my encryption working. the code:

`using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

byte[] request = UTF8Encoding.UTF8.GetBytes("{string which needs encrypting}");

byte[] key = UTF8Encoding.UTF8.GetBytes("{key}");
byte[] iv = UTF8Encoding.UTF8.GetBytes("{iv}");

AesCryptoServiceProvider aes = new AesCryptoServiceProvider();

aes.Key = key;
aes.IV = iv;


aes.Mode = CipherMode.CBC;

aes.Padding = PaddingMode.Zeros;

ICryptoTransform cTransform = aes.CreateEncryptor();

byte[] result = cTransform.TransformFinalBlock(request, 0, request.Length);

aes.Clear()

string encryptedRequest = Convert.ToBase64String(result, 0, result.Length);`

ive looked a common crypto, but i cannot see an option to CBC mode [i dont know cccrypto much anyways, maybe i overlook?] thanks;

Simon
  • 67
  • 1
  • 5

3 Answers3

2

Common Crypto is the right place to look. Specifically, you want to use the 3rd parameter of CCCryptorCreate, which is CCOptions set to 0. That is, the default is CBC. You should open up CommonCrypto.h, as it's actually better documentation than the man page. Here's an example of how to do it:

CCCryptorRef cryptorRef;
CCCryptorStatus rc;
rc = CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, 0, key, keySize, NULL, &cryptorRef);

I passed in NULL for the IV (which means all zeros) and assumed you got the key and key size setup correctly. In my test, I used a 32 byte (256 bit) key.

Doug Richardson
  • 10,483
  • 6
  • 51
  • 77
2

The Method in CommonCrypto.m

- (NSData *) dataEncryptedUsingAlgorithm: (CCAlgorithm) algorithm
                                 key: (id) key
                initializationVector: (id) iv
                             options: (CCOptions) options
                               error: (CCCryptorStatus *) error

iv parameter declaration

@param      iv              Initialization vector, optional. Used for 
                            Cipher Block Chaining (CBC) mode. If present, 
                            must be the same length as the selected 
                            algorithm's block size. If CBC mode is
                            selected (by the absence of any mode bits in 
                            the options flags) and no IV is present, a 
                            NULL (all zeroes) IV will be used. This is 
                            ignored if ECB mode is used or if a stream 
                            cipher algorithm is selected. 

so , you could pass nil value to iv parameter

Sakares
  • 606
  • 12
  • 31
0

Take a look to the following links.

AES1 AES2 AES3

You can download source code library from there and use it in your project if you find any of them useful for you.