How to implement php openssl_encrypt () method in iOS Objective-C?

I want to implement the php openssl_encrypt() method in iOS Objective-C . So I tried this code:

  #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]; } 

But this is not the same openssl_encrypt () method in php. I checked iv, key and other methods. the length and bytes are correct, but using the output in another method is wrong.

-1
source share
1 answer
  • decodedKeyData is 32 bytes) (256 bits), but the key size is specified as kCCKeySizeAES192 .

  • Just use randomBytes as IV, it makes no sense to convert it to Base64 and vice versa.

0
source

Source: https://habr.com/ru/post/1233081/


All Articles