AES ECB iOS Encrypt - ios

I try to encrypt some string using AES algorithm with ECB option.
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode,
encryptionKey, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess) {
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
But func returns kCCAlignmentError (-4303)
Then I try to align data:
unsigned long diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
unsigned long newSize = 0;
if (diff > 0) {
newSize = dataLength + diff;
}
char dataPtr[newSize];
memcpy(dataPtr, [self bytes], [self length]);
for(int i = 0; i < diff; i++) {
dataPtr[i + dataLength] = 0x20;
}
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode,
encryptionKey, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
dataPtr, sizeof(dataPtr), /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
input string
"test_string,test2"
result is
jxtFOhYpgBVieM90zx9oDanqBkcsVAvRRJsM4GL3cio=
On Android result is
jxtFOhYpgBVieM90zx9oDUfV7v43WFv7F5bzErfxrL8=
What did I wrong?

Simply AES is a block cypher which means it requires it's input data to be a multiple of the block size (16-bytes for AES). Your input data is 17 bytes thus th alignment error. (It is not talking about the alignment in memory).
The way to handle this is to specify PKCS#7 padding in the options:
kCCOptionPKCS7Padding | kCCOptionECBMode
The input data will be padded to a block multiple and on decryption the padding will be removed. To allow this on encryption it is necessary to increase the output buffer by one block size.
Consider not using [ECB mode](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_.28ECB.29 (Scroll down to the Penguin), it is not secure.
If you are using mcrypt on Android: don't, it is abandonware and does not support standard padding, only null padding. Instead consider defuse or RNCryptor which is a full secure implementation is is available for iOS and Java.
If you do use mcrypt you will need to add your own PKCS#7 padding.
Here is example code:
+ (NSData *)doCipher:(NSData *)dataIn
key:(NSData *)symmetricKey
context:(CCOperation)encryptOrDecrypt // kCCEncrypt or kCCDecrypt
{
CCCryptorStatus ccStatus = kCCSuccess;
size_t cryptBytes = 0; // Number of bytes moved to buffer.
NSMutableData *dataOut = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];
ccStatus = CCCrypt( encryptOrDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
symmetricKey.bytes,
kCCKeySizeAES128,
0,
dataIn.bytes, dataIn.length,
dataOut.mutableBytes, dataOut.length,
&cryptBytes);
if (ccStatus != kCCSuccess) {
NSLog(#"CCCrypt status: %d", ccStatus);
}
dataOut.length = cryptBytes;
return dataOut;
}
Example PHP PKCS#7 padding:
Add PKCS#7 padding
$padLength = $blockSize - (strlen($clearText) % $blockSize);
$clearText = $clearText . str_repeat(chr($padLength), $padLength);
Strip PKCS#7 padding
$padLength = ord($cryptText[strlen($cryptText)-1]);
$cryptText = substr($cryptText, 0, strlen($cryptText) - $padLength);

Although AES/ECB is not really recommended. This post explains why there's an alignment error and how to deal with it.
Alignment error almost means there is something wrong with the sizes.
Why is there an error?
A block cipher works on units of a fixed size (known as a block size), but messages come in a variety of lengths. So some modes (namely ECB and CBC) require that the final block be padded before encryption. (Source: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_(ECB) )
Since AES ECB doesn't do the padding for you, you have to process the raw data before encrypting it.
Of course you can use kCCOptionPKCS7Padding when permitted, but since this thread is talking about ECB mode and alignment error, let's just focus on how to pad the data.
How many bytes should I pad?
The number of plain data bytes has to be an integral multiple of the current algorithm's block size.
That is, if your block size is kCCBlockSizeAES128 (16), you have to pad your data into "the nearest multiple of the block size" (16*n).
For example,
if your data is "abc" (3 bytes),
then you have to pad your data into 16 bytes;
if your data is "1234567890123456" (16 bytes),
then you have to pad it into 32 bytes.
0 ~ 15 bytes => pad to 16 bytes
16 ~ 31 bytes => pad to 32 bytes
32 ~ 47 bytes => pad to 48 bytes
... and so on
What is the value of the bytes to be padded?
If you have to pad 1 byte, then the 1 byte you pad would be '01';
If you have to pad 2 bytes, then the 2 bytes you pad would be '02';
...
If you have to pad 16 bytes, then the 16 bytes you pad would be '10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10'
Example of raw data and padded data before encryption
Example 1. (under block size 16)
Original data string: "abc" (3 bytes)
Data Bytes: "61 62 63"
Padded Data Bytes: "61 62 63 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d 0d"
Explanation:
Data are 3 bytes, so the nearest multiple of the block size is 16 bytes.
So there are 13 bytes to be padded.
And 13 in hex would be 0xd, so '0d' is padded for 13 times.
Let's have another example of data that is exactly a multiple of block size.
Example 2. (under block size 16)
Original data string: "1234567890123456" (16 bytes)
Data Bytes: "31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36"
Padded Data Bytes: "31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10"
Explanation:
Data are 16 bytes, so the nearest multiple of the block size is 32 bytes.
So there are 16 bytes to be padded.
And 16 in hex would be 0x10, so '10' is padded for 16 times.
To pad the data in Objective-C
Here is an example of how to pad your data when using AES/ECB encryption mode:
+ (NSData *)addPaddingBeforeEncryptWithAESECB:(NSData *) data{
//Length has to be the nearest multiple of the block size
int cipherLen = (int)(data.length/kAlgorithmBlockSize + 1)*kAlgorithmBlockSize;
NSMutableData *newData = [NSMutableData dataWithLength:cipherLen];
newData = [data mutableCopy];
//How many bytes to be padded
int bytesToAddOn = kAlgorithmBlockSize - data.length%kAlgorithmBlockSize;
//Each byte in hex
char byteToAdd = bytesToAddOn & 0xff;
char *buffer = malloc(bytesToAddOn * sizeof byteToAdd);
memset (buffer, byteToAdd, sizeof (char) * bytesToAddOn);
[newData appendBytes:buffer length:bytesToAddOn];
return newData;
}
Full example of AES ECB encryption:
+ (NSData *)encryptDataWithAESECB:(NSData *)data
key:(NSData *) key
error:(NSError **)error {
size_t outLength;
int cipherLen = (int)(data.length/kAlgorithmBlockSize + 1)*kAlgorithmBlockSize;
NSMutableData *cipherData = [NSMutableData dataWithLength:cipherLen];
NSData *newData = [self addPaddingBeforeEncryptWithAESECB:data];
CCCryptorStatus result = CCCrypt(kCCEncrypt, // operation
kAlgorithm, // Algorithm
kCCOptionECBMode, // Mode
key.bytes, // key
key.length, // keylength
0,// iv
newData.bytes, // dataIn
newData.length, // dataInLength,
cipherData.mutableBytes, // dataOut
cipherData.length, // dataOutAvailable
&outLength); // dataOutMoved
if (result == kCCSuccess) {
cipherData.length = outLength;
}else {
if (error) {
*error = [NSError errorWithDomain:kRNCryptManagerErrorDomain code:result userInfo:nil];
}
return nil;
}
return cipherData;
}
What's next?
You have to strip off the extra bytes before AES ECB decryption.

Related

How to decrypt AES 256 https://aesencryption.net/ - IOS

Plain text : Encrypt and decrypt text with AES algorithm
Key (256) : testsecret
Result (https://aesencryption.net/) : iFhSyFY3yYoO2G6GVGkdhZJjD+h0Pxv5fQnO3xIarzuGQSkIxlrpSprC5bC3gJ2U
i use small code in object to decrypt this this text :
(NSData*)AES256DecryptWithKey:(NSString*)key {
// 'key' should be 32 bytes for AES256, will be null-padded otherwise
char keyPtr[kCCKeySizeAES256 + 1]; // room for terminator (unused)
bzero(keyPtr, sizeof(keyPtr)); // fill with zeroes (for padding)
// fetch key data
[key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
//See the doc: For block ciphers, the output size will always be less than or
//equal to the input size plus the size of one block.
//That's why we need to add the size of one block here
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesDecrypted = 0; // char iv[kCCBlockSizeAES128 + 1]; bzero(iv, sizeof(iv)) ;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES, kCCOptionPKCS7Padding ,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) /,
[self bytes], dataLength, / input /
buffer, bufferSize, / output */
&numBytesDecrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSMutableData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil; }
Result : t\PFLFC\^X\^C^\^^\^RWQV\^\ypt text with AES algorithm
Seem it alway wrong first 16bit block. Can u help me. what i'm wrong when encrypt ?
aesencryption.net performs AES in CBC mode. IV is a hardcoded ASCII string (16 chars). Message is UTF8-encoded then PKCS7-padded. AES key is the given password, UTF8-encoded then null-padded to choosen key size (or truncated if password is too long). And of course, the result is displayed as base64.
Getting the IV is as simple as encrypting a given block, decrypting it in ECB mode, and xoring that decrypted block with the original one...
Try to use AESCrypt-ObjC instead of Cryptlib Library.
Installation
Add this line to your class:
#import "AESCrypt.h"
Usage
NSString *message = #"top secret message";
NSString *password = #"p4ssw0rd";
Encrypting
NSString *encryptedData = [AESCrypt encrypt:message password:password];
Decrypting
NSString *message = [AESCrypt decrypt:encryptedData password:password];
Hope this will help.
Also, you can see this answer: https://stackoverflow.com/a/51767050/5167909
Your CCCryptorStatus parameters in osstatus :
should look like this
cryptStatus = CCCrypt( kCCDecrypt, kCCAlgorithmAES128,kCCOptionECBMode + kCCOptionPKCS7Padding, keyPtr, kCCKeySizeAES256 NULL,[self bytes], dataLength, buffer, bufferSize, &numBytesEncrypted );,
However you length of the key is less than 16 bytes. At least make sure that your secret key should be of 16 bytes.

AES/CFB8 IV size

AFAIK, CFB8 mode has block size of 1byte. So I can induce that IV is also 1byte length.
However, when I do a test passing same iv of just 1 byte into common crypto create function for encrypt and decrypt function, encrypted and decrypted message mismatch.
So I think that the API should have taken more than 1 byte to use as IV. I would like to know why? Any thing wrong with my understanding?
CCCryptorStatus result = CCCryptorCreateWithMode(operation,
kCCModeCFB8,
kCCAlgorithmAES128,
ccNoPadding,
iv.bytes,
key.bytes,
key.length,
NULL,
0,
0,
0,
&_cryptor);
if (result == kCCSuccess)
result = CCCryptorUpdate(_cryptor,
data.bytes,
data.length,
cipherData.mutableBytes,
cipherData.length,
&outLength);
if (result == kCCSuccess)
result = CCCryptorFinal(_cryptor,
cipherData.mutableBytes,
cipherData.length,
&outLength);
if (result == kCCSuccess)
result = CCCryptorRelease(_cryptor);
The IV size must match the symmetric algorithm block size. Hence, for AES you should have an IV of 16 bytes.
CFB-8 has a shift size of a byte. It bears no relation to the block size of the cipher.
It doesn't have block size of 1 byte, it is just resynchronized each 1 byte.
The IV is actually 16 bytes (for AES).

get 32 bit number in ios

How to get a 32 bit number in objective c when an byte array is passed to it, similarly as in java where,
ByteBuffer bb = ByteBuffer.wrap(truncation);
return bb.getInt();
Where truncation is the byte array.
It returns 32 bit number.. Is this possible in objective c?
If the number is encoded in little-endian within the buffer, then use:
int32_t getInt32LE(const uint8_t *buffer)
{
int32_t value = 0;
unsigned length = 4;
while (length > 0)
{
value <<= 8;
value |= buffer[--length];
}
return value;
}
If the number is encoded in big-endian within the buffer, then use:
int32_t getInt32BE(const uint8_t *buffer)
{
int32_t value = 0;
for (unsigned i = 0; i < 4; i++)
{
value <<= 8;
value |= *buffer++;
}
return value;
}
UPDATE If you are using data created on the same host then endianness is not an issue, in which case you can use a union as a bridge between the buffer and integers, which avoids some unpleasant casting:
union
{
uint8_t b[sizeof(int32_t)];
int32_t i;
} u;
memcpy(u.b, buffer, sizeof(u.b));
// value is u.i
Depending on the endianness:
uint32_t n = b0 << 24 | b1 << 16 | b2 << 8 | b3;
or
uint32_t n = b3 << 24 | b2 << 16 | b1 << 8 | b0
Not sure if you just want to read 4 bytes and assign that value to an integer. This case:
int32_t number;
memcpy(&number, truncation, sizeof(uint32_t));
About endianess
From your question (for me) was clear that the bytes were already ordered correctly. However if you have to re-order these bytes, use ntohl() after memcpy() :
number=ntohl(number);

Strange SecKeyEncrypt behaviour

I'm trying to implement RSA encryption with PKCS1 padding using SecKeyEncrypt function.
The code is following:
NSData *encryptText(NSString *text, SecKeyRef publicKey)
{
NSCParameterAssert(text.length > 0);
NSCParameterAssert(publicKey != NULL);
NSData *dataToEncrypt = [text dataUsingEncoding:NSUTF8StringEncoding];
const uint8_t *bytesToEncrypt = dataToEncrypt.bytes;
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
NSCAssert(cipherBufferSize > 11, #"block size is too small: %zd", cipherBufferSize);
const size_t inputBlockSize = cipherBufferSize - 11; // since we'll use PKCS1 padding
uint8_t *cipherBuffer = (uint8_t *) malloc(sizeof(uint8_t) * cipherBufferSize);
NSMutableData *accumulator = [[NSMutableData alloc] init];
#try {
for (size_t block = 0; block * inputBlockSize < dataToEncrypt.length; block++) {
size_t blockOffset = block * inputBlockSize;
const uint8_t *chunkToEncrypt = (bytesToEncrypt + block * inputBlockSize);
const size_t remainingSize = dataToEncrypt.length - blockOffset;
const size_t subsize = remainingSize < inputBlockSize ? remainingSize : inputBlockSize;
size_t actualOutputSize = cipherBufferSize;
OSStatus status = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, chunkToEncrypt, subsize, cipherBuffer, &actualOutputSize);
if (status != noErr) {
NSLog(#"Cannot encrypt data, last SecKeyEncrypt status: %ld", status);
return nil;
}
[accumulator appendBytes:cipherBuffer length:actualOutputSize];
}
return [accumulator copy];
}
#finally {
free(cipherBuffer);
}
}
It works perfectly on iOS 6, but fails on iOS 5, SecKeyEncrypt returns -50 (errSecParam). It would work on iOS 5 if I change 11 to 12 in inputBlockSize = cipherBufferSize - 11.
Apple doc says that input chunk length should be less or equal SecKeyGetBlockSize() - 11 if PKCS1 padding used. But on iOS 5 it definitely requires shorter input.
My key block size is 64, so input chunk max length is 53, according to docs. On iOS 5 only 52 or less would work.
What's wrong with this code? Or it's iOS 5 Security.framework bug?
UPD: problem reproduces only with 512-bit key. Tried with generated 1024-bit key, code works on iOS 5 with 11
Related Apple doc: http://developer.apple.com/library/ios/documentation/Security/Reference/certifkeytrustservices/Reference/reference.html#//apple_ref/c/func/SecKeyEncrypt

Why would SecKeyEncrypt return paramErr (-50) for input strings longer than 246 bytes?

I am using SecKeyEncrypt with a JSON formatted string as input. If pass SecKeyEncrypt a plainTextLength of less than 246, it works. If I pass it a length of 246 or more, it fails with return value: paramErr (-50).
It could be a matter of the string itself. An example of what I might send SecKeyEncrypt is:
{"handle":"music-list","sym_key":"MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALeaEO7ZrjgOFGLBzBHZtQuzH2GNDYMLWP+fIFNu5Y+59C6HECY+jt0yOXXom2mzp/WYYI/9G+Ig8OD6YiKv2nMCAwEAAQ==","app_id":"xgfdt.LibraryTestApp","api_key":"7e080f74de3625b90dd293fc8be560a5cdfafc08"}
The 245th character is '0'.
The ONLY input that is changing between this working and is the plainTextLength. SecKeyGetBlockSize() is returning 256 to me, so any input up to 256 characters long should work.
Here is my encrypt method:
+ (NSData*)encrypt:(NSString*)data usingPublicKeyWithTag:(NSString*)tag
{
OSStatus status = noErr;
size_t cipherBufferSize;
uint8_t *cipherBuffer;
// [cipherBufferSize]
size_t dataSize = 246;//[data lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
const uint8_t* textData = [[data dataUsingEncoding:NSUTF8StringEncoding] bytes];
SecKeyRef publicKey = [Encryption copyPublicKeyForTag:tag];
NSAssert(publicKey, #"The public key being referenced by tag must have been stored in the keychain before attempting to encrypt data using it!");
// Allocate a buffer
cipherBufferSize = SecKeyGetBlockSize(publicKey);
// this value will not get modified, whereas cipherBufferSize may.
const size_t fullCipherBufferSize = cipherBufferSize;
cipherBuffer = malloc(cipherBufferSize);
NSMutableData* accumulatedEncryptedData = [NSMutableData dataWithCapacity:0];
// Error handling
for (int ii = 0; ii*fullCipherBufferSize < dataSize; ii++) {
const uint8_t* dataToEncrypt = (textData+(ii*fullCipherBufferSize));
const size_t subsize = (((ii+1)*fullCipherBufferSize) > dataSize) ? fullCipherBufferSize-(((ii+1)*fullCipherBufferSize) - dataSize) : fullCipherBufferSize;
// Encrypt using the public key.
status = SecKeyEncrypt( publicKey,
kSecPaddingPKCS1,
dataToEncrypt,
subsize,
cipherBuffer,
&cipherBufferSize
);
[accumulatedEncryptedData appendBytes:cipherBuffer length:cipherBufferSize];
}
if (publicKey) CFRelease(publicKey);
free(cipherBuffer);
return accumulatedEncryptedData;
}
From the documentation:
plainTextLen
Length in bytes of the data in the plainText buffer. This must be less than or equal to the value returned by the SecKeyGetBlockSize function. When PKCS1 padding is performed, the maximum length of data that can be encrypted is 11 bytes less than the value returned by the SecKeyGetBlockSize function (secKeyGetBlockSize() - 11).
(emphasis mine)
You're using PKCS1 padding. So if the block size is 256, you can only encrypt up to 245 bytes at a time.

Resources