3des encryption in iphone - iphone

i am fairly new to iOS development and objective c.
I am developing an application which will send encrypted data to a server.
The server uses 3des with cbc and no padding.
I have read most of the related questions in stackoverflow but still unable to get it work.
Been working on this for few days but still unable to get it to match with the server encryption.
Here is what i have work out:
NSString* plaintexthex = #"536176696E67204163636F756E747C313233343536000000";
NSData *dTextIn = [self dataFromHexString:plaintexthex]; //my own way of convert hex to data
NSString* keyhex = #"6E7B336FD2051BA165A9362BD9735531";
NSData *_keyData = [self dataFromHexString:keyhex]; //my own way of convert hex to data
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
bufferPtrSize = ([dTextIn length] + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x00, bufferPtrSize);
uint8_t iv[kCCBlockSize3DES];
memset((void *) iv, 0x00, (size_t) sizeof(iv));
unsigned char *bytePtr = (unsigned char *)[_keyData bytes];
ccStatus = CCCrypt(kCCEncrypt, // CCoperation op
kCCAlgorithm3DES, // CCAlgorithm alg
kCCModeCBC, // CCOptions
[_keyData bytes], // const void *key
kCCKeySize3DES, // 3DES key size length 24 bit
iv, // const void *iv,
[dTextIn bytes], // const void *dataIn
[dTextIn length], // size_t dataInLength
bufferPtr, // void *dataOut
bufferPtrSize, // size_t dataOutAvailable
&movedBytes); // size_t *dataOutMoved
NSString *result;
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length: (NSUInteger)movedBytes];
result = [self hexStringFromData:myData];
NSLog(#"Data to encrypt %#",dTextIn);
NSLog(#"Encryption key %#",_keyData);
NSLog(#"Bytes of key are %s ", bytePtr);
NSLog(#"Key length %d ",[_keyData length]);
NSLog(#"Encrypted bytes %#", myData);
NSLog(#"Encrypted string %#", result);
NSLog(#"Encrypted string length %d", [result length]);
- (NSData *)dataFromHexString:(NSString *)string
{
NSMutableData *stringData = [[[NSMutableData alloc] init] autorelease];
unsigned char whole_byte;
char byte_chars[3] = {'\0','\0','\0'};
int i;
for (i=0; i < [string length] / 2; i++) {
byte_chars[0] = [string characterAtIndex:i*2];
byte_chars[1] = [string characterAtIndex:i*2+1];
whole_byte = strtol(byte_chars, NULL, 16);
[stringData appendBytes:&whole_byte length:1];
}
return stringData;
}
I have develop a similar application on the Android platform and it works well with the server.
Heres the encryption of the function i used on the Android platform.
public byte[] encrypt(byte[] key, byte[] message) throws Exception {
byte [] plainTextBytes = message;
byte[] encryptKey = key;
SecretKey theKey = new SecretKeySpec(encryptKey, "DESede");
Cipher cipher = Cipher.getInstance("DESede/CBC/NoPadding");
IvParameterSpec IvParameters = new IvParameterSpec(new byte[] {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00});
cipher.init(Cipher.ENCRYPT_MODE, theKey, IvParameters);
byte[] encrypted = cipher.doFinal(plainTextBytes);
return encrypted;
}
Basically i want to replicate this similar encryption to be used on the iOS platform.
Any help will be welcome and thank you in advance.

kCCModeCBC is a mode, not an option. The option you want is 0. CBC is the default mode for CCCrypt(). The default is also no padding.

I am an iOS user, not a developer, but as far as I know, iOS no longer supports 3DES. I use an iPad for VPN, and iOS 3 worked fine with 3DES encryption, but as of iOS 4, the minimum encryption level required is AES128.
Hope that helps.

Related

RSA decryption with openSSL

I have a problem with RSA encrypted and Base 64 encoded text decryption. When i decrypt directly encrypted text(unsigned char *) then everything is okay and I get correct result. But when I do base64 encoding, than openssl fails to decrypt data, although base64 decoded data is exactly same as was encrypted data:
For example(first is encryption result and second base 64 decoding result. Decoding first char * directly works pretty well.)
encrypted - ßÁ¨£®Òz>Ô‹n.€Ö∫BÔ–∂ü∏ÕD⁄UÖáµ)ûKufi wÆ&_è”eëõ~gK∂¶$kŸƒ∫ª`ÔfΩ˙˛{∆_MªÔëbP Q¶fl±Ü;!ü•◊s>ħ∆◊⁄≤ò˙ˇCWôVÂzôzíö≤ÙU¶?⁄l[*H?o\ñ>ƒ<‘4mœ“Lr
Íhh
decoded string - ßÁ¨£®Òz>Ô‹n.€Ö∫BÔ–∂ü∏ÕD⁄UÖáµ)ûKufi wÆ&_è”eëõ~gK∂¶$kŸƒ∫ª`ÔfΩ˙˛{∆_MªÔëbP Q¶fl±Ü;!ü•◊s>ħ∆◊⁄≤ò˙ˇCWôVÂzôzíö≤ÙU¶?⁄l[*H?o\ñ>ƒ<‘4mœ“Lr
Íhh
Code:
+(NSString *) rsaEncryptedStringFromText: (NSString *) text
{
const char *message = [text UTF8String];
NSLog(#"message - %s", message);
int bufSize;
NSString *keyFilePath = [[NSBundle mainBundle] pathForResource:#"publicKey" ofType:#"pem"];
FILE *keyfile = fopen([keyFilePath UTF8String], "r");
RSA *rsa = PEM_read_RSA_PUBKEY(keyfile, NULL, NULL, NULL);
if (rsa == NULL)
{
return nil;
}
int key_size = RSA_size(rsa);
unsigned char *encrypted = (unsigned char *) malloc(key_size);
bufSize = RSA_public_encrypt(strlen(message), (unsigned char *) message, encrypted, rsa, RSA_PKCS1_PADDING);
if (bufSize == -1)
{
RSA_free(rsa);
return nil;
}
NSLog(#"encrypted - %s", encrypted);
NSData *encryptedData = [NSData dataWithBytes:encrypted length:strlen((const char *)encrypted)];
NSString *base64 = [encryptedData base64Encoding];
RSA_free(rsa);
return base64;
}
+(NSString *) rsaDecryptToStringFromText: (NSString *) text
{
//NSLog(#"text - %#", text);
NSData *decodedData = [NSData dataWithBase64EncodedString: text];
unsigned char* message = (unsigned char*) [decodedData bytes];
NSLog(#"decoded string - %s", message);
RSA *privKey = NULL;
FILE *priv_key_file;
unsigned char *ptext;
NSString *keyFilePath = [[NSBundle mainBundle] pathForResource:#"privateKeyPair" ofType:#"pem"];
priv_key_file = fopen([keyFilePath UTF8String], "rb");
ERR_print_errors_fp(priv_key_file);
privKey = PEM_read_RSAPrivateKey(priv_key_file, NULL, NULL, NULL);
int key_size = RSA_size(privKey);
ptext = malloc(key_size);
int outlen = RSA_private_decrypt(key_size, (const unsigned char*)message, ptext, privKey, RSA_PKCS1_PADDING);
if(outlen < 0) return nil;
RSA_free(privKey);
return [NSString stringWithUTF8String: (const char *)ptext];
}
Base 64 encoding-decoding is done with this:
http://www.iphonedevsdk.com/forum/iphone-sdk-development/21689-base-64-string-help.html#post98080
Main problem was in base64 encoding+decoding class. Switched to QSutilities and everything works.

Objective-C decrypt AES 128 cbc hex string

I am developing an application for iPhone on Snow Leopard with Xcode 3.1 that receives from a restful web service an encrypted text in hexadecimal format with the algorithm AES 128-bit (CBC). The algorithm uses an initialization vector + secret key. How do I decrypt this text? Thanks to everyone for the tips that I will succeed in giving.
EDIT:
I get response from REST Server in hex AND crypted format,I try with this code but i receive always bad param error. Can you help me to find the error?
Is it possible that i firstly convert the string response into binary format?
NSString *response = [request responseString];
NSData *encryptedData = [response dataUsingEncoding: NSASCIIStringEncoding];
NSString *key = #"32charlength";
NSString *iv = #"16charlength";
NSData *unencryptedData = NULL;
size_t unencryptedLength = [unencryptedData length];
CCCryptorStatus ccStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key, kCCKeySizeAES128, iv, [encryptedData bytes], [encryptedData length], unencryptedData, [encryptedData length], &unencryptedLength);
NSString *output = [[NSString alloc] initWithBytes:unencryptedData length:unencryptedLength encoding:NSUTF8StringEncoding];
if (ccStatus == kCCSuccess) risultato.text = #"SUCCESS";
else if (ccStatus == kCCParamError) risultato.text = #"BAD PARAM";
else if (ccStatus == kCCBufferTooSmall) risultato.text = #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) risultato.text = #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) risultato.text = #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) risultato.text = #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) risultato.text = #"UNIMPLEMENTED";
EDIT2:
this function return BAD PARAM because haven't the right buffer size where allocate decrypted data. I edit the function in this working way:
NSData *encryptedData = [response dataUsingEncoding: NSASCIIStringEncoding];
const void *key = #"32charlength;
uint8_t *iv = #"16charlength";
char buffer[4*4096];
memset(buffer, '\0', sizeof(buffer));
size_t size = sizeof(buffer);
CCCryptorStatus ccStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES128,
0,
key,
kCCKeySizeAES128,
iv,
[encryptedData bytes],
[encryptedData length],
buffer,
sizeof(buffer),
&size);
This function working for me.. thanks so much.
EDIT 23 MARCH------
Now the system work form me with 16 byte key size. Now i have a question, what i can do to implement 32 byte key size ? thanks so much.
This is possible using the CCCryptor functions included in the <CommonCrypto/CommonCryptor.h> header. Check man CCCryptor for the gory details, in your case it sounds like you can use a single call to CCCrypt() to decode the received data:
CCCryptorStatus
CCCrypt(CCOperation op, CCAlgorithm alg, CCOptions options, const void *key, size_t keyLength,
const void *iv, const void *dataIn, size_t dataInLength, void *dataOut, size_t dataOutAvailable,
size_t *dataOutMoved);
Assuming you have the data to be decrypted in NSData *encryptedData you could try something like:
char * key = "shouldbe16chars.";
NSUInteger dataLength = [encryptedData length];
uint8_t unencryptedData[dataLength + kCCKeySizeAES128];
size_t unencryptedLength;
CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key, kCCKeySizeAES128, NULL, [encryptedData bytes], dataLength, unencryptedData, dataLength, &unencryptedLength);
NSString *output = [[NSString alloc] initWithBytes:unencryptedData length:unencryptedLength encoding:NSUTF8StringEncoding];
This is untested, make sure you check the return value of CCCrypt for errors. Check the header file for details, it is well documented.

PBEWithMD5AndDES Encryption in iOS

I'm having an issue with PBEWithMD5AndDES encryption in iOS. I've got my strings encrypting and decrypting using this, https://gist.github.com/788840/24bc73ecd0ac3134cbd242892c74a06ac561d37b.
The problem is I get different encrypted values depending on which class my methods are in. For example, I moved all the encryption methods into a helper class and ran it. I noticed I was getting a different encrypted value.
I now have two identical versions of the same method in different classes and I'm running them side by side. They get different encrypted values, and one cannot decrypt the others'. I'm kind of stumped on this.
Here's the helper class that does encryption/decryption.
#implementation CryptoHelper
#pragma mark -
#pragma mark Init Methods
- (id)init
{
if(self = [super init])
{
}
return self;
}
#pragma mark -
#pragma mark String Specific Methods
/**
* Encrypts a string for social blast service.
*
* #param plainString The string to encrypt;
*
* #return NSString The encrypted string.
*/
- (NSString *)encryptString: (NSString *) plainString{
// Convert string to data and encrypt
NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:#"1111"];
// Get encrypted string from data
return [data base64EncodingWithLineLength:1024];
}
/**
* Descrypts a string from social blast service.
*
* #param plainString The string to decrypt;
*
* #return NSString The decrypted string.
*/
- (NSString *)decryptString: (NSString *) encryptedString{
// decrypt the data
NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:#"1111"];
// extract and return string
return [NSString stringWithUTF8String:[data bytes]];
}
#pragma mark -
#pragma mark Crypto Methods
- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}
- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}
- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
NSLog(#"helper data = %#", inData);
static const char gSalt[] =
{
(unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
(unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA
};
unsigned char *salt = (unsigned char *)gSalt;
int saltLen = strlen(gSalt);
int iterations = 15;
EVP_CIPHER_CTX cipherCtx;
unsigned char *mResults; // allocated storage of results
int mResultsLen = 0;
const char *cPassword = [password UTF8String];
unsigned char *mData = (unsigned char *)[inData bytes];
int mDataLen = [inData length];
SSLeay_add_all_algorithms();
/*X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
iterations, salt, saltLen);*/
const EVP_CIPHER *cipher = EVP_des_cbc();
// Need to set with iv
X509_ALGOR *algorithm = PKCS5_pbe2_set_iv(cipher, iterations,
salt, saltLen, salt, NID_hmacWithMD5);
memset(&cipherCtx, 0, sizeof(cipherCtx));
if (algorithm != NULL)
{
EVP_CIPHER_CTX_init(&(cipherCtx));
if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
algorithm->parameter, &(cipherCtx), direction))
{
EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);
int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
mResults = (unsigned char *)OPENSSL_malloc(allocLen);
unsigned char *in_bytes = mData;
int inLen = mDataLen;
unsigned char *out_bytes = mResults;
int outLen = 0;
int outLenPart1 = 0;
if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
{
out_bytes += outLenPart1;
int outLenPart2 = 0;
if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
{
outLen += outLenPart1 + outLenPart2;
mResults[outLen] = 0;
mResultsLen = outLen;
}
} else {
unsigned long err = ERR_get_error();
ERR_load_crypto_strings();
ERR_load_ERR_strings();
char errbuff[256];
errbuff[0] = 0;
ERR_error_string_n(err, errbuff, sizeof(errbuff));
NSLog(#"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
ERR_lib_error_string(err),
ERR_func_error_string(err),
ERR_reason_error_string(err));
ERR_free_strings();
}
NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;
//NSLog(#"encryption result: %#\n", [encryptedData base64EncodingWithLineLength:1024]);
EVP_cleanup();
return encryptedData;
}
}
EVP_cleanup();
return nil;
}
#end
I'm trying to duplicate the results of this java function. I have the same salt.
public DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
The accepted answer appears to use OpenSSL which is not included in the iOS SDK. Here is an encrypting and decrypting solution that uses the included CommonCrypto library (in libSystem). I'm a bit of an ObjC n00b, so take this code with a grain of salt. By the way, this code will successfully decrypt data encrypted using java's PBEWithMD5AndDES cipher. Hopefully this will save a day or two for someone else.
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonCryptor.h>
+(NSData*) cryptPBEWithMD5AndDES:(CCOperation)op usingData:(NSData*)data withPassword:(NSString*)password andSalt:(NSData*)salt andIterating:(int)numIterations {
unsigned char md5[CC_MD5_DIGEST_LENGTH];
memset(md5, 0, CC_MD5_DIGEST_LENGTH);
NSData* passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];
CC_MD5_CTX ctx;
CC_MD5_Init(&ctx);
CC_MD5_Update(&ctx, [passwordData bytes], [passwordData length]);
CC_MD5_Update(&ctx, [salt bytes], [salt length]);
CC_MD5_Final(md5, &ctx);
for (int i=1; i<numIterations; i++) {
CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
}
size_t cryptoResultDataBufferSize = [data length] + kCCBlockSizeDES;
unsigned char cryptoResultDataBuffer[cryptoResultDataBufferSize];
size_t dataMoved = 0;
unsigned char iv[kCCBlockSizeDES];
memcpy(iv, md5 + (CC_MD5_DIGEST_LENGTH/2), sizeof(iv)); //iv is the second half of the MD5 from building the key
CCCryptorStatus status =
CCCrypt(op, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, (CC_MD5_DIGEST_LENGTH/2), iv, [data bytes], [data length],
cryptoResultDataBuffer, cryptoResultDataBufferSize, &dataMoved);
if(0 == status) {
return [NSData dataWithBytes:cryptoResultDataBuffer length:dataMoved];
} else {
return NULL;
}
}
The problem is that you are not specifying an IV for your encryption, this way a random number will automatically be generated for you, that's also the reason why you get a different result each time.
Try using PKCS5_pbe2_set_iv instead of PKCS5_pbe2_set providing an explicit IV value, that you may randomly choose, much like your salt value.
Using johwayner's response, I fixed this up a little for my purposes of decrypting Java's PBEWithMD5AndDES from jasypt. Here's what I ended up with:
#interface NSData (PBEEncryption)
/**
* Decrypt the receiver using PKCS#5 PBE with MD5 and DES assuming that the salt is prefixed into the first 8 bytes of
* the data and the number of key obtention iterations is 1000. This is compatible with Java's PBEWithMD5AndDES
* encryption when the encryption generates a random salt for the data (the default when providing no salt).
*/
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password;
/**
* Decrypt the receiver using PKCS#5 PBE with MD5 and DES. Explicitly provide the salt and number of key obtention
* iterations.
*/
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations;
#end
#implementation NSData (PBEEncryption)
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password {
NSData *salt = nil;
NSData *input = self;
if ([input length] > 8) {
salt = [input subdataWithRange:NSMakeRange(0, 8)];
input = [input subdataWithRange:NSMakeRange(8, [input length] - 8)];
}
return [input decrytpPBEWithMD5AndDESUsingPassword:password salt:salt iterations:1000];
}
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations {
unsigned char md5[CC_MD5_DIGEST_LENGTH] = {};
CC_MD5_CTX ctx;
CC_MD5_Init(&ctx);
CC_MD5_Update(&ctx, [password bytes], [password length]);
CC_MD5_Update(&ctx, [salt bytes], [salt length]);
CC_MD5_Final(md5, &ctx);
for (NSUInteger i = 1; i < iterations; i++) {
CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
}
// initialization vector is the second half of the MD5 from building the key
unsigned char iv[kCCBlockSizeDES];
assert(kCCBlockSizeDES == CC_MD5_DIGEST_LENGTH / 2);
memcpy(iv, md5 + kCCBlockSizeDES, sizeof(iv));
NSMutableData *output = [NSMutableData dataWithLength:([self length] + kCCBlockSize3DES)];
size_t outputLength = 0;
CCCryptorStatus status =
CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, kCCBlockSizeDES, iv,
[self bytes], [self length], [output mutableBytes], [output length], &outputLength);
if (status == kCCSuccess) { [output setLength:outputLength]; }
else { output = nil; }
return output;
}
#end
Use like so:
NSString *password = #"myTopSecretPassword";
NSData *inputData = [NSData dataFromBase64String:#"base64string"];
NSData *outputData = [inputData decrytpPBEWithMD5AndDESUsingPassword:
[password dataUsingEncoding:NSUTF8StringEncoding]];
Not sure what the protocol is here for accepting answers/upvoting them. I apologize if I'm doing this wrong. The answer turned out to be the lack of a final byte in the salt. I actually didn't need the IV with the 3DES encryption. I upvoted the other answer because it was helpful in understanding more about encryption.
Here's the final objective c class.
#implementation CryptoHelper
#pragma mark -
#pragma mark Init Methods
- (id)init
{
if(self = [super init])
{
}
return self;
}
#pragma mark -
#pragma mark String Specific Methods
/**
* Encrypts a string for social blast service.
*
* #param plainString The string to encrypt;
*
* #return NSString The encrypted string.
*/
- (NSString *)encryptString: (NSString *) plainString{
// Convert string to data and encrypt
NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:#"1111"];
// Get encrypted string from data
return [data base64EncodingWithLineLength:1024];
}
/**
* Descrypts a string from social blast service.
*
* #param plainString The string to decrypt;
*
* #return NSString The decrypted string.
*/
- (NSString *)decryptString: (NSString *) encryptedString{
// decrypt the data
NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:#"1111"];
// extract and return string
return [NSString stringWithUTF8String:[data bytes]];
}
#pragma mark -
#pragma mark Crypto Methods
- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}
- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}
- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
NSLog(#"helper data = %#", inData);
static const char gSalt[] =
{
(unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
(unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
(unsigned char)0x00
};
unsigned char *salt = (unsigned char *)gSalt;
int saltLen = strlen(gSalt);
int iterations = 15;
EVP_CIPHER_CTX cipherCtx;
unsigned char *mResults; // allocated storage of results
int mResultsLen = 0;
const char *cPassword = [password UTF8String];
unsigned char *mData = (unsigned char *)[inData bytes];
int mDataLen = [inData length];
SSLeay_add_all_algorithms();
X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
iterations, salt, saltLen);
memset(&cipherCtx, 0, sizeof(cipherCtx));
if (algorithm != NULL)
{
EVP_CIPHER_CTX_init(&(cipherCtx));
if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
algorithm->parameter, &(cipherCtx), direction))
{
EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);
int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
mResults = (unsigned char *)OPENSSL_malloc(allocLen);
unsigned char *in_bytes = mData;
int inLen = mDataLen;
unsigned char *out_bytes = mResults;
int outLen = 0;
int outLenPart1 = 0;
if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
{
out_bytes += outLenPart1;
int outLenPart2 = 0;
if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
{
outLen += outLenPart1 + outLenPart2;
mResults[outLen] = 0;
mResultsLen = outLen;
}
} else {
unsigned long err = ERR_get_error();
ERR_load_crypto_strings();
ERR_load_ERR_strings();
char errbuff[256];
errbuff[0] = 0;
ERR_error_string_n(err, errbuff, sizeof(errbuff));
NSLog(#"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
ERR_lib_error_string(err),
ERR_func_error_string(err),
ERR_reason_error_string(err));
ERR_free_strings();
}
NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;
//NSLog(#"encryption result: %#\n", [encryptedData base64EncodingWithLineLength:1024]);
EVP_cleanup();
return encryptedData;
}
}
EVP_cleanup();
return nil;
}
#end
I want to thank wbyoung. His answer helped me solve the mystery for how to encrypt Data from iOS and have it decrypted from Java. Below are the additions I made to his Code.
The trick is to take the salt used to encrypt the Data, and prepend it to the result. Java will then be able to decrypt it.
#implementation NSData (PBEEncryption)
- (NSData *)encryptPBEWithMD5AndDESUsingPassword:(NSData *)password {
unsigned char gSalt[] =
{
(unsigned char)0x18, (unsigned char)0x79, (unsigned char)0x6D, (unsigned char)0x6D,
(unsigned char)0x35, (unsigned char)0x3A, (unsigned char)0x6A, (unsigned char)0x60,
(unsigned char)0x00
};
NSData *salt = nil;
salt = [NSData dataWithBytes:gSalt length:strlen(gSalt)];
NSData* encrypted = [self encryptPBEWithMD5AndDESUsingPassword:password salt:salt iterations:1000];
NSMutableData* result = [NSMutableData dataWithData:salt];
[result appendData:encrypted];
return [NSData dataWithData:result];
}
- (NSData *)encryptPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations {
unsigned char md5[CC_MD5_DIGEST_LENGTH] = {};
CC_MD5_CTX ctx;
CC_MD5_Init(&ctx);
CC_MD5_Update(&ctx, [password bytes], [password length]);
CC_MD5_Update(&ctx, [salt bytes], [salt length]);
CC_MD5_Final(md5, &ctx);
for (NSUInteger i = 1; i < iterations; i++) {
CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
}
// initialization vector is the second half of the MD5 from building the key
unsigned char iv[kCCBlockSizeDES];
assert(kCCBlockSizeDES == CC_MD5_DIGEST_LENGTH / 2);
memcpy(iv, md5 + kCCBlockSizeDES, sizeof(iv));
NSMutableData *output = [NSMutableData dataWithLength:([self length] + kCCBlockSize3DES)];
size_t outputLength = 0;
CCCryptorStatus status =
CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, kCCBlockSizeDES, iv,
[self bytes], [self length], [output mutableBytes], [output length], &outputLength);
if (status == kCCSuccess) { [output setLength:outputLength]; }
else { output = nil; }
return output;
}
#end
The Corresponding Swift Code to Encrypt a String:
static func encryptForOverTheWire(string: String) -> String {
let stringData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
let passwordData = PASSWORD.dataUsingEncoding(NSUTF8StringEncoding)
let encryptedData = stringData?.encryptPBEWithMD5AndDESUsingPassword(passwordData)
let base64 = encryptedData?.base64EncodedDataWithOptions(NSDataBase64EncodingOptions())
guard base64 != nil else { return "" }
let result = String(data: base64!, encoding: NSUTF8StringEncoding)
return result ?? ""
}
By the way I am able to get it working with Swift. Only issue I am facing is I am getting a Data object from the objective C module, but when I try to convert to String, it gives me nil. here is the code. Please let me know what is that I am doing wrong here
static func encrypt(inString: String) -> String? {
let passwordStr = "blablalba"
let iterations:Int32 = 19
let salt = [0x44, 0x44, 0x22, 0x22, 0x56, 0x35, 0xE3, 0x03] as [UInt8]
let operation: CCOperation = UInt32(kCCEncrypt)
let saltData = NSData(bytes: salt, length: salt.count)
let out = CryptoHelper.cryptPBE(withMD5AndDES: operation, using: inString.data(using: .utf8), withPassword: passwordStr, andSalt: saltData as Data, andIterating: iterations) as Data
let outString = String.init(data: out, encoding: .utf8)
return outString
}

Duplicating Java Encryption in Objective C

This is a continuation of this question, PBEWithMD5AndDES Encryption in iOS, as it was suggested I start a new questions with a different approach.
What I basically need to do here is duplicate some encryption that's happening in an android app, in an iOS app. I have some encryption working, but as it says in the previous question, the encrypted value is inconsistent. I need the encrypted value on the iOS end to be the same as the encrypted value on the android side, because they will be sharing that data. I am including the java function as well as the objective c class. Both sides of this are flexible, I just have limited knowledge of encryption algorithms.
Here's the java function.
public DesEncrypter(String passPhrase) {
try {
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance(
"PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
} catch (java.security.InvalidAlgorithmParameterException e) {
} catch (java.security.spec.InvalidKeySpecException e) {
} catch (javax.crypto.NoSuchPaddingException e) {
} catch (java.security.NoSuchAlgorithmException e) {
} catch (java.security.InvalidKeyException e) {
}
}
Here's the objective c class.
#implementation CryptoHelper
#pragma mark -
#pragma mark Init Methods
- (id)init
{
if(self = [super init])
{
}
return self;
}
#pragma mark -
#pragma mark String Specific Methods
/**
* Encrypts a string for social blast service.
*
* #param plainString The string to encrypt;
*
* #return NSString The encrypted string.
*/
- (NSString *)encryptString: (NSString *) plainString{
// Convert string to data and encrypt
NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:#"1111"];
// Get encrypted string from data
return [data base64EncodingWithLineLength:1024];
}
/**
* Descrypts a string from social blast service.
*
* #param plainString The string to decrypt;
*
* #return NSString The decrypted string.
*/
- (NSString *)decryptString: (NSString *) encryptedString{
// decrypt the data
NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:#"1111"];
// extract and return string
return [NSString stringWithUTF8String:[data bytes]];
}
#pragma mark -
#pragma mark Crypto Methods
- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}
- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}
- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
NSLog(#"helper data = %#", inData);
static const char gSalt[] =
{
(unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
(unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
(unsigned char)0x00
};
unsigned char *salt = (unsigned char *)gSalt;
int saltLen = strlen(gSalt);
int iterations = 15;
EVP_CIPHER_CTX cipherCtx;
unsigned char *mResults; // allocated storage of results
int mResultsLen = 0;
const char *cPassword = [password UTF8String];
unsigned char *mData = (unsigned char *)[inData bytes];
int mDataLen = [inData length];
SSLeay_add_all_algorithms();
X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
iterations, salt, saltLen);
memset(&cipherCtx, 0, sizeof(cipherCtx));
if (algorithm != NULL)
{
EVP_CIPHER_CTX_init(&(cipherCtx));
if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
algorithm->parameter, &(cipherCtx), direction))
{
EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);
int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
mResults = (unsigned char *)OPENSSL_malloc(allocLen);
unsigned char *in_bytes = mData;
int inLen = mDataLen;
unsigned char *out_bytes = mResults;
int outLen = 0;
int outLenPart1 = 0;
if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
{
out_bytes += outLenPart1;
int outLenPart2 = 0;
if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
{
outLen += outLenPart1 + outLenPart2;
mResults[outLen] = 0;
mResultsLen = outLen;
}
} else {
unsigned long err = ERR_get_error();
ERR_load_crypto_strings();
ERR_load_ERR_strings();
char errbuff[256];
errbuff[0] = 0;
ERR_error_string_n(err, errbuff, sizeof(errbuff));
NSLog(#"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
ERR_lib_error_string(err),
ERR_func_error_string(err),
ERR_reason_error_string(err));
ERR_free_strings();
}
NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;
//NSLog(#"encryption result: %#\n", [encryptedData base64EncodingWithLineLength:1024]);
EVP_cleanup();
return encryptedData;
}
}
EVP_cleanup();
return nil;
}
#end
I'm using an openssl static library for ios.
Thanks,
Brandon
For encryption to work correctly everything needs to be exactly the same at both ends. The same mode, the same key, the same IV and the same padding. You need to check each of these. Don't rely on the default mode but explicitly specify CBC (or CTR) at both ends. After generating your key, print it in hex on both ends so you can check that it is identical. Print the IV in hex at both ends to check. Don't rely on the defaults but explicitly specify the padding (PKCS5 or PKCS7) on both ends.
I have also seen problems with cyphertext where is is converted into a string in one character encoding but converted back to bytes as if it was in another character encoding. Make sure that you are using the same character encoding at both ends.
Once you have identified where the mismatches are happening you can fix them.
On a side note I notice that you are using DES. This is now obsolete and should only be used for backwards compatibility. Use AES for all new applications.

iPhone SDK CCCrypt 3DES and ECB mode always returns PARAM ERROR

I've seen quite a lot of posts about CCCrypt and 3DES on the iPhone at various places around the Net, but there does not seem to be a working example of using it with ECB mode, always with PKCS7Padding.
Does anyone have any working code to encrypt and decrypt a passed string using 3DES and ECB mode using the CCCrypt function?
Currently my code (which I admit came from a site somewhere, I think it was Apple's own developer forums) is as follows:
+ (NSString*)doCipher:(NSString*)plainText action:(CCOperation)encryptOrDecrypt {
const void *vplainText;
size_t plainTextBufferSize;
if (encryptOrDecrypt == kCCDecrypt) {
NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:plainText];
plainTextBufferSize = [EncryptData length];
vplainText = [EncryptData bytes];
}
else {
//plainTextBufferSize = [plainText length];
//vplainText = (const void *)[plainText UTF8String];
NSData *plainTextData = [plainText dataUsingEncoding: NSUTF8StringEncoding];
plainTextBufferSize = [plainTextData length];
vplainText = [plainTextData bytes];
}
CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
// uint8_t ivkCCBlockSize3DES;
bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);
// memset((void *) iv, 0x0, (size_t) sizeof(iv));
NSString *key = #"123456789012345678901234";
NSString *initVec = #"init Vec";
const void *vkey = (const void *)[key UTF8String];
const void *vinitVec = (const void *)[initVec UTF8String];
ccStatus = CCCrypt(encryptOrDecrypt,
kCCAlgorithm3DES,
kCCOptionECBMode,
vkey, //"123456789012345678901234", //key
kCCKeySize3DES,
nil, //"init Vec", //iv,
vplainText, //"Your Name", //plainText,
plainTextBufferSize,
(void *)bufferPtr,
bufferPtrSize,
&movedBytes);
//if (ccStatus == kCCSuccess) NSLog(#"SUCCESS");
/*else*/ if (ccStatus == kCCParamError) return #"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return #"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return #"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return #"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return #"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return #"UNIMPLEMENTED";
NSString *result;
if (encryptOrDecrypt == kCCDecrypt) {
result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding] autorelease];
}
else {
NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
result = [myData base64EncodingWithLineLength:movedBytes];
}
return result; }
The above ALWAYS fails with PARAM ERROR.
- (NSData *) encrypt:(NSString *) dataToEncrypt{
NSUInteger data_length= [dataToEncrypt length];
uint8_t input_raw_data[data_length];
//The [dataToEncrypt length] gives the number of chars present in the string.So say there are 10 chars.
//Now,the getBytes needs to get the raw bytes from this i.e. binary NSData.But suppose the encoding was
//full 16 bit encoding then the number of bytes needed wd have been double- 20.But as we are using the
//NSUTF8StringEncoding,the number of byes needed is 1 per char as the chars(even if originally unicode are
//compressed into an 8 bit UTF8 encoding.)
[dataToEncrypt getBytes:&input_raw_data maxLength:data_length usedLength:NULL encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0,data_length) remainingRange:NULL];
//According to 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 buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_encrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[self.symmetricKey bytes], kCCKeySizeAES256,
NULL,
input_raw_data, data_length,
buffer, buffer_size,
&num_bytes_encrypted);
NSLog(#"~~num bytes encrypted: %d",num_bytes_encrypted);
if (crypt_status == kCCSuccess){
NSLog(#"~~Data encoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_encrypted];
}
free(buffer); //free the buffer;
return nil;
}
- (NSData *) decrypt:(NSData *) dataToDecrypt{
NSUInteger data_length= [dataToDecrypt 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 buffer_size = data_length + kCCBlockSizeAES128;
void* buffer = malloc(buffer_size);
size_t num_bytes_decrypted = 0;
CCCryptorStatus crypt_status = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
[self.symmetricKey bytes], kCCKeySizeAES256,
NULL /* initialization vector (optional) */,
[dataToDecrypt bytes], data_length, /* input */
buffer, buffer_size, /* output */
&num_bytes_decrypted);
NSLog(#"~~num bytes decrypted: %d",num_bytes_decrypted);
if (crypt_status == kCCSuccess){
NSLog(#"~~Data decoded successfully...");
return [NSData dataWithBytesNoCopy:buffer length:num_bytes_decrypted];
}
free(buffer); //free the buffer;
return nil;
}
The above code worked for me, with some changes. The changes are i decelare the moveBytes and bufferPtf as instance variable and did following chandge.
if (encryptOrDecrypt == kCCDecrypt) {
plainTextBufferSize = movedBytes;
vplainText = bufferPtr;
}
else {
plainTextBufferSize = [plainText length];
vplainText = (const void *)[plainText UTF8String];
}
instead base64encoding use nsasciiencoding.