iOS AES加密和PHP解密

时间:2014-03-14 12:49:31

标签: php ios objective-c encryption aes

我正在尝试加密iOS中的字符串并使用PHP解密。

在iOS中,根据此链接AES-128 encryption in iOS and Decryption in PHP

中的信息,我有以下代码
- (void)testCrypto {
    NSString *password = @"1234567891234567";
    NSString *plaintext = @"This is a test";
    NSString *encrypted = [plaintext AES128EncryptWithKey:password];

    dispatch_queue_t jsonParsingQueue = dispatch_queue_create("jsonParsingQueue", NULL);
    dispatch_async(jsonParsingQueue, ^{
        NSString *webResult = [EPWebServices cryptoData:[encrypted dataUsingEncoding:NSUTF8StringEncoding] password:password];
        [self performSelectorOnMainThread:@selector(testing:) withObject:webResult waitUntilDone:YES];
    });
}

- (void)testing:(id)test {
    test = [[NSString alloc] initWithData:test encoding:NSUTF8StringEncoding];
    NSLog(@"Result:%@", test);
}

上面用于加密的NSData上的类别位于链接中。 EPWebServices是一个将密文转换为base64的类,并使用密码和密文将URLRequest发送到服务器。

在PHP中我(也来自上面的链接):

$Pass = $_GET['pw'];
$crypted = urldecode($_GET['encrypted']);        
$newClear = decrypt_password($crypted, $Pass);
echo "Dec: ".$newClear . "Input: ".$crypted;


function decrypt_password($pass,$key)
{
$base64encoded_ciphertext = $pass;

$res_non = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), ‘ecb’);
$decrypted = $res_non;
$dec_s2 = strlen($decrypted);

$padding = ord($decrypted[$dec_s2-1]);
$decrypted = substr($decrypted, 0, -$padding);

return  $decrypted;
}

问题是解密的消息只是一个空字符串。我在NSLog中得到的结果只是Dec:Input: ejhCNHo0Z2tNZ0paMGdJOTJLdEJjZz09。我已经确认密码和密文都是在PHP中正确接收的,但是,解密只打印出一个空字符串。我是加密新手,因此可能存在一些基本错误。如果需要特定的输出/ NSLog等,请告诉我。

0 个答案:

没有答案