php ios通用的AES加密方法

weixin_34377065發表於2012-12-13

AES for iphone下載AES庫

在不同平臺進行AES加密,並使用Base64進行編碼,結果有可能不同,但解密之後會一樣,所以不要因為在2個平臺加密結果不一樣而認為自己錯了。。。

 

php加密解密: 

<?php

$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);

$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$key = 'a16byteslongkey!a16byteslongkey!';

$plaintext = "iphone";

 

$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB);

$base64encoded_ciphertext = base64_encode($ciphertext);

echo "ciphertext: ".$base64encoded_ciphertext."<br/>";

 

$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), MCRYPT_MODE_ECB);

echo "plaintext: ".$plaintext."<br/>";

 

$base64encoded_ciphertext =  "I3chV+E2XUHeLCcJAhBaJQ==";

$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), MCRYPT_MODE_ECB);

echo "plaintext: ".trim($plaintext);

?> 

 

iphone加密解密

#import "NSString+AESCrypt.h"
NSString *key = @"a16byteslongkey!a16byteslongkey!";
NSString *plaintext = @"iphone";
NSString *ciphertext = [plaintext AES256EncryptWithKey: key];
NSLog(@"ciphertext: %@", ciphertext);
plaintext = [ciphertext AES256DecryptWithKey: key];
NSLog(@"plaintext: %@", plaintext);

 

Demo:

php 程式碼:

<?php
$key = "test_AES_key";
 
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = md5($key);
$plaintext = "ksfe";
 
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_ECB);
$base64encoded_ciphertext = base64_encode($ciphertext);
echo $base64encoded_ciphertext."<br/>";
 
//$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($base64encoded_ciphertext), MCRYPT_MODE_ECB);
//echo "plaintext: ".$plaintext."<br/>";
?>

 

 
iphone 程式碼:
-(NSString *)md5:(NSString *)str { 
    const char *cStr = [str UTF8String]; 
    unsigned char result[32]; 
    CC_MD5( cStr, strlen(cStr), result ); 
    return [NSString stringWithFormat: 
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3], 
            result[4], result[5], result[6], result[7], 
            result[8], result[9], result[10], result[11], 
            result[12], result[13], result[14], result[15] 
            ]; 
}
 
#import "NSString+AESCrypt.h"
 
NSString *strKey = @"test_AES_key";
NSData *chipherData = [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://192.168.157.1/index_aes.php"]];
    
NSString *chipherText = [[NSString alloc] initWithData: chipherData encoding: NSUTF8StringEncoding];
NSString *plainText = [chipherText AES256DecryptWithKey: [self md5: strKey]];
NSLog(@"plainText: %@", plainText);

 

相關文章