I'm trying to implement AES128 encryption on an Android. I've got a solution working on an iPhone with Objective C but having trouble porting it to Android. I've searched stackoverflow for a solution, but I seem to be doing something wrong. I'm fairly new to Java so I think I'm missing something to do with data, string conversion.
Here is my iPhone encrypt:
char keyPtr[kCCKeySizeAES128+1];
[keyString getCString:keyPtr
maxLength:sizeof(keyPtr)
encoding:NSASCIIStringEncoding];
// CString for the plain text
char plainBytes[[plainString length]+1];
[plainString getCString:plainBytes
maxLength:sizeof(plainBytes)
encoding:NSASCIIStringEncoding];
size_t bytesEncrypted = 0;
// Allocate the space for encrypted data
NSUInteger dataLength = [plainString length];
size_t bufferSize = dataLength + kCCBlockSizeAES128;
void* buffer = malloc(bufferSize);
// Encrypt
CCCryptorStatus ret = CCCrypt(kCCEncrypt,
kCCAlgorithmAES128,
kCCOptionPKCS7Padding | kCCOptionECBMode,
keyPtr,
kCCKeySizeAES128,
NULL,
plainBytes, sizeof(plainBytes),
buffer, bufferSize,
&bytesEncrypted);
if (ret != kCCSuccess) {
free(buffer);
}
encryptedData = [NSData dataWithBytes:buffer length:bytesEncrypted];
Here is my Java:
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("UTF-8"));
Using the same key and plaintext in iPhone and Java give different results. My iPhone result works the way I need it so I'm trying to get java to give me the iPhone result. I'm missing something in the Java for sure, just not sure what it is.
edit
based on suggestions below I modified my Java to this
byte[] keyBytes = plainTextKey.getBytes("US-ASCII");
SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(plainText.getBytes("US-ASCII"));
but I'm still getting different results between android and iPhone