如何在iOS Objective-C中实现php的openssl_encrypt()方法?

时间:2017-01-15 11:38:19

标签: php ios objective-c aes php-openssl

我想在 iOS Objective-C 中实现php的openssl_encrypt()方法。因此我尝试了这段代码:

    #import <CommonCrypto/CommonHMAC.h>
    #import <CommonCrypto/CommonCryptor.h>
    - (void)viewDidLoad {
       [super viewDidLoad];
    NSData *dataIn     = [@"123456" dataUsingEncoding:NSISOLatin1StringEncoding];

    NSString *key = @"ygXa6pBJOWSAXXX/J6POVTjvJpMIiPAMQiTMjBrcOGw=";
    NSData *decodedKeyData = [[NSData alloc] initWithBase64EncodedString:key options:0];


    uint8_t randomBytes[16];
    NSMutableString *ivStr;
    int result = SecRandomCopyBytes(kSecRandomDefault, 16, randomBytes);
    if(result == 0) {
        ivStr = [[NSMutableString alloc] initWithCapacity:16];
        for(NSInteger index = 0; index < 8; index++)
        {
            [ivStr appendFormat: @"%02x", randomBytes[index]];
        }
        NSLog(@"iv string is %@  %lu" , ivStr , ivStr.length);
    } else {
        NSLog(@"iv string failed for some reason");
    }

    NSData *iv         = [[NSData alloc] initWithBase64EncodedString:ivStr options:0];

    // setup key
    unsigned char cKeyR[kCCKeySizeAES256];
    bzero(cKeyR, sizeof(cKeyR));
    [decodedKeyData getBytes:cKeyR length:kCCKeySizeAES256];
    // setup iv
    char cIv[kCCBlockSizeAES128];
    bzero(cIv, kCCBlockSizeAES128);
    if (iv) {
        [iv getBytes:cIv length:kCCBlockSizeAES128];
    }
    // setup output buffer
    size_t bufferSize = [dataIn length] + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    // do encrypt
    size_t encryptedSize = 0;
    CCCryptorStatus cryptStatus = CCCrypt(
                                          kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding,
                                          cKeyR,
                                          kCCKeySizeAES192,
                                          cIv,
                                          [dataIn bytes],
                                          [dataIn length],
                                          buffer,
                                          bufferSize,
                                          &encryptedSize
                                          );

    NSData *encrypted = [NSData dataWithBytesNoCopy:buffer length:encryptedSize];
    NSString *encStr = [encrypted base64EncodedStringWithOptions:0]; 
}

但它与php中的openssl_encrypt()方法不同。我已经检查过iv,key和其他方法。长度和字节输出是正确的但是当在另一种方法中使用输出时它是错误的。

1 个答案:

答案 0 :(得分:0)

  1. decodedKeyData为32字节)(256位),但密钥大小指定为kCCKeySizeAES192

  2. 只需使用randomBytes作为IV,转换它是没有意义的是Base64并返回。