Welcome!

Welcome to the official BlackBerry Support Community Forums.

This is your resource to discuss support topics with your peers, and learn from each other.

inside custom component

Native Development

Reply
Developer
Posts: 216
Registered: ‎09-18-2009
My Device: Z10
My Carrier: O2
Accepted Solution

PKCS5 padding with AES

I use the AES cipher including the header huaes.h. Operation mode is ECB. Encryption and decryption on the device works fine. But I want to send the encypted data to a server using PKCS5 padding.

 

How do I set PKCS5 padding?

Developer
Posts: 216
Registered: ‎09-18-2009
My Device: Z10
My Carrier: O2

Re: PKCS5 padding with AES

Since the API does not provide a way to do this I did this manually.

 

For everybody else stumbling upon this issue I want to share my code which adds the padding. All the other code is removed.

 

 

QByteArray Cipher::encrypt(QByteArray & plaintext) {
    int moduloBlockSize = plaintext.length() % SB_AES_128_BLOCK_BYTES;
    int plainTextBlockLength = 0;
    if (moduloBlockSize != 0) {
        int nBlockBytes = plaintext.length() / SB_AES_128_BLOCK_BYTES;
        int plaintextBlockBytes = nBlockBytes * SB_AES_128_BLOCK_BYTES;
        plainTextBlockLength = plaintextBlockBytes + SB_AES_128_BLOCK_BYTES;
    } else {
        plainTextBlockLength = plaintext.length() + SB_AES_128_BLOCK_BYTES;
    }
    unsigned char nPaddingBytes = SB_AES_128_BLOCK_BYTES - moduloBlockSize;
    QByteArray plaintextPaddingQByteArray = QByteArray(nPaddingBytes, nPaddingBytes);
    plaintext.append(plaintextPaddingQByteArray);
}

 

Most other cryptographic libraries like crypto++ pad the plain text by default. Or at least they provide a method to do this.

 

So, I really cannot understand why such a common feature is missing in the native API. Maybe, this should be added to the issue tracker?

Retired
Posts: 418
Registered: ‎07-18-2012
My Device: Q10
My Carrier: Bell Canada

Re: PKCS5 padding with AES

[ Edited ]

Hi,

 

I've pushed an article including padding verification here.

 

If you're not talking to an existing system though;

  • consider avoiding ECB - look at Tux here . Every block is independent. (Padding only protects the final block under ECB!)
  • consider using a MAC or an authenticated mode like AES-GCM
  • keep in mind how weak PKCS5/7 padding is. Random data has > 1/256 chance of being verified as padded correctly.
--
Rob is no longer associated with BlackBerry.