I am new in xcode. I am encrypting a string in xcode and also encrypting the same string in Java using AES 256 bit and am seeing some strange issues. The Encryption in java and Iphone do not match each other i have used the following code:
NSString *password = @"mypassword";
NSString *str = @"message";
NSLog(@"encrypting string =%@",str);
NSData *data = [str dataUsingEncoding: NSASCIIStringEncoding];
NSData *encryptedData = [data AES256EncryptWithKey:password];
NSString *responseString = [[NSString alloc] initWithData:encryptedData encoding:NSASCIIStringEncoding];
[Base64 initialize];
NSString *b64EncStr = [Base64 encode:encryptedData];
NSLog(@"Base 64 encoded = %@",b64EncStr);
NSData *b64DecData = [Base64 decode:b64EncStr];
NSData *decryptedData = [b64DecData AES256DecryptWithKey:password];
NSString* decryptedStr = [[NSString alloc] initWithData:decryptedData encoding:NSASCIIStringEncoding];
NSLog(@"decrypted string = %@",decryptedStr);
/////////////////************///////////////***************************/////////////////////
- (NSData *)AES256EncryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256 + 1];
bzero( keyPtr, sizeof( keyPtr ) );
[key getCString:keyPtr maxLength:sizeof( keyPtr )
encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesEncrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCEncrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL ,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesEncrypted );
if( cryptStatus == kCCSuccess ) {
return [NSData dataWithBytesNoCopy:buffer
length:numBytesEncrypted]; }
>free( buffer );
>return nil; }
- (NSData *)AES256DecryptWithKey:(NSString *)key {
char keyPtr[kCCKeySizeAES256+1];
bzero( keyPtr, sizeof( keyPtr ) );
[key getCString:keyPtr maxLength:sizeof( keyPtr )
encoding:NSUTF8StringEncoding];
NSUInteger dataLength = [self length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void *buffer = malloc( bufferSize );
size_t numBytesDecrypted = 0;
CCCryptorStatus cryptStatus = CCCrypt( kCCDecrypt,
kCCAlgorithmAES128, kCCOptionPKCS7Padding,
keyPtr, kCCKeySizeAES256,
NULL ,
[self bytes], dataLength,
buffer, bufferSize,
&numBytesDecrypted );
if( cryptStatus == kCCSuccess ) {
return [NSData dataWithBytesNoCopy:buffer
length:numBytesDecrypted]; }
free( buffer );
return nil; }
i am getting an encrypted string nd1+bWMbk+BEnr9uPIq2eQ== in xcode
but in java using the following code i am encrypting it
SecretKeySpec spec = getKeySpec();
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, spec);
BASE64Encoder enc = new BASE64Encoder();
String hexString = stringToHex(text);
>return enc.encode(cipher.doFinal(hex2byte(hexString)));
and the encrypted string is mCP+z7ZqxDWPoJPaPoVfSw== i am not able to find the perfect solution in java?