objective-c - 如何在 Objective C 中使用 AES 256 CBC 加密

标签 objective-c encryption

我正在构建一个 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 中做同样的事情

最佳答案

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

关于objective-c - 如何在 Objective C 中使用 AES 256 CBC 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832991/

相关文章:

ios - UIPageViewController 在 childViewController 中具有动态内容

objective-c - UIProgressView : modify height for track line

java - 使用 AES-128 加密/解密大于 256 字节的字节数组

c++ - 自定义协议(protocol)的 SSL 或 TLS 加密

javascript - 需要帮助使用 Javascript 解密 AES 加密字符串(使用 crypto-js)

ios - 使用Grand Central Dispatch将URL字符串从JSON转换为ImageView的图像

ios - 如何在标签栏中设置角标(Badge)值?

iphone - iOS - RestKit 并清除所有数据?

Java:如何用字节创建一个包?

html - EME 如何阻止我录制 netflix 流?