I have an iPhone solutions that uses XML to transmit data between the client (mobile) and the server (Java). Some of the parts of the message (XML) must be encrypted because
This code works for me. Give a look:
AES 128 IOS
+ (NSString *) encrypt:(NSString *) dataToEncrypt withKey:(NSString*) key{
NSData *data = [dataToEncrypt dataUsingEncoding:NSUTF8StringEncoding];
NSData *mData = [key dataUsingEncoding:NSUTF8StringEncoding];
CCCryptorStatus ccStatus = kCCSuccess;
// Begin to calculate bytesNeeded....
size_t bytesNeeded = 0;
ccStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionECBMode | kCCOptionPKCS7Padding,
[mData bytes],
[mData length],
nil,
[data bytes],
[data length],
NULL,
0,
&bytesNeeded);
if(kCCBufferTooSmall != ccStatus){
NSLog(@"Here it must return BUFFER TOO SMALL !!");
return nil;
}
// .....End
// Now i do the real Crypting
char* cypherBytes = malloc(bytesNeeded);
size_t bufferLength = bytesNeeded;
if(NULL == cypherBytes)
NSLog(@"cypherBytes NULL");
ccStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionECBMode | kCCOptionPKCS7Padding,
[mData bytes],
[mData length],
nil,
[data bytes],
[data length],
cypherBytes,
bufferLength,
&bytesNeeded);
if(kCCSuccess != ccStatus){
NSLog(@"kCCSuccess NO!");
return nil;
}
return [Base64 encode:[NSData dataWithBytes:cypherBytes length:bufferLength]];
}
JAVA
public static void encrypt_AES(String message){
Cipher ecipher;
try {
// generate secret key using DES algorithm
SecretKeySpec key = new SecretKeySpec(theKey.getBytes("UTF-8"), "AES");
ecipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
// initialize the ciphers with the given key
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = ecipher.doFinal(message.getBytes("UTF-8"));
}catch (Exception e) {
//
e.printStackTrace();
}
}
I found the Base64 class here: http://www.imthi.com/blog/programming/iphone-sdk-base64-encode-decode.php
Hope it can help someone