How can I do this same encrypt/decrypt PHP function on iOS with Objective-C?

前端 未结 5 593
清酒与你
清酒与你 2021-02-06 15:50

I have a function in PHP that encrypts and decrypts strings:

function encrypt_decrypt($action, $string) 
{
   $output = false;
   $key = \'mykeyhereblah\';
   $i         


        
5条回答
  •  无人共我
    2021-02-06 16:27

    So you want to encrypt using AES256 in CBC mode. The library you are looking for is CommonCrypto and you can find a good article about it here:http://robnapier.net/aes-commoncrypto.

    You will also need an MD5 function that you can find here: http://www.makebetterthings.com/iphone/how-to-get-md5-and-sha1-in-objective-c-ios-sdk/

    Your code should look something like this:

    NSString *originalString,*keyString;
    NSData *key = [[self md5:keyString] dataUsingEncoding:NSUTF8StringEncoding];
    NSData *iv = [[self md5:[self md5:key]] dataUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *cipherData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128]; //The block size of MCRYPT_RIJNDAEL_256 is just like AES128
    size_t outLength;
    
    CCCryptorStatus result
           = CCCrypt(kCCEncrypt, // operation, replace with kCCDecrypt to decrypt
                     kCCAlgorithmAES, // Same as MCRYPT_RIJNDAEL_256
                     nil, // CBC mode
                     key.bytes, // key
                     32, // Since you are using AES256
                     iv.bytes,// iv
                     data.bytes, // dataIn
                     data.length, // dataInLength,
                     cipherData.mutableBytes, // dataOut
                     cipherData.length, // dataOutAvailable
                     &outLength); // dataOutMoved
    NSString resultString = [cipherData base64Encoding];
    

    And make sure you are using the same UTF8 encoding in both cases, and use this import:

    #import 
    

    I am pretty sure this should work.

    EDIT: the key length should be 32 since you are using AES256 256bit=32bytes. The MD5 output wouldn't match this length by default I think.

提交回复
热议问题