I have a code, writed on PHP:
function aes128Encrypt($key, $data) {
$iv = rand(1,9999999);
$size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($size,$iv);
$key = md5($key);
return base64_encode($iv.mcrypt_encrypt(MCRYPT_RIJNDAEL_128, pack("H*", $key) , $data, MCRYPT_MODE_CBC, $iv));
return $data;
}
//Function for decryption of AES-128
function aes128Decrypt($key, $data) {
$data = base64_decode($data);
$iv = substr($data, 0, 16);
$data = substr_replace($data, null, 0, 16);
$key = md5($key);
$decrypted = urlencode(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, pack("H*", $key) , $data, MCRYPT_MODE_CBC, $iv));
$decrypted = str_replace('%00','',$decrypted);
return urldecode($decrypted);
}
I need to make the same code on iOS, using Objective-C. How can i do it? I'm new in Objective-C, so help please :)
There are several problems with the php cryptography.
The rand() function documentation: "This function does not generate cryptographically secure values, and should not be used for cryptographic purposes . If you need a cryptographically secure value". See: mcrypt_create_iv.
If the input key is text, such as a password, using md5 to derive a key is no longer considered acceptable, use a function such as PBKDF2. See: hash_pbkdf2.
For iOS use Apple's Common Crypto library.
Note that Base64 encoding/decoding is separate from Common Crypto and part of NSData
in iOS7 and above.
The Common Crypto functions you will need are:
CCCryptorStatus CCCrypt(
CCOperation op, /* kCCEncrypt, etc. */
CCAlgorithm alg, /* kCCAlgorithmAES128, etc. */
CCOptions options, /* kCCOptionPKCS7Padding, etc. */
const void *key, size_t keyLength,
const void *iv, /* optional initialization vector */
const void *dataIn, size_t dataInLength,
void *dataOut, /* data RETURNED here */
size_t dataOutAvailable,
size_t *dataOutMoved)
int
CCKeyDerivationPBKDF(
CCPBKDFAlgorithm algorithm,
const char *password, size_t passwordLen,
const uint8_t *salt, size_t saltLen,
CCPseudoRandomAlgorithm prf, uint rounds,
uint8_t *derivedKey, size_t derivedKeyLen)
The Base64 methods you will need:
- (NSString *)base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)options
- (NSData *)base64EncodedDataWithOptions:(NSDataBase64EncodingOptions)options
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.