【问题标题】:How to encrypt with AES 256 CBC in Objective C如何在 Objective C 中使用 AES 256 CBC 进行加密
【发布时间】:2023-03-08 03:01:01
【问题描述】:

我正在构建一个 iPhone 应用程序,它获取一个加密字符串并将其发送到后端。

在 PHP 中,我像这样加密字符串:

$encrypt_method = "AES-256-CBC";
$secret_key = 'This is my secret key';
$secret_iv = 'This is my secret iv';

// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);

if( $action == 'encrypt' ) {
    $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
    $output = base64_encode($output);
}

在 Objective C 中我如何做同样的事情

【问题讨论】:

标签: objective-c encryption


【解决方案1】:
#import <CommonCrypto/CommonCryptor.h>

#define key @"YOUR_KEY"
#define iv @"YOUR_IV"

- (NSData *) cryptOperation:(CCOperation)operation
{
    // 'key' should be 32 bytes for AES256, will be null-padded otherwise
    char keys[kCCKeySizeAES256 + 1];
    [key getCString:keys maxLength:sizeof(keys) encoding:NSUTF8StringEncoding];
    // Perform PKCS7Padding on the key.
    unsigned long bytes_to_pad = sizeof(keys) - [key length];
    if (bytes_to_pad > 0)
    {
        char byte = bytes_to_pad;
        for (unsigned long i = sizeof(keys) - bytes_to_pad; i < sizeof(keys); i++)
            keys[i] = byte;
    }
    NSUInteger dataLength = [self length];
    //See the doc: For block ciphers, the output size will always be less than or
    //equal to the input size plus the size of one block.
    //That's why we need to add the size of one block here
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    size_t numBytesDecrypted = 0;
    CCCryptorStatus status = CCCrypt(operation, kCCAlgorithmAES128,
                                     kCCOptionPKCS7Padding,
                                     keys, kCCKeySizeAES256,
                                     [iv UTF8String],
                                     [self bytes], dataLength, /* input */
                                     buffer, bufferSize, /* output */
                                     &numBytesDecrypted);
    if (status == kCCSuccess)
    {
        //the returned NSData takes ownership of buffer and will free it on dealloc
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer); //free the buffer;
    return nil;
}

- (NSData *)AES256Encrypt
{
    return [self cryptOperation:kCCEncrypt];
}

- (NSData *)AES256Decrypt
{
    return [self cryptOperation:kCCDecrypt];
}

您可以通过以下方式使用此方法..

NSString *receivedDataDecryptString = [self decrypt:@"YOUR_STRING"];
NSString *receivedDataEncryptString = [self encrypt:@"YOUR_STRING"];

    -(NSString *)encrypt:(NSString *)string
    {
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        NSData *dataEncrypted = [data AES256Encrypt];
        NSString *strRecordEncrypted = [dataEncrypted base64EncodedStringWithOptions:0];
        return strRecordEncrypted;
    }

    -(NSString *)decrypt:(NSString *)string
    {
        if([string containsString:@"\n"] || [string containsString:@"\t"])
        {
            string = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
            string = [string stringByReplacingOccurrencesOfString:@"\t" withString:@""];
        }
    NSData *keyData = [[NSData alloc] initWithBase64EncodedString:string options:0];
    NSData *dataDecrypted = [keyData AES256Decrypt];
    NSString *receivedDataDecryptString = [[NSString alloc]initWithData:dataDecrypted encoding:NSUTF8StringEncoding];
    return receivedDataDecryptString;
}

【讨论】:

  • 我的密钥是 NSData。它是 32 字节的。这种情况下该如何处理?
  • @AthulGeorge 来自“key”和“iv”,你在 NSData 中有“key”。对吗?
  • 是的,我可以解决它。我正在使用 ECC 生成共享密钥。即,我将拥有一个 32 字节的密钥(作为曲线生成的 NSData),它将用于加密纯数据。加密是使用 AES256 完成的。 IV 为零。 unsigned long total_bytes_key = (kCCKeySizeAES256 + 1) * sizeof(char); char *dataPtrKey = malloc(total_bytes_key); bzero(dataPtrKey,total_bytes_key); memcpy(dataPtrKey, keyX.bytes, keyX.length);
【解决方案2】:

感谢Nirav Kotecha您的回答。

我最终使用CrytoSwift 并添加扩展类 NSString 和 String 来调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-11
    • 2017-08-28
    • 2017-09-28
    • 1970-01-01
    • 2012-08-05
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多