如何在iOS上使用AES GCM加密?

6

我需要在GCM模式下使用AES加密/解密一些数据,但是似乎CommonCrypto API无法完成此操作。这个问题之前已经被问过(链接),但采纳的答案不符合我的需求,因为我需要使用这个特定算法。

有什么想法吗?我应该使用OpenSSL吗?因为我听说在iOS上使用它会有一些bug。

我正在寻找Swift的答案,但Objective-C也可以。

5个回答

9

自从 iOS 13 版本以来,我们拥有了 CryptoKit,这是一个非常强大且相对容易掌握的工具。今天我创建了一个代码示例,演示了 AES-GCM 256 加密和解密。虽然我不是密码学专家,但该示例展示了使用该算法的两种可能方式。请随意克隆我的示例仓库并玩转 CryptoKit 示例:

import Foundation
import CryptoKit

let key = SymmetricKey(size: .bits256)
let plain = """
    {"data":{"id":"7fab123e96","created_at":"2020-01-21T14:16:41Z","name":"John","age":18,"sex":"male"}}
    """

/// Encrypt: Using plain text only • nonce & tag are randomly created
/// Decrypt: Specify all 3 parameters: nonce + cipher text + tag
func cryptoDemoCipherText() {

    // Encrypt
    let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key)

    // Decrypt
    let sealedBoxRestored = try! AES.GCM.SealedBox(nonce: sealedBox.nonce, ciphertext: sealedBox.ciphertext, tag: sealedBox.tag)
    let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key)

    print("Crypto Demo I\n••••••••••••••••••••••••••••••••••••••••••••••••••\n")
    print("Combined:\n\(sealedBox.combined!.base64EncodedString())\n")
    print("Cipher:\n\(sealedBox.ciphertext.base64EncodedString())\n")
    print("Nonce:\n\(sealedBox.nonce.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n")
    print("Tag:\n\(sealedBox.tag.base64EncodedString())\n")
    print("Decrypted:\n\(String(data: decrypted, encoding: .utf8)!)\n")
}

/// Encrypt: Specify all 3 parameters yourself: nonce + cipher text + tag
/// Decrypt: Using combined data (nonce + cipher text + tag) and tag to open
func cryptoDemoCombinedData() {

    let nonce = try! AES.GCM.Nonce(data: Data(base64Encoded: "fv1nixTVoYpSvpdA")!)
    let tag = Data(base64Encoded: "e1eIgoB4+lA/j3KDHhY4BQ==")!

    // Encrypt
    let sealedBox = try! AES.GCM.seal(plain.data(using: .utf8)!, using: key, nonce: nonce, authenticating: tag)

    // Decrypt
    let sealedBoxRestored = try! AES.GCM.SealedBox(combined: sealedBox.combined!)
    let decrypted = try! AES.GCM.open(sealedBoxRestored, using: key, authenticating: tag)

    print("Crypto Demo II\n••••••••••••••••••••••••••••••••••••••••••••••••••\n")
    print("Combined:\n\(sealedBox.combined!.base64EncodedString())\n")
    print("Cipher:\n\(sealedBox.ciphertext.base64EncodedString())\n")
    print("Nonce:\n\(nonce.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n")
    print("Tag:\n\(tag.base64EncodedString())\n")
    print("Decrypted:\n\(String(data: decrypted, encoding: .utf8)!)\n")
}


print("Key32:\n\(key.withUnsafeBytes { Data(Array($0)).base64EncodedString() })\n")

cryptoDemoCombinedData()
cryptoDemoCipherText()

希望这对你们中的一些人有所帮助 :-) 以下是需要翻译的内容:

https://github.com/Blackjacx/Playgrounds/blob/master/playgrounds/CryptoKit.playground/Contents.swift


1
我添加了你提供的代码,因为链接可能会失效。 - Andrew
我无法在Objective C中使用相同的。 - Harish
@Harish 是的,但是你可以创建一个处理这个问题的 Swift 类,然后导入 Swift 头文件,在 Objective C 文件中使用 Swift 代码。 - TJ Olsen

7
CommonCryptorSPI.h中有一些GCM加密函数,它们尚未公开。但是,如果您将它们添加到桥接标头中,就可以使用它们。
#include <CommonCrypto/CommonCryptor.h>
CCCryptorStatus CCCryptorGCM(
CCOperation     op,             /* kCCEncrypt, kCCDecrypt */
CCAlgorithm     alg,
const void      *key,           /* raw key material */
size_t          keyLength,  
const void      *iv,
size_t          ivLen,
const void      *aData,
size_t          aDataLen,
const void      *dataIn,
size_t          dataInLength,
void            *dataOut,
const void      *tag,
size_t          *tagLength);

或者您可以尝试使用SwCrypt库。


2
关于使用私有 API,那会通过应用审核吗? - zaph
2
请大家向苹果提交错误报告:https://bugreport.apple.com,请求iOS支持GCM。虽然这意味着需要进行另一次FIPS 140-2审核,但是现在是苹果更新Common Crypto的时候了。 - zaph
在审查SEM格式后,一个非常关键的缺失是版本指示器。没有版本指示器,SEM无法在实现向后兼容性的同时进行更新。考虑添加一个版本指示器。 - zaph
1
如何在不使用仅适用于iOS 13+的CryptoKit的情况下实现AES-GCM? - Ratnesh Singh
1
@GabrielHuff:您能否在这里为我提供一个示例,我和您一样的处境。 - Harish
显示剩余5条评论

0

虽然这个问题已经有答案了,但我想要做出我的贡献。

一段时间以前,我回答了一个非常类似的问题。总之,我也需要使用AES GCM加密一些数据,但是苹果没有提供任何公共函数(显然他们也没有任何意图这样做)。因此,我开发了自己的库,可以在GitHub上找到。

下面是一个使用示例:

#import <CommonCrypto/CommonCrypto.h>
#import "IAGAesGcm.h"

// Define an Encryption Key
u_char keyBytes[kCCKeySizeAES128] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10};
NSData *key = [NSData dataWithBytes:keyBytes length:sizeof(keyBytes)];

// Define an Initialization Vector
// GCM recommends a IV size of 96 bits (12 bytes), but you are free
// to use other sizes
u_char ivBytes[12] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C};
NSData *iv = [NSData dataWithBytes:ivBytes length:sizeof(ivBytes)];

// Define an Additional Authenticated Data
NSData *aad = [@"AdditionalAuthenticatedData" dataUsingEncoding:NSUTF8StringEncoding];

// Now, we are ready to encrypt some plain data
NSData *expectedPlainData = [@"PlainData" dataUsingEncoding:NSUTF8StringEncoding];

// The returned ciphered data is a simple class with 2 properties: the actual encrypted data and the authentication tag.
// The authentication tag can have multiple sizes and it is up to you to set one, in this case the size is 128 bits
// (16 bytes)
IAGCipheredData *cipheredData = [IAGAesGcm cipheredDataByAuthenticatedEncryptingPlainData:expectedPlainData
                                                          withAdditionalAuthenticatedData:aad
                                                                  authenticationTagLength:IAGAuthenticationTagLength128
                                                                     initializationVector:iv
                                                                                      key:key
                                                                                    error:nil];

// And now, de-cypher the encrypted data to see if the returned plain data
// is as expected
NSData *plainData = [IAGAesGcm plainDataByAuthenticatedDecryptingCipheredData:cipheredData
                                              withAdditionalAuthenticatedData:aad
                                                         initializationVector:iv
                                                                          key:key
                                                                        error:nil];

XCTAssertEqualObjects(expectedPlainData, plainData);

根据一个错误报告的回应,苹果将不再开发CommonCrypto,也不会将任何SPI公开为API。因此,苹果似乎不会将AES-GCM添加到Common Crypto中。希望有另一种解决方案在进行中,可能是从OSX移植加密转换。苹果知道Common Crypto在Android加密API方面非常缺乏和可笑。 - zaph
我知道这是一个晚评论,但在iOS 13中,他们将发布CryptoKit,包括GCM。 - thorb65

0
#import "CommonCryptorSPI.h"

/*!
 * @brief Generates AES GCM ciphertext, tag (MAC) and IV of a input data
 * @param dataIn the data to be encrypted
 * @param ivLenghtInBits the desired length for the initialization vector (iv)
 * @param symmetricKey the symmetric key
 * @param aad the additional authentication data
 * @param encryptOrDecrypt the operation type kCCEncrypt or kCCDecrypt
 * @param error NSError pointer
 * @return a NSDictionary with the cyphertext ('cyphertext' key) tag ('tag' key) and the iv ('iv' key)
 */
+ (NSDictionary *)dataEncryption:(NSData *)dataIn ivLengthInBits:(int)ivLenghtInBits key:(NSData *)symmetricKey aad:(NSData *)aad context:(CCOperation)encryptOrDecrypt error:(NSError **)error
{
    CCCryptorStatus ccStatus = kCCSuccess;
    NSData *iv = [self randomKeyDataGeneratorWithNumberBits:ivLenghtInBits];
    NSMutableData  *dataOut = [NSMutableData dataWithLength:dataIn.length];
    NSMutableData  *tag = [NSMutableData dataWithLength:kCCBlockSizeAES128];
    size_t          tagLength = kCCBlockSizeAES128;

    ccStatus = CCCryptorGCM(encryptOrDecrypt,
                            kCCAlgorithmAES,
                            symmetricKey.bytes,
                            kCCKeySizeAES256,
                            iv.bytes,
                            iv.length,
                            aad.bytes,
                            aad.length,
                            dataIn.bytes,
                            dataIn.length,
                            dataOut.mutableBytes,
                            tag.bytes,
                            &tagLength);

    if (ccStatus == kCCSuccess) {
       return [NSDictionary dictionaryWithObjectsAndKeys:dataOut,@"cyphertext",tag,@"tag",iv,@"iv",nil];
    } else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        return nil;
    }

}

/*!
 * @brief Generates NSData from a randomly generated byte array with a specific number of bits
 * @param numberOfBits the number of bits the generated data must have
 * @return the randomly generated NSData
 */
- (NSData *)randomKeyDataGeneratorWithNumberBits:(int)numberOfBits {
    int numberOfBytes = numberOfBits/8;
    uint8_t randomBytes[numberOfBytes];
    int result = SecRandomCopyBytes(kSecRandomDefault, numberOfBytes, randomBytes);
    if(result == 0) {
        return [NSData dataWithBytes:randomBytes length:numberOfBytes];
    } else {
        return nil;
    }
}

如果你没有CommonCryptorSPI.h,这里提供下载:

/*
 * Copyright (c) 2010 Apple Inc. All Rights Reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 *
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 *
 * @APPLE_LICENSE_HEADER_END@
 */

#ifndef _CC_CryptorSPI_H_
#define _CC_CryptorSPI_H_

#include <sys/types.h>
#include <sys/param.h>
#include <stdint.h>

#include <string.h>
#ifdef KERNEL
#include <machine/limits.h>
#else
#include <limits.h>
#include <stdlib.h>
#endif /* KERNEL */
#include <Availability.h>

#ifdef __cplusplus
extern "C" {
#endif

    /*
     This is an SPI header.  It includes some work in progress implementation notes that
     will be removed when this is promoted to an API set.
     */

    /*
     Private Ciphers
     */

    /* Lion SPI name for no padding.  Defining for compatibility.  Is now
     ccNoPadding in CommonCryptor.h
     */

    enum {
        ccDefaultPadding            = 0,
    };


    enum {
        kCCAlgorithmAES128NoHardware = 20,
        kCCAlgorithmAES128WithHardware = 21
    };

    /*
     Private Modes
     */
    enum {
        kCCModeGCM      = 11,
        kCCModeCCM      = 12,
    };

    /*
     Private Paddings
     */
    enum {
        ccCBCCTS1           = 10,
        ccCBCCTS2           = 11,
        ccCBCCTS3           = 12,
    };

    /*
     Private Cryptor direction (op)
     */
    enum {
        kCCBoth     = 3,
    };




    /*
     Supports a mode call of
     int mode_setup(int cipher, const unsigned char *IV, const unsigned char *key, int keylen,
     const unsigned char *tweak, int tweaklen, int num_rounds, int options, mode_context *ctx);
     */

    /* User supplied space for the CryptorRef */

    CCCryptorStatus CCCryptorCreateFromDataWithMode(
                                                    CCOperation     op,             /* kCCEncrypt, kCCEncrypt, kCCBoth (default for BlockMode) */
                                                    CCMode          mode,
                                                    CCAlgorithm     alg,
                                                    CCPadding       padding,
                                                    const void      *iv,            /* optional initialization vector */
                                                    const void      *key,           /* raw key material */
                                                    size_t          keyLength,
                                                    const void      *tweak,         /* raw tweak material */
                                                    size_t          tweakLength,
                                                    int             numRounds,
                                                    CCModeOptions   options,
                                                    const void      *data,          /* caller-supplied memory */
                                                    size_t          dataLength,     /* length of data in bytes */
                                                    CCCryptorRef    *cryptorRef,    /* RETURNED */
                                                    size_t          *dataUsed)      /* optional, RETURNED */
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


    /*
     Assuming we can use existing CCCryptorCreateFromData for all modes serviced by these:
     int mode_encrypt(const unsigned char *pt, unsigned char *ct, unsigned long len, mode_context *ctx);
     int mode_decrypt(const unsigned char *ct, unsigned char *pt, unsigned long len, mode_context *ctx);
     */

    /*
     Block mode encrypt and decrypt interfaces for IV tweaked blocks (XTS and CBC)

     int mode_encrypt_tweaked(const unsigned char *pt, unsigned long len, unsigned char *ct, const unsigned char *tweak, mode_context *ctx);
     int mode_decrypt_tweaked(const unsigned char *ct, unsigned long len, unsigned char *pt, const unsigned char *tweak, mode_context *ctx);
     */

    CCCryptorStatus CCCryptorEncryptDataBlock(
                                              CCCryptorRef cryptorRef,
                                              const void *iv,
                                              const void *dataIn,
                                              size_t dataInLength,
                                              void *dataOut)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


    CCCryptorStatus CCCryptorDecryptDataBlock(
                                              CCCryptorRef cryptorRef,
                                              const void *iv,
                                              const void *dataIn,
                                              size_t dataInLength,
                                              void *dataOut)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

    /*
     Assuming we can use the existing CCCryptorRelease() interface for
     int mode_done(mode_context *ctx);
     */

    /*
     Not surfacing these other than with CCCryptorReset()

     int mode_setiv(const unsigned char *IV, unsigned long len, mode_context *ctx);
     int mode_getiv(const unsigned char *IV, unsigned long *len, mode_context *ctx);
     */

    /*
     DES key utilities
     */

    CCCryptorStatus CCDesIsWeakKey(
                                   void *key,
                                   size_t Length)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

    void CCDesSetOddParity(
                           void *key,
                           size_t Length)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

    uint32_t CCDesCBCCksum(void *input, void *output,
                           size_t length, void *key, size_t keylen,
                           void *ivec)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);


    /*
     * returns a cipher blocksize length iv in the provided iv buffer.
     */

    CCCryptorStatus
    CCCryptorGetIV(CCCryptorRef cryptorRef, void *iv)
    __OSX_AVAILABLE_STARTING(__MAC_10_7, __IPHONE_5_0);

    /*
     GCM Support Interfaces

     Use CCCryptorCreateWithMode() with the kCCModeGCM selector to initialize
     a CryptoRef.  Only kCCAlgorithmAES128 can be used with GCM and these
     functions.  IV Setting etc will be ignored from CCCryptorCreateWithMode().
     Use the CCCryptorGCMAddIV() routine below for IV setup.
     */

    /*
     This adds the initial vector octets from iv of length ivLen to the GCM
     CCCryptorRef. You can call this function as many times as required to
     process the entire IV.
     */

    CCCryptorStatus
    CCCryptorGCMAddIV(CCCryptorRef cryptorRef,
                      const void        *iv,
                      size_t ivLen)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

    /*
     Additional Authentication Data
     After the entire IV has been processed, the additional authentication
     data can be processed. Unlike the IV, a packet/session does not require
     additional authentication data (AAD) for security. The AAD is meant to
     be used as side–channel data you want to be authenticated with the packet.
     Note: once you begin adding AAD to the GCM CCCryptorRef you cannot return
     to adding IV data until the state has been reset.
     */

    CCCryptorStatus
    CCCryptorGCMAddAAD(CCCryptorRef cryptorRef,
                       const void       *aData,
                       size_t aDataLen)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);

    // Maintain the old symbol with incorrect camel-case for now.
    CCCryptorStatus
    CCCryptorGCMaddAAD(CCCryptorRef cryptorRef,
                       const void       *aData,
                       size_t aDataLen)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_6_0);

    // This is for old iOS5 clients
    CCCryptorStatus
    CCCryptorGCMAddADD(CCCryptorRef cryptorRef,
                       const void       *aData,
                       size_t aDataLen)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


    CCCryptorStatus CCCryptorGCMEncrypt(
                                        CCCryptorRef cryptorRef,
                                        const void *dataIn,
                                        size_t dataInLength,
                                        void *dataOut)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


    CCCryptorStatus CCCryptorGCMDecrypt(
                                        CCCryptorRef cryptorRef,
                                        const void *dataIn,
                                        size_t dataInLength,
                                        void *dataOut)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

    /*
     This terminates the GCM state gcm and stores the tag in tag of length
     taglen octets.
     */

    CCCryptorStatus CCCryptorGCMFinal(
                                      CCCryptorRef cryptorRef,
                                      const void *tag,
                                      size_t *tagLength)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

    /*
     This will reset the GCM CCCryptorRef to the state that CCCryptorCreateWithMode()
     left it. The user would then call CCCryptorGCMAddIV(), CCCryptorGCMaddAAD(), etc.
     */

    CCCryptorStatus CCCryptorGCMReset(
                                      CCCryptorRef cryptorRef)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);

    /*
     This will initialize the GCM state with the given key, IV and AAD value
     then proceed to encrypt or decrypt the message text and store the final
     message tag. The definition of the variables is the same as it is for all
     the manual functions. If you are processing many packets under the same
     key you shouldn’t use this function as it invokes the pre–computation
     with each call.
     */

    CCCryptorStatus CCCryptorGCM(
                                 CCOperation    op,             /* kCCEncrypt, kCCDecrypt */
                                 CCAlgorithm        alg,
                                 const void         *key,           /* raw key material */
                                 size_t             keyLength,
                                 const void         *iv,
                                 size_t             ivLen,
                                 const void         *aData,
                                 size_t             aDataLen,
                                 const void         *dataIn,
                                 size_t             dataInLength,
                                 void           *dataOut,
                                 const void         *tag,
                                 size_t             *tagLength)
    __OSX_AVAILABLE_STARTING(__MAC_10_8, __IPHONE_5_0);


    void CC_RC4_set_key(void *ctx, int len, const unsigned char *data)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

    void CC_RC4(void *ctx, unsigned long len, const unsigned char *indata,
                unsigned char *outdata)
    __OSX_AVAILABLE_STARTING(__MAC_10_4, __IPHONE_5_0);

    /*
     GCM interface can then be easily bolt on the rest of standard CCCryptor interface; typically following sequence can be used:

     CCCryptorCreateWithMode(mode = kCCModeGCM)
     0..Nx: CCCryptorAddParameter(kCCParameterIV, iv)
     0..Nx: CCCryptorAddParameter(kCCParameterAuthData, data)
     0..Nx: CCCryptorUpdate(inData, outData)
     0..1: CCCryptorFinal(outData)
     0..1: CCCryptorGetParameter(kCCParameterAuthTag, tag)
     CCCryptorRelease()

     */

    enum {
        /*
         Initialization vector - cryptor input parameter, typically
         needs to have the same length as block size, but in some cases
         (GCM) it can be arbitrarily long and even might be called
         multiple times.
         */
        kCCParameterIV,

        /*
         Authentication data - cryptor input parameter, input for
         authenticating encryption modes like GCM.  If supported, can
         be called multiple times before encryption starts.
         */
        kCCParameterAuthData,

        /*
         Mac Size - cryptor input parameter, input for
         authenticating encryption modes like CCM. Specifies the size of
         the AuthTag the algorithm is expected to produce.
         */
        kCCMacSize,

        /*
         Data Size - cryptor input parameter, input for
         authenticating encryption modes like CCM. Specifies the amount of
         data the algorithm is expected to process.
         */
        kCCDataSize,

        /*
         Authentication tag - cryptor output parameter, output from
         authenticating encryption modes like GCM.  If supported,
         should be retrieved after the encryption finishes.
         */
        kCCParameterAuthTag,
    };
    typedef uint32_t CCParameter;

    /*
     Sets or adds some other cryptor input parameter.  According to the
     cryptor type and state, parameter can be either accepted or
     refused with kCCUnimplemented (when given parameter is not
     supported for this type of cryptor at all) or kCCParamError (bad
     data length or format).
     */

    CCCryptorStatus CCCryptorAddParameter(
                                          CCCryptorRef cryptorRef,
                                          CCParameter parameter,
                                          const void *data,
                                          size_t dataSize);


    /*
     Gets value of output cryptor parameter.  According to the cryptor
     type state, the request can be either accepted or refused with
     kCCUnimplemented (when given parameteris not supported for this
     type of cryptor) or kCCBufferTooSmall (in this case, *dataSize
     argument is set to the requested size of data).
     */

    CCCryptorStatus CCCryptorGetParameter(
                                          CCCryptorRef cryptorRef,
                                          CCParameter parameter,
                                          void *data,
                                          size_t *dataSize);


#ifdef __cplusplus
}
#endif

#endif /* _CC_CryptorSPI_H_ */

请记住,AES GCM要求密钥和IV具有特定数量的位数,因此我建议获取您想要使用的任何密钥的SHA-256哈希值,并像这样调用函数:

NSError *error;
NSDictionary *AESGCMEncrypted = [self dataEncryption:data ivLengthInBits:96 key:YourSHA256BitsKey aad:aadData context:kCCEncrypt error:&error];

-1
以下代码(修改自此C code)应该在iOS中运行良好。它启用了AES-GCM文件加密和解密。标签包含在加密文件中,在解密操作期间将被提取和验证。
#include "openssl/evp.h"

typedef struct _cipher_params_t{
    unsigned char *key;
    unsigned char *iv;
    unsigned char *tag;
    char *aad;
    unsigned int iv_len;
    unsigned int aad_len;
    unsigned int encrypt;
    const EVP_CIPHER *cipher_type;
}cipher_params_t;


+(int) file_enc_dec_aes_gcm: (cipher_params_t*) params inPath: (const char*) inPath  outPath: (const char*) outPath {
    FILE *ifp = fopen(inPath, "rb");
    if (!ifp) {
        /* Unable to open file for reading */
        fprintf(stderr, "ERROR: fopen error: %s\n", strerror(errno));
        return errno;
    }

    /* Open and truncate file to zero length or create ciphertext file for writing */
    FILE *ofp = fopen(outPath, "wb");
    if (!ofp) {
        /* Unable to open file for writing */
        fprintf(stderr, "ERROR: fopen error: %s\n", strerror(errno));
        return errno;
    }
    /* Allow enough space in output buffer for additional block */


    int cipher_block_size = EVP_CIPHER_block_size(params->cipher_type);
    unsigned char in_buf[BUFSIZE], out_buf[BUFSIZE + cipher_block_size];

    int num_bytes_read, out_len;
    EVP_CIPHER_CTX *ctx;

    ctx = EVP_CIPHER_CTX_new();
    if(ctx == NULL){
        fprintf(stderr, "ERROR: EVP_CIPHER_CTX_new failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        cleanup(params, ifp, ofp, ERR_EVP_CTX_NEW);
    }

    /* Don't set key or IV right away; we want to check lengths */
    if(!EVP_CipherInit_ex(ctx, params->cipher_type, NULL, NULL, NULL, params->encrypt)){
        fprintf(stderr, "ERROR: EVP_CipherInit_ex failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        cleanup(params, ifp, ofp, ERR_EVP_CIPHER_INIT);
    }


    //EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, 12, NULL);

    OPENSSL_assert(EVP_CIPHER_CTX_key_length(ctx) == AES_256_KEY_SIZE);
    //OPENSSL_assert(EVP_CIPHER_CTX_iv_length(ctx) == AES_BLOCK_SIZE);

    /* Now we can set key and IV */
    if(!EVP_CipherInit_ex(ctx, NULL, NULL, params->key, params->iv, params->encrypt)){
        fprintf(stderr, "ERROR: EVP_CipherInit_ex failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        EVP_CIPHER_CTX_cleanup(ctx);
        cleanup(params, ifp, ofp, ERR_EVP_CIPHER_INIT);
    }

    std::cout << "AAD len = " << strlen(params->aad) << std::endl;


    if(!EVP_EncryptUpdate (ctx, NULL, &out_len, (const unsigned char *)params->aad, strlen(params->aad))){

        fprintf(stderr, "ERROR: EVP_CipherUpdate AAD failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        EVP_CIPHER_CTX_cleanup(ctx);
        cleanup(params, ifp, ofp, ERR_EVP_CIPHER_INIT);
    }


    //std::cout <<"aad out len = " << out_len << std::endl;


    unsigned char tag[AES_BLOCK_SIZE] = {0};



    if(!params->encrypt)
    {
        //retrieve tag

        fread(tag, sizeof(unsigned char), AES_BLOCK_SIZE, ifp);



        params->tag = tag;




    }
    else{
        fseek(ofp, AES_BLOCK_SIZE, SEEK_SET); //16 is tag len only done during encryption

    }

    while(1){
        // Read in data in blocks until EOF. Update the ciphering with each read.
        num_bytes_read = fread(in_buf, sizeof(unsigned char), BUFSIZE, ifp);
        if (ferror(ifp)){
            fprintf(stderr, "ERROR: fread error: %s\n", strerror(errno));
            EVP_CIPHER_CTX_cleanup(ctx);
            cleanup(params, ifp, ofp, errno);
        }
        if(!EVP_CipherUpdate(ctx, out_buf, &out_len, in_buf, num_bytes_read)){
            fprintf(stderr, "ERROR: EVP_CipherUpdate failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
            EVP_CIPHER_CTX_cleanup(ctx);
            cleanup(params, ifp, ofp, ERR_EVP_CIPHER_UPDATE);
        }

        //std::cout <<"enc/dec out len = " << out_len << std::endl;

        fwrite(out_buf, sizeof(unsigned char), out_len, ofp);
        if (ferror(ofp)) {
            fprintf(stderr, "ERROR: fwrite error: %s\n", strerror(errno));
            EVP_CIPHER_CTX_cleanup(ctx);
            cleanup(params, ifp, ofp, errno);
        }
        if (num_bytes_read < BUFSIZE) {
            /* Reached End of file */
            break;
        }
    }

    /* Now cipher the final block and write it out to file */
    if(params->encrypt && !EVP_CipherFinal_ex(ctx, out_buf, &out_len)){
        fprintf(stderr, "ERROR: EVP_CipherFinal_ex failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        EVP_CIPHER_CTX_cleanup(ctx);

        cleanup(params, ifp, ofp, ERR_EVP_CIPHER_FINAL);
    }

    /* Get the tag */
    if(params->encrypt && 1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, params->tag))
    {
        //handleErrors();
        fprintf(stderr, "ERROR: Tag gen failed. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        EVP_CIPHER_CTX_cleanup(ctx);

        cleanup(params, ifp, ofp, ERR_EVP_CIPHER_FINAL);
    }
    else if(params->encrypt)
    {
        fwrite(out_buf, sizeof(unsigned char), out_len, ofp);
        printf("Successful encryption and tag generation...\n");

        BIO_dump_fp(stdout, (const char*)params->tag, 16);

        fseek(ofp, 0, SEEK_SET);


        fwrite(params->tag, sizeof(char), AES_BLOCK_SIZE, ofp);


    }


    /* verify the tag */
    if(!params->encrypt && !EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16,params->tag))
    {
        //handleErrors();
        fprintf(stderr, "ERROR: Tag error. OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
        EVP_CIPHER_CTX_cleanup(ctx);

        cleanup(params, ifp, ofp, ERR_EVP_CIPHER_FINAL);
    }

    int ret = -1;
    if(!params->encrypt){
        ret = EVP_CipherFinal_ex(ctx, out_buf, &out_len);
        if(ret > 0){

            fwrite(out_buf, sizeof(unsigned char), out_len, ofp);
            printf("tag verification and decryption success \n");
        }else{

            fprintf(stderr, "ERROR: EVP_CipherFinal_ex failed. Tag verification failed...OpenSSL error: %s\n", ERR_error_string(ERR_get_error(), NULL));
            EVP_CIPHER_CTX_cleanup(ctx);

            cleanup(params, ifp, ofp, ERR_EVP_CIPHER_FINAL);
        }
    }



    if (ferror(ofp)) {
        fprintf(stderr, "ERROR: fwrite error: %s\n", strerror(errno));
        EVP_CIPHER_CTX_cleanup(ctx);
        cleanup(params, ifp, ofp, errno);
    }


    fclose(ifp);
    fclose(ofp);
    EVP_CIPHER_CTX_cleanup(ctx);


    return ret;
}

void cleanup(cipher_params_t *params, std::ifstream& ifp, std::ofstream& ofp, int rc){
    free(params);

    ifp.close();

    ofp.close();
    exit(rc);
}

1
它还需要openssl。 - Sulthan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接