I have an application which gets encrypted video in compressed mode from a Java server. On the iOS side I'm not able to decrypt that.
The code I using for encryption in Java is:
// generate a key
KeyGenerator keygen = KeyGenerator.getInstance("AES");
keygen.init(128); // To use 256 bit keys, you need the "unlimited strength" encryption policy files from Sun.
//byte[] key = keygen.generateKey().getEncoded();
byte key[] = {0x00, 0x01, 0x02, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
SecureRandom random = new SecureRandom();
IvParameterSpec ivspec = new IvParameterSpec(key);
// initialize the cipher for encrypt mode
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivspec);
System.out.println();
byte[] encrypted = cipher.doFinal(IOUtils.toByteArray(new FileInputStream(new File(fileName))));
My code for decryption in iOS is the following:
char keyPtr[kCCKeySizeAES256+1];
bzero( keyPtr, sizeof(keyPtr) );
[key getCString: keyPtr maxLength: sizeof(keyPtr) encoding: NSUTF16StringEncoding];
Byte iv [] = {0x00, 0x01, 0x02, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
//unsigned char keyPtr[kCCKeySizeAES128] = { 0x00, 0x01, 0x02, 0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
NSData *passwordData = [@"[B@71e2b67c" dataUsingEncoding:NSUTF8StringEncoding];
size_t numBytesEncrypted = 0;
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer_decrypt = malloc(bufferSize);
CCCryptorStatus result = CCCrypt( kCCDecrypt , kCCAlgorithmAES128, kCCOptionPKCS7Padding,
passwordData.bytes, kCCKeySizeAES256,
iv,
[self bytes], [self length],
buffer_decrypt, bufferSize,
&numBytesEncrypted );
NSLog(@".......decryption...........%d........",result);
if( result == kCCSuccess )
return [NSData dataWithBytesNoCopy:buffer_decrypt length:numBytesEncrypted];
What might be the problem here and how can I solve it?
The password is not the correct length for kCCAlgorithmAES128
, it is 88 bits:
NSData *passwordData = [@"[B@71e2b67c" dataUsingEncoding:NSUTF8StringEncoding];
There is an inconsistency:
kCCAlgorithmAES128
and kCCKeySizeAES256
The decryption key is not the same as the encryption key.
The decryption iv is not the same as the encryption iv.
Just for starters you need to get these correct.
As @Duncan writes, start with a very simple case and when that is working add complexity. A simple starting point is exactly one block of data, no padding, a simple key of the correct size, an iv of all 0s.
Best bet: hire a domain expert, security is very hard to get correct.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With