Related
After upgrading to Xcode 12.0.1 my command line Mac app (written in Swift) for file decryption runs into these errors when trying to build:
Implicit declaration of function 'SecKeyEncrypt' is invalid in C99
Implicit declaration of function 'SecKeyRawSign' is invalid in C99
Implicit declaration of function 'SecKeyDecrypt' is invalid in C99
The en-/de-cryption code (written in Objective C) was taken from https://github.com/ideawu/Objective-C-RSA - it worked just fine in Xcode 11.
It uses this import statement
#import <Security/Security.h>
<Security/Security.h> has a line
#include <Security/SecKey.h>
and in this file, the methods are declared:
#if SEC_OS_IPHONE
/*!
#function SecKeyRawSign
#abstract Given a private key and data to sign, generate a digital
signature.
#param key Private key with which to sign.
#param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
#param dataToSign The data to be signed, typically the digest of the
actual data.
#param dataToSignLen Length of dataToSign in bytes.
#param sig Pointer to buffer in which the signature will be returned.
#param sigLen IN/OUT maximum length of sig buffer on input, actualy
length of sig on output.
#result A result code. See "Security Error Codes" (SecBase.h).
#discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
will be performed prior to signing. If this argument is kSecPaddingNone,
the incoming data will be signed "as is".
When PKCS1 padding is performed, the maximum length of data that can
be signed is the value returned by SecKeyGetBlockSize() - 11.
NOTE: The behavior this function with kSecPaddingNone is undefined if the
first byte of dataToSign is zero; there is no way to verify leading zeroes
as they are discarded during the calculation.
If you want to generate a proper PKCS1 style signature with DER encoding
of the digest type - and the dataToSign is a SHA1 digest - use
kSecPaddingPKCS1SHA1.
*/
OSStatus SecKeyRawSign(
SecKeyRef key,
SecPadding padding,
const uint8_t *dataToSign,
size_t dataToSignLen,
uint8_t *sig,
size_t *sigLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
/*!
#function SecKeyRawVerify
#abstract Given a public key, data which has been signed, and a signature,
verify the signature.
#param key Public key with which to verify the signature.
#param padding See Padding Types above, typically kSecPaddingPKCS1SHA1.
#param signedData The data over which sig is being verified, typically
the digest of the actual data.
#param signedDataLen Length of signedData in bytes.
#param sig Pointer to the signature to verify.
#param sigLen Length of sig in bytes.
#result A result code. See "Security Error Codes" (SecBase.h).
#discussion If the padding argument is kSecPaddingPKCS1, PKCS1 padding
will be checked during verification. If this argument is kSecPaddingNone,
the incoming data will be compared directly to sig.
If you are verifying a proper PKCS1-style signature, with DER encoding
of the digest type - and the signedData is a SHA1 digest - use
kSecPaddingPKCS1SHA1.
*/
OSStatus SecKeyRawVerify(
SecKeyRef key,
SecPadding padding,
const uint8_t *signedData,
size_t signedDataLen,
const uint8_t *sig,
size_t sigLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
/*!
#function SecKeyEncrypt
#abstract Encrypt a block of plaintext.
#param key Public key with which to encrypt the data.
#param padding See Padding Types above, typically kSecPaddingPKCS1.
#param plainText The data to encrypt.
#param plainTextLen Length of plainText in bytes, this must be less
or equal to the value returned by SecKeyGetBlockSize().
#param cipherText Pointer to the output buffer.
#param cipherTextLen On input, specifies how much space is available at
cipherText; on return, it is the actual number of cipherText bytes written.
#result A result code. See "Security Error Codes" (SecBase.h).
#discussion If the padding argument is kSecPaddingPKCS1 or kSecPaddingOAEP,
PKCS1 (respectively kSecPaddingOAEP) padding will be performed prior to encryption.
If this argument is kSecPaddingNone, the incoming data will be encrypted "as is".
kSecPaddingOAEP is the recommended value. Other value are not recommended
for security reason (Padding attack or malleability).
When PKCS1 padding is performed, the maximum length of data that can
be encrypted is the value returned by SecKeyGetBlockSize() - 11.
When memory usage is a critical issue, note that the input buffer
(plainText) can be the same as the output buffer (cipherText).
*/
OSStatus SecKeyEncrypt(
SecKeyRef key,
SecPadding padding,
const uint8_t *plainText,
size_t plainTextLen,
uint8_t *cipherText,
size_t *cipherTextLen)
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
/*!
#function SecKeyDecrypt
#abstract Decrypt a block of ciphertext.
#param key Private key with which to decrypt the data.
#param padding See Padding Types above, typically kSecPaddingPKCS1.
#param cipherText The data to decrypt.
#param cipherTextLen Length of cipherText in bytes, this must be less
or equal to the value returned by SecKeyGetBlockSize().
#param plainText Pointer to the output buffer.
#param plainTextLen On input, specifies how much space is available at
plainText; on return, it is the actual number of plainText bytes written.
#result A result code. See "Security Error Codes" (SecBase.h).
#discussion If the padding argument is kSecPaddingPKCS1 or kSecPaddingOAEP,
the corresponding padding will be removed after decryption.
If this argument is kSecPaddingNone, the decrypted data will be returned "as is".
When memory usage is a critical issue, note that the input buffer
(plainText) can be the same as the output buffer (cipherText).
*/
OSStatus SecKeyDecrypt(
SecKeyRef key, /* Private key */
SecPadding padding, /* kSecPaddingNone,
kSecPaddingPKCS1,
kSecPaddingOAEP */
const uint8_t *cipherText,
size_t cipherTextLen, /* length of cipherText */
uint8_t *plainText,
size_t *plainTextLen) /* IN/OUT */
__OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_2_0);
#endif // SEC_OS_IPHONE
The method for decryption where the error is raised looks like this:
+ (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
UInt8 *outbuf = malloc(block_size);
size_t src_block_size = block_size;
NSMutableData *ret = [[NSMutableData alloc] init];
for(int idx=0; idx<srclen; idx+=src_block_size){
//NSLog(#"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
size_t data_len = srclen - idx;
if(data_len > src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyDecrypt(keyRef, // <<<<<<<<<<<<<<<<<<<<<< This raises the error
kSecPaddingNone,
srcbuf + idx,
data_len,
outbuf,
&outlen
);
if (status != 0) {
NSLog(#"SecKeyEncrypt fail. Error Code: %d", status);
ret = nil;
break;
}else{
//the actual decrypted data is in the middle, locate it!
int idxFirstZero = -1;
int idxNextZero = (int)outlen;
for ( int i = 0; i < outlen; i++ ) {
if ( outbuf[i] == 0 ) {
if ( idxFirstZero < 0 ) {
idxFirstZero = i;
} else {
idxNextZero = i;
break;
}
}
}
[ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}
It seems that the en-/de-cryption functions cannot be called directly anymore. I am not sure what has changed here - is the problem due to a change in Xcode? And more importantly: how can this problem be fixed? (I am on Catalina 10.15.6)
Any help is highly appreciated! (Please let me know if some information is missing.)
As Phillip Mills pointed out, there is an #if SEC_OS_IPHONE conditional in the Security/SecKey.h include and indeed, if I create an iOS app instead of Mac app, the project can be built without errors. So I assume the conditional has been introduced with Xcode 12 and functions like SecKeyEncrypt and SecKeyDecrypt cannot be called on macOS anymore (unless Mac Catalyst) - maybe have never been supported officially.
Anyway, I have now added OpenSSL via CocoaPods and got the decryption part working. In case you are interested, my header file RSACryptoOpenSSL.h looks like this:
#import <Foundation/Foundation.h>
#import <openssl/bio.h>
#import <openssl/pem.h>
NS_ASSUME_NONNULL_BEGIN
#interface RSACryptoOpenSSL : NSObject
+ (NSString *)decryptMacOsString:(NSString *)str privateKey:(NSString *)privKey;
#end
NS_ASSUME_NONNULL_END
and the implementation file like this
#import "RSACryptoOpenSSL.h"
#implementation RSACryptoOpenSSL
+ (NSString *)decryptMacOsString:(NSString *)str privateKey:(NSString *)privKey
{
NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
// load private key
const char *private_key = [privKey UTF8String];
BIO *bio = BIO_new_mem_buf((void*)private_key, (int)strlen(private_key));
RSA *rsa_privatekey = PEM_read_bio_RSAPrivateKey(bio, NULL, 0, NULL);
BIO_free(bio);
int maxSize = RSA_size(rsa_privatekey);
unsigned char *output = (unsigned char *) malloc(maxSize * sizeof(char));
int bytes __unused = RSA_private_decrypt((int)[data length], [data bytes], output, rsa_privatekey, RSA_PKCS1_PADDING);
NSString *ret = [NSString stringWithUTF8String:(char *)output];
return ret;
}
#end
Thanks to doginthehat and timburks for the valuable information.
If the below code is compiled with UNICODE as compiler option, the GetComputerNameEx API returns junk characters.
Whereas if compiled without UNICODE option, the API returns truncated value of the hostname.
This issue is mostly seen with Asia-Pacific languages like Chinese, Japanese, Korean to name a few (i.e., non-English).
Can anyone throw some light on how this issue can be resolved.
# define INFO_SIZE 30
int main()
{
int ret;
TCHAR infoBuf[INFO_SIZE+1];
DWORD bufSize = (INFO_SIZE+1);
char *buf;
buf = (char *) malloc(INFO_SIZE+1);
if (!GetComputerNameEx((COMPUTER_NAME_FORMAT)1,
(LPTSTR)infoBuf, &bufSize))
{
printf("GetComputerNameEx failed (%d)\n", GetLastError());
return -1;
}
ret = wcstombs(buf, infoBuf, (INFO_SIZE+1));
buf[INFO_SIZE] = '\0';
return 0;
}
In the languages you mentioned, most characters are represented by more than one byte. This is because these languages have alphabets of much more than 256 characters. So you may need more than 30 bytes to encode 30 characters.
The usual pattern for calling a function like wcstombs goes like this: first get the amount of bytes required, then allocate a buffer, then convert the string.
(edit: that actually relies on a POSIX extension, which also got implemented on Windows)
size_t size = wcstombs(NULL, infoBuf, 0);
if (size == (size_t) -1) {
// some character can't be converted
}
char *buf = new char[size + 1];
size = wcstombs(buf, infoBuf, size + 1);
I'm trying to encrypt string in Xcode to PHP with AES128 method by using following code:
Xcode
- (NSData*)AES256EncryptWithKey:(NSString*)key {
char keyPtr[kCCKeySizeAES256];
[key cStringUsingEncoding:NSASCIIStringEncoding];
NSString *iv = #"fdsfds85435nfdfs";
char ivPtr[kCCKeySizeAES128];
[iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSASCIIStringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, NULL,
keyPtr, kCCKeySizeAES256,
ivPtr,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
But when I run above coding, following result is not what I expect to be:
NSString *key = #"89432hjfsd891787";
NSData *plaintext = [[#"aaa0000000000000" dataUsingEncoding:NSASCIIStringEncoding] AES256EncryptWithKey: key];
NSString *mystring = [[NSString alloc] initWithData:plaintext encoding:NSASCIIStringEncoding];
NSLog(#"mystring %#", mystring);
OUTPUT is
uçó)â½S/èRÅ
What I want it something like that.
m9FNGM9IiwibWFjIjoiNmJkYzNmZTA5
Note: due to a coding error the keyPtr is not set to the key value, it becomes the value of the uninitialized memory.
You get "uçó)â½S/èRÅ" because you try to create a string from the data and there are a couple reasons this will not work.
Many data bytes do not map to printable ASCII characters or to any unicode character.
A data byte can be 0 (1 in 256 bytes on average will be 0x00) and that is a terminator for a "C" string so the string will be short.
There are two general conventions for encoding data into a string representation:
Hex-ascii where each data byte is encoded into two characters 0-9a-f.
Base64 where each 3 data data bytes are encoded into 4 ASCII characters.
You are probably looking for Base64 encoding:
NSString *mystring = [plaintext base64EncodedStringWithOptions:0];
Other errors in the code:
[key cStringUsingEncoding:NSASCIIStringEncoding]; The string may not be ASCII, better to use NSUTF8StringEncoding. Note that the output is not captured.
The keyPtr is never set to the key value, see above.
The key size id specified as 256-bits (32-bytes) but the key is 16 characters, use a key size that matched the key.
char ivPtr[kCCKeySizeAES128], an iv size is the block size not the key size: kCCBlockSizeAES128.
Looks like you want a Base64 encoded string.
NSString *mystring = [plaintext base64EncodedStringWithOptions:0];
I have a basic notes app, and I want to allow the user to have encrypted or secure notes. I have an UI whipped up, but right now, I can't seem to get encryption working. Either it returns me a bunch of garbage or nothing at all. This is what I use to en/decrypt:
- (BOOL) encryptWithAES128Key: (NSString *) key {
// 'key' should be 16 bytes for AES128, will be null-padded otherwise
char * keyPtr[kCCKeySizeAES128+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];
// encrypts in-place, since this is a mutable data object
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128 , kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self mutableBytes], [self length], /* input */
[self mutableBytes], [self length] + kCCBlockSizeAES128, /* output */
&numBytesEncrypted);
return (result == kCCSuccess);
}
- (NSMutableData *) decryptWithAES128Key: (NSString *) key {
// 'key' should be 16 bytes for AES128, will be null-padded otherwise
char * keyPtr[kCCKeySizeAES128+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];
// encrypts in-place, since this is a mutable data object
size_t bufferSize = [self length] + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
size_t numBytesEncrypted = 0;
CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES128,
NULL /* initialization vector (optional) */,
[self bytes], [self length], /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if(result == kCCSuccess || result == kCCParamError) {
return [[NSMutableData dataWithBytesNoCopy:buffer length:numBytesEncrypted] retain];
}
return nil;
}
Does anyone have any idea why this might be going wrong?
Edit 1:
I've revised my en/decryption code to be the same. Here is how it looks right now:
- (BOOL) encryptWithAES128Key: (NSString *) key {
CCCryptorStatus ccStatus = kCCSuccess;
// Symmetric crypto reference.
CCCryptorRef thisEncipher = NULL;
// Cipher Text container.
NSData * cipherOrPlainText = nil;
// Pointer to output buffer.
uint8_t * bufferPtr = NULL;
// Total size of the buffer.
size_t bufferPtrSize = 0;
// Remaining bytes to be performed on.
size_t remainingBytes = 0;
// Number of bytes moved to buffer.
size_t movedBytes = 0;
// Length of plainText buffer.
size_t plainTextBufferSize = 0;
// Placeholder for total written.
size_t totalBytesWritten = 0;
// A friendly helper pointer.
uint8_t * ptr;
// Initialization vector; dummy in this case 0's.
uint8_t iv[kCCBlockSizeAES128];
memset((void *) iv, 0x0, (size_t) sizeof(iv));
plainTextBufferSize = [self length];
ccStatus = CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, (const void *)[key UTF8String], kCCKeySizeAES128, (const void *)iv, &thisEncipher);
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Allocate buffer.
bufferPtr = [self mutableBytes];
// Zero out buffer.
//memset((void *)bufferPtr, 0x0, bufferPtrSize);
// Initialize some necessary book keeping.
ptr = bufferPtr;
// Set up initial size.
remainingBytes = bufferPtrSize;
// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate(thisEncipher, (const void *) [self bytes], plainTextBufferSize, ptr, remainingBytes, &movedBytes);
ptr += movedBytes;
remainingBytes -= movedBytes;
totalBytesWritten += movedBytes;
// Finalize everything to the output buffer.
ccStatus = CCCryptorFinal(thisEncipher, ptr, remainingBytes, &movedBytes);
cipherOrPlainText = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)totalBytesWritten];
NSLog(#"data: %#", cipherOrPlainText);
NSLog(#"buffer: %s", bufferPtr);
CCCryptorRelease(thisEncipher);
thisEncipher = NULL;
if(bufferPtr) free(bufferPtr);
}
- (NSMutableData *) decryptWithAES128Key: (NSString *) key {
CCCryptorStatus ccStatus = kCCSuccess;
// Symmetric crypto reference.
CCCryptorRef thisEncipher = NULL;
// Cipher Text container.
NSData * cipherOrPlainText = nil;
// Pointer to output buffer.
uint8_t * bufferPtr = NULL;
// Total size of the buffer.
size_t bufferPtrSize = 0;
// Remaining bytes to be performed on.
size_t remainingBytes = 0;
// Number of bytes moved to buffer.
size_t movedBytes = 0;
// Length of plainText buffer.
size_t plainTextBufferSize = 0;
// Placeholder for total written.
size_t totalBytesWritten = 0;
// A friendly helper pointer.
uint8_t * ptr;
// Initialization vector; dummy in this case 0's.
uint8_t iv[kCCBlockSizeAES128];
memset((void *) iv, 0x0, (size_t) sizeof(iv));
plainTextBufferSize = [self length];
ccStatus = CCCryptorCreate(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, (const void *)[key UTF8String], kCCKeySizeAES128, (const void *)iv, &thisEncipher);
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Allocate buffer.
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t) );
// Zero out buffer.
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// Initialize some necessary book keeping.
ptr = bufferPtr;
// Set up initial size.
remainingBytes = bufferPtrSize;
// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate(thisEncipher, (const void *) [self bytes], plainTextBufferSize, ptr, remainingBytes, &movedBytes);
ptr += movedBytes;
remainingBytes -= movedBytes;
totalBytesWritten += movedBytes;
// Finalize everything to the output buffer.
ccStatus = CCCryptorFinal(thisEncipher, ptr, remainingBytes, &movedBytes);
cipherOrPlainText = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)totalBytesWritten];
NSLog(#"data: %#", cipherOrPlainText);
NSLog(#"buffer: %s", bufferPtr);
CCCryptorRelease(thisEncipher);
thisEncipher = NULL;
if(bufferPtr) free(bufferPtr);
return [NSMutableData dataWithData:cipherOrPlainText];
}
This code somewhat works. If I encrypt this string with the passphrase '1234567890123456':
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>dict</key>
<dict>
<key>device</key>
<string>Tristan's Magical Macbook of Death</string>
<key>text</key>
<string>e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcY29jb2FydGYxMDM4XGNvY29hc3VicnRm
MzYwCntcZm9udHRibFxmMFxmc3dpc3NcZmNoYXJzZXQwIEhlbHZldGljYTt9Cntc
Y29sb3J0Ymw7XHJlZDI1NVxncmVlbjI1NVxibHVlMjU1O30KXHBhcmRcdHg1NjBc
dHgxMTIwXHR4MTY4MFx0eDIyNDBcdHgyODAwXHR4MzM2MFx0eDM5MjBcdHg0NDgw
XHR4NTA0MFx0eDU2MDBcdHg2MTYwXHR4NjcyMFxxbFxxbmF0dXJhbFxwYXJkaXJu
YXR1cmFsCgpcZjBcZnMyNCBcY2YwIFx1bCBcdWxjMCBCTEFILn0=
</string>
<key>title</key>
<string>Welcome to Notepaddy!</string>
<key>uuid</key>
<string>5yvghz9n4ukgefnbx0qa2xne3nxeebcmcvpci9j5lwpncul1asftdayjv8a</string>
</dict>
<key>text</key>
<string>e1xydGYxXGFuc2lcYW5zaWNwZzEyNTJcY29jb2FydGYxMDM4XGNvY29hc3VicnRm
MzYwCntcZm9udHRibFxmMFxmc3dpc3NcZmNoYXJzZXQwIEhlbHZldGljYTt9Cntc
Y29sb3J0Ymw7XHJlZDI1NVxncmVlbjI1NVxibHVlMjU1O30KXHBhcmRcdHg1NjBc
dHgxMTIwXHR4MTY4MFx0eDIyNDBcdHgyODAwXHR4MzM2MFx0eDM5MjBcdHg0NDgw
XHR4NTA0MFx0eDU2MDBcdHg2MTYwXHR4NjcyMFxxbFxxbmF0dXJhbFxwYXJkaXJu
YXR1cmFsCgpcZjBcZnMyNCBcY2YwIFx1bCBcdWxjMCBCTEFILn0=
</string>
<key>title</key>
<string>Welcome to Notepaddy!</string>
<key>uuid</key>
<string>5yvghz9n4ukgefnbx0qa2xne3nxeebcmcvpci9j5lwpncul1asftdayjv8a</string>
</dict>
</plist>
I get the same text back, but the entire </plist> is missing and the </dict> is cut off. Decrypting and printing the result string out gives me complete garbage when encrypted with the passphrase '0987654321123456' or any other passphrase, or the same as above when copied into the password field.
Both versions have the same problem: You tell CommonCrypto to write past the end of your buffer, and then you ignore the result.
The first version:
[self mutableBytes], [self length] + kCCBlockSizeAES128, /* output */
The second version:
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Allocate buffer.
bufferPtr = [self mutableBytes];
That's not right. You're not allocating anything. You're telling it to write bufferPtrSize bytes to a buffer of size [self length]!
You want to do something more like this (if you really want to encrypt in-place):
// Calculate byte block alignment for all calls through to and including final.
bufferPtrSize = CCCryptorGetOutputLength(thisEncipher, plainTextBufferSize, true);
// Increase my size if necessary:
if (bufferPtrSize > self.length) {
self.length = bufferPtrSize;
}
I'm also not sure why encrypting is in-place while decrypting is not; the latter is, if anything, easier to do.
Your second version has an additional problems:
You free something you didn't allocate: if(bufferPtr) free(bufferPtr);
You potentially read past the end of the string: (const void *)[key UTF8String], kCCKeySizeAES128
Additional crypto problems:
Keys are supposed to be fixed-size and have a decent amount of entropy. Naively converting a string to bytes does not a good key make (for one, keys longer than 16 bytes are effectively truncated). The least you could do is hash it. You might also want to iterate the hash, or just use PBKDF2 (admittedly I haven't found the spec/test vectors for PBKDF2...)
You almost certainly want to use a random IV too (see SecRandomCopyBytes).
Addendum:
The reason why you're seeing a truncated result is because you're returning a truncated answer (with PKCS7 padding, the encrypted result is always bigger than the original data). Chances (about 255/256) are that the last ciphertext block was incorrectly padded (because you gave CCryptor truncated data), so ccStatus says an error happened but you ignored this and returned the result anyway. This is incredibly bad practice. (Additionally, you really want to use a MAC with CBC to avoid the padding oracle security hole.)
EDIT:
Some code that seems to work looks something like this (complete with test cases):
Notes:
Not actually tested on iOS (though the non-iOS code should work on iOS; it's just that SecRandomCopyBytes is a slightly nicer interface but not available on OS X).
The read() loop might be right, but is not thoroughly tested.
The ciphertext is prefixed with the IV. This is the "textbook" method, but makes ciphertexts bigger.
There is no authentication, so this code can act as a padding oracle.
There is no support for AES-192 or AES-256. It would not be difficult to add (you'd just need to switch on the key length and pick the algorithm appropriately).
The key is specified as a NSData, so you'll need to do something like [string dataUsingEncoding:NSUTF8StringEncoding]. For bonus points, run it through CC_SHA256 and take the first 16 output bytes.
There's no in-place operation. I didn't think it was worth it.
.
#include <Foundation/Foundation.h>
#include <CommonCrypto/CommonCryptor.h>
#if TARGET_OS_IPHONE
#include <Security/SecRandom.h>
#else
#include <fcntl.h>
#include <unistd.h>
#endif
#interface NSData(AES)
- (NSData*) encryptedDataUsingAESKey: (NSData *) key;
- (NSData*) decryptedDataUsingAESKey: (NSData *) key;
#end
#implementation NSData(AES)
- (NSData*) encryptedDataUsingAESKey: (NSData *) key {
uint8_t iv[kCCBlockSizeAES128];
#if TARGET_OS_IPHONE
if (0 != SecRandomCopyBytes(kSecRandomDefault, sizeof(iv), iv))
{
return nil;
}
#else
{
int fd = open("/dev/urandom", O_RDONLY);
if (fd < 0) { return nil; }
ssize_t bytesRead;
for (uint8_t * p = iv; (bytesRead = read(fd,p,iv+sizeof(iv)-p)); p += (size_t)bytesRead) {
// 0 means EOF.
if (bytesRead == 0) { close(fd); return nil; }
// -1, EINTR means we got a system call before any data could be read.
// Pretend we read 0 bytes (since we already handled EOF).
if (bytesRead < 0 && errno == EINTR) { bytesRead = 0; }
// Other errors are real errors.
if (bytesRead < 0) { close(fd); return nil; }
}
close(fd);
}
#endif
size_t retSize = 0;
CCCryptorStatus result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length],
iv,
[self bytes], [self length],
NULL, 0,
&retSize);
if (result != kCCBufferTooSmall) { return nil; }
// Prefix the data with the IV (the textbook method).
// This requires adding sizeof(iv) in a few places later; oh well.
void * retPtr = malloc(retSize+sizeof(iv));
if (!retPtr) { return nil; }
// Copy the IV.
memcpy(retPtr, iv, sizeof(iv));
result = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length],
iv,
[self bytes], [self length],
retPtr+sizeof(iv),retSize,
&retSize);
if (result != kCCSuccess) { free(retPtr); return nil; }
NSData * ret = [NSData dataWithBytesNoCopy:retPtr length:retSize+sizeof(iv)];
// Does +[NSData dataWithBytesNoCopy:length:] free if allocation of the NSData fails?
// Assume it does.
if (!ret) { free(retPtr); return nil; }
return ret;
}
- (NSData*) decryptedDataUsingAESKey: (NSData *) key {
const uint8_t * p = [self bytes];
size_t length = [self length];
if (length < kCCBlockSizeAES128) { return nil; }
size_t retSize = 0;
CCCryptorStatus result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length],
p,
p+kCCBlockSizeAES128, length-kCCBlockSizeAES128,
NULL, 0,
&retSize);
if (result != kCCBufferTooSmall) { return nil; }
void * retPtr = malloc(retSize);
if (!retPtr) { return nil; }
result = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[key bytes], [key length],
p,
p+kCCBlockSizeAES128, length-kCCBlockSizeAES128,
retPtr, retSize,
&retSize);
if (result != kCCSuccess) { free(retPtr); return nil; }
NSData * ret = [NSData dataWithBytesNoCopy:retPtr length:retSize];
// Does +[NSData dataWithBytesNoCopy:length:] free if allocation of the NSData fails?
// Assume it does.
if (!ret) { free(retPtr); return nil; }
return ret;
}
#end
void test(NSData * data, NSData * key)
{
NSLog(#"%#, %#", data, key);
NSData * enc = [data encryptedDataUsingAESKey:key];
NSLog(#"%#", enc);
NSData * dec = [enc decryptedDataUsingAESKey:key];
NSLog(#"%#", dec);
NSLog((data == dec || [data isEqual:dec]) ? #"pass" : #"FAIL");
}
int main()
{
#define d(x) [NSData dataWithBytesNoCopy:("" x) length:sizeof("" x)-1 freeWhenDone:0]
[NSAutoreleasePool new];
NSData * key = d("0123456789abcdef");
test([NSData data], key);
test(d(""), key);
test(d("a"), key);
test(d("0123456789abcde"), key);
test(d("0123456789abcdef"), key);
test(d("0123456789abcdef0"), key);
test(d("0123456789abcdef0123456789abcde"), key);
test(d("0123456789abcdef0123456789abcdef"), key);
test(d("0123456789abcdef0123456789abcdef0"), key);
}
Regarding your *de*cryption code
kCCParamError is, as its name says, an error. Why are you treating it as success? If you get that error, it means you did something wrong; look at the parameters you passed and figure out what.
This is probably why you're getting “garbage”: CCCrypt (decrypting) never actually gave you anything, because it could not work with whatever values you gave it. What you're getting is whatever was lying around in the output buffer when you allocated it.
If you switch to calloc or to creating the NSMutableData object before calling CCCrypt and using its mutableBytes as the buffer, I think you'll find that the buffer then always contains all zeroes. Same reason: CCCrypt is not filling it out, because it's failing, because you passed one or more wrong values (parameter error).
You need to fix the parameter error before you can expect this to work.
You might try breaking the CCCrypt call into calls to CCCryptorCreate, CCCryptorUpdate, CCCryptorFinal, and CCCryptorRelease, at least temporarily, to see where it's going wrong.
Encryption: The same problem, or no problem at all
Is your encryption method returning YES or NO? I'm guessing it returns NO, because the code appears to be mostly the same between the encryption and decryption methods, so whatever you have wrong in your decryption code is probably wrong in your encryption code as well. See what CCCrypt is returning and, if it's failing, get it working.
If it is returning YES (CCCrypt is succeeding), then I wonder what you mean by “returns me a bunch of garbage”. Are you referring to the contents of the data object you sent the encryptWithAES128Key: message to?
If that's the case, then that is the expected result. Your code encrypts the contents of the data object in place, overwriting the cleartext with the ciphertext. What you're seeing isn't pure “garbage”—it's the ciphertext! Decrypting it (successfully) will reveal the cleartext again.
By the way, you have the “encrypts in-place, since this is a mutable data object” comment on the creation of an output buffer in order to not work in-place in the decryption code. It should be in the encryption method, where you are working in-place. I suggest making either both work in-place or neither work in-place; consistency is a virtue.
If you have following padding changes in your code remove it and always keep kCCOptionPKCS7Padding on, this should solve your issue.
if (encryptOrDecrypt == kCCEncrypt) {
if (*pkcs7 != kCCOptionECBMode) {
if ((plainTextBufferSize % kChosenCipherBlockSize) == 0) {
*pkcs7 = 0x0000;
} else {
*pkcs7 = kCCOptionPKCS7Padding;
}
}
}
You should use RNCryptor, it's high level encryption opensource api around CommonCrypto, and high level encryption API's are the best practice for cryptography these days, because it's easy for experts to make mistakes in the implementations using crypto primatives, and there are alot of side channel attacks out there that take advantage of those mistakes.
For example, you code says /* initialization vector (optional) * / 100% not true, thus you've totally crippled AES-CBC, and that's just the most obvious issue.
In your case RNCryptor is ideal, I'd strongly suggest you don't roll your own implementation.
I am searching for some cocoa code on AES encryption and I did some google search for it. I found this very useful link -
http://iphonedevelopment.blogspot.com/2009/02/strong-encryption-for-cocoa-cocoa-touch.html. So I tried it but it did not work for me.
Can anyone suggest me some useful link or source code which can help me to implement it in my sample application.
I use a simple category on NSData that uses the built-in CommonCrypto framework to do AES 256-bit encryption. I use this on the Mac but it should work OK on iPhone too:
#import <CommonCrypto/CommonCryptor.h>
#implementation NSData (AESAdditions)
- (NSData*)AES256EncryptWithKey:(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 numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[self bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesEncrypted);
if (cryptStatus == kCCSuccess)
{
//the returned NSData takes ownership of the buffer and will free it on deallocation
return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (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;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 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 [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
}
free(buffer); //free the buffer;
return nil;
}
#end
AES128 encryption is available on the iPhone in the CommonCrypto framework. The relevant functions are in the CommonCryptor.h header.
You can create a cryptor like so:
// Assume key and keylength exist
CCCryptorRef cryptor;
if(kCCSuccess != CCCryptorCreate(kCCEncrypt, kCCAlgorithmAES128, 0, key, keyLength, NULL, &cryptor))
; //handle error
// Repeatedly call CCCryptorUpdate to encrypt the data
CCCryptorRelease(cryptor);
It seems from the question and the link that you are looking for example implementations of AES. I would not recommend this- use Apple's implementation!
It looks like http://pastie.org/297563.txt might help you also, but I haven't tested it.
All examples I found didn't work for me, so I changed the solution above. This one works for me and uses the Google-Lib for Base64 stuff:
+ (NSData *)AES256DecryptWithKey:(NSString *)key data:(NSData*)data encryptOrDecrypt:(CCOperation)encryptOrDecrypt {
// '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];
if (encryptOrDecrypt == kCCDecrypt)
{
data = [GTMBase64 decodeData:data];
}
NSUInteger dataLength = [data 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;
CCCryptorStatus cryptStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding,
keyPtr,
kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[data bytes], dataLength, /* input */
buffer, bufferSize, /* output */
&numBytesDecrypted);
if (cryptStatus != kCCSuccess){
NSLog(#"ERROR WITH FILE ENCRYPTION / DECRYPTION");
return nil;
}
NSData *result;
if (encryptOrDecrypt == kCCDecrypt)
{
result = [NSData dataWithBytes:(const void *)buffer length:(NSUInteger)numBytesDecrypted];
}
else
{
NSData *myData = [NSData dataWithBytes:(const void *)buffer length:(NSUInteger)numBytesDecrypted];
result = [GTMBase64 encodeData:myData];
}
free(buffer); //free the buffer;
return result;
}
thanks for the great category extension. One thing that I've discovered - when you use CCCrypt with an algorithm stronger then 64 bit, you need to be compliant to the BIS export regulations. See the iTunes Connect FAQ for more details. Even if you use Apple's inbuild crypto api you need to get approval from the BIS.
There was a discussion on sf about this topic before (in context of ssl usage):
Using SSL in an iPhone App - Export Compliance
Best Regards
Chris