iOS平台上类似于SpongyCastle加密库的替代方案

5
这让我感到困惑 - 以下代码使用了SpongyCastle的加密/解密来实现Android - 我正在尝试为iOS实现跨平台的加密/解密。以下代码(来自Android)可行,使用提供的盐和密码,采用AES 128位CBC与PKCS7Padding,其中盐存储在mysql数据库中,密码由最终用户输入,以下代码改编自kelhoer 的这个答案。
我使用AES128bit的原因是iOS 4+中不支持AES256,它是在iOS5+中引入的,而且必须涉足使用 openssl 生成派生密钥和初始化向量(iv),但学到苹果拒绝与openssl库静态链接的应用程序,这很棘手。
由于该平台基于iOS 4.2+,所以采用捆绑并静态链接openssl库似乎有些过头,更好的方法是使用CommonCryptor库。
以下是已经使用Spongycastle代码的Android版本:
private static void encrypt(InputStream fin, 
    OutputStream fout, 
    String password, 
    byte[] bSalt) {
    try {
        PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(
            new SHA256Digest()
            );
        char[] passwordChars = password.toCharArray();
        final byte[] pkcs12PasswordBytes = 
            PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
        pGen.init(pkcs12PasswordBytes, bSalt, ITERATIONS);
        CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
        ParametersWithIV aesCBCParams = 
            (ParametersWithIV) pGen.generateDerivedParameters(128, 128);
        aesCBC.init(true, aesCBCParams);
        PaddedBufferedBlockCipher aesCipher = 
            new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding());
        aesCipher.init(true, aesCBCParams);
        byte[] buf = new byte[BUF_SIZE];
        // Read in the decrypted bytes and write the cleartext to out
        int numRead = 0;
        while ((numRead = fin.read(buf)) >= 0) {
            if (numRead == 1024) {
                byte[] plainTemp = new byte[
                    aesCipher.getUpdateOutputSize(numRead)];
                int offset = 
                    aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
                final byte[] plain = new byte[offset];
                System.arraycopy(plainTemp, 0, plain, 0, plain.length);
                fout.write(plain, 0, plain.length);
            } else {
                byte[] plainTemp = new byte[aesCipher.getOutputSize(numRead)];
                int offset = 
                    aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
                int last = aesCipher.doFinal(plainTemp, offset);
                final byte[] plain = new byte[offset + last];
                System.arraycopy(plainTemp, 0, plain, 0, plain.length);
                fout.write(plain, 0, plain.length);
            }
        }
        fout.close();
        fin.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private static void decrypt(InputStream fin, 
    OutputStream fout, 
    String password, 
    byte[] bSalt) {
    try {
        PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(
            new SHA256Digest()
            );
        char[] passwordChars = password.toCharArray();
        final byte[] pkcs12PasswordBytes = 
            PBEParametersGenerator.PKCS12PasswordToBytes(passwordChars);
        pGen.init(pkcs12PasswordBytes, bSalt, ITERATIONS);
        CBCBlockCipher aesCBC = new CBCBlockCipher(new AESEngine());
        ParametersWithIV aesCBCParams = 
            (ParametersWithIV) pGen.generateDerivedParameters(128, 128);
        aesCBC.init(false, aesCBCParams);
        PaddedBufferedBlockCipher aesCipher = 
            new PaddedBufferedBlockCipher(aesCBC, new PKCS7Padding());
        aesCipher.init(false, aesCBCParams);
        byte[] buf = new byte[BUF_SIZE];
        // Read in the decrypted bytes and write the cleartext to out
        int numRead = 0;
        while ((numRead = fin.read(buf)) >= 0) {
            if (numRead == 1024) {
                byte[] plainTemp = new byte[
                    aesCipher.getUpdateOutputSize(numRead)];
                int offset = 
                    aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
                // int last = aesCipher.doFinal(plainTemp, offset);
                final byte[] plain = new byte[offset];
                System.arraycopy(plainTemp, 0, plain, 0, plain.length);
                fout.write(plain, 0, plain.length);
            } else {
                byte[] plainTemp = new byte[
                    aesCipher.getOutputSize(numRead)];
                int offset = 
                    aesCipher.processBytes(buf, 0, numRead, plainTemp, 0);
                int last = aesCipher.doFinal(plainTemp, offset);
                final byte[] plain = new byte[offset + last];
                System.arraycopy(plainTemp, 0, plain, 0, plain.length);
                fout.write(plain, 0, plain.length);
            }
        }
        fout.close();
        fin.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

然而,在 iOS 4.2(使用 XCode)下,我无法找出如何执行相同的操作。

以下是我在 Objective C 下尝试的内容,目的是从 Android 端解密数据,这些数据存储在 mysql 数据库中,以测试此功能:

+(NSData*) decrypt:(NSData*)cipherData 
    userPassword:(NSString*)argPassword 
    genSalt:(NSData*)argPtrSalt{

    size_t szPlainBufLen = cipherData.length + (kCCBlockSizeAES128);
    uint8_t *ptrPlainBuf = malloc(szPlainBufLen);
    //
    const unsigned char *ptrPasswd = 
        (const unsigned char*)[argPassword 
            cStringUsingEncoding:NSASCIIStringEncoding];
    int ptrPasswdLen = strlen(ptrPasswd);
    //
    NSString *ptrSaltStr = [[NSString alloc]
        initWithData:argPtrSalt 
        encoding:NSASCIIStringEncoding];

    const unsigned char *ptrSalt = 
        (const unsigned char *)[ptrSaltStr UTF8String];
    NSString *ptrCipherStr = 
        [[NSString alloc]initWithData:cipherData 
            encoding:NSASCIIStringEncoding];
    unsigned char *ptrCipher = (unsigned char *)[ptrCipherStr UTF8String];
    unsigned char key[kCCKeySizeAES128];
    unsigned char iv[kCCKeySizeAES128];
    //
    //int     EVP_BytesToKey(const EVP_CIPHER *type,const EVP_MD *md,
    //const unsigned char *salt, const unsigned char *data,
    //int datal, int count, unsigned char *key,unsigned char *iv);
    int i = EVP_BytesToKey(EVP_aes_128_cbc(), 
                       EVP_sha256(), 
                       ptrSalt, 
                       ptrPasswd, 
                       ptrPasswdLen, 
                       PBKDF2_ITERATIONS, 
                       key, 
                       iv);
    NSAssert(i == kCCKeySizeAES128, 
        @"Unable to generate key for AES");
    //
    size_t cipherLen = [cipherData length];
    size_t outlength = 0;
    //
    CCCryptorStatus resultCCStatus = CCCrypt(kCCDecrypt,
                                             kCCAlgorithmAES128,
                                             kCCOptionPKCS7Padding,
                                             key,
                                             kCCBlockSizeAES128,
                                             iv,
                                             ptrCipher,
                                             cipherLen,
                                             ptrPlainBuf,
                                             szPlainBufLen,
                                             &outlength);
    NSAssert(resultCCStatus == kCCSuccess, 
        @"Unable to perform PBE AES128bit decryption: %d", errno);
    NSData *ns_dta_PlainData = nil;

    if (resultCCStatus == kCCSuccess){
        ns_dta_PlainData = 
        [NSData dataWithBytesNoCopy:ptrPlainBuf length:outlength];
    }else{
        return nil;
    }
    return ns_dta_PlainData;
}

我已经提供了数据和用户密码,并从CCCrypt获得了返回代码,其值为-4304,这表明解码失败。

我认为可能是编码方案导致CommonCryptor的解密路由出现问题,因此才需要通过冗长的方式转换为NSASCIIStringEncoding

盐值存储在密文数据中,长度为32字节。

在这方面我错过了什么,需要注意的是,我对加密学很弱。


1
如果您想要达到兼容性,我认为在iOS和Android之间使用不同的代码库会让您自找麻烦。为什么不只是找一个C/C++的AES实现,并将其编译到两个平台的代码库中呢? - Abhi Beckert
2个回答

4
我已经编写了一个直接移植自安卓端的PKCS12Parameters生成器,上面是这个头文件的要点。
实现方法也是直接复制自此处,密码被转换为PKCS12等效格式——unicode、大端字节序,并在末尾填充两个额外的零。
生成器通过执行1000次迭代(在安卓端也是如此),使用SHA256摘要算法来生成派生密钥和向量,最终生成的密钥和向量作为参数传递给CCCryptorCreate函数。
下面的代码示例也无法正常工作,调用CCCryptorFinal时会出现-4304错误。
代码片段如下:
#define ITERATIONS 1000

PKCS12ParametersGenerator *pGen = [[PKCS12ParametersGenerator alloc]
        init:argPassword 
        saltedHash:argPtrSalt 
        iterCount:ITERATIONS 
        keySize:128 
        initVectSize:128]; 
//
[pGen generateDerivedParameters];
//
CCCryptorRef decryptor = NULL;
// Create and Initialize the crypto reference.
CCCryptorStatus ccStatus = CCCryptorCreate(kCCDecrypt,
                           kCCAlgorithmAES128,
                           kCCOptionPKCS7Padding,
                           pGen.derivedKey.bytes,
                           kCCKeySizeAES128,
                           pGen.derivedIV.bytes,
                           &decryptor
                           );
NSAssert(ccStatus == kCCSuccess, 
    @"Unable to initialise decryptor!");
//
size_t szPlainBufLen = cipherData.length + (kCCBlockSizeAES128);

// Calculate byte block alignment for all calls through to and including final.
size_t szPtrPlainBufSize = CCCryptorGetOutputLength(decryptor, szPlainBufLen, true);
uint8_t *ptrPlainBuf = calloc(szPtrPlainBufSize, sizeof(uint8_t));
//
// Set up initial size.
size_t remainingBytes = szPtrPlainBufSize;
uint8_t *ptr = ptrPlainBuf;
size_t movedBytes = 0;
size_t totalBytesWritten = 0;

// Actually perform the encryption or decryption.
ccStatus = CCCryptorUpdate(decryptor,
                           (const void *) cipherData.bytes,
                           szPtrPlainBufSize,
                           ptr,
                           remainingBytes,
                           &movedBytes
                           );
NSAssert(ccStatus == kCCSuccess, 
    @"Unable to update decryptor! Error: %d", ccStatus);
ptr += movedBytes;
remainingBytes -= movedBytes;
totalBytesWritten += movedBytes;
//
// Finalize everything to the output buffer.
CCCryptorStatus resultCCStatus = CCCryptorFinal(decryptor,
                          ptr,
                          remainingBytes,
                          &movedBytes
                          );

totalBytesWritten += movedBytes;

if(decryptor) {
    (void) CCCryptorRelease(decryptor);
    decryptor = NULL;
}

NSAssert(resultCCStatus == kCCSuccess, 
    @"Unable to perform PBE AES128bit decryption: %d", resultCCStatus);

有趣的是,如果我在CCCryptorCreate的开始处用0x0000替换kCCOptionPKCS7Padding,即无填充模式,则解密有效。可惜的是,数据仍然被完全打乱,与我预期的不同。
它在某个地方失败了,因此如果有更好的实现方法,我很高兴听取其他意见。
要么就改变Android端的机制,使其与iPhone"跨平台"兼容,要么就寻求另一种加密解决方案,以牺牲双方平台上的较弱加密性,以便实现数据交换的可移植性。
提供的输入数据:
  • Base64编码的密码文本,盐和密码由":"分隔:tnNhKyJ2vvrUzAmtQV5q9uEwzzAH63sTKtLf4pOQylw=:qTBluA+aNeFnEUfkUFUEVgNYrdz7enn5W1n4Q9uBKYmFfJeSCcbsfziErsa4EU9Cz/pO0KE4WE1QdqRcvSXthQ==
  • 提供的密码是f00b4r
  • 原始字符串是The quick brown fox jumped over the lazy dog and ran away

0

好的,我不得不放弃Android端的加密算法,这是一个挑战,需要找到一个跨平台兼容的算法。

我阅读了很多关于Rob Napier's RNCryptor的资料,并在搜索Android等效算法时发现了JNCryptor,因此我在iOS端采用了RNCryptor。

github上分叉了JNCryptor代码以添加能够指定自定义设置并使用SpongyCastle的增强功能,以适用于旧版本的Android。从那时起,两个平台都能够互相加密/解密。

我增强JNCryptor的原因是PKDBF2函数的迭代次数太高了 - 默认值为10,000(因为代码将在旧手机上运行 - 如果您有双/四核心,那就很好!),需要覆盖迭代次数以使其更“可承受”- 1,000。使用自定义设置可以通过RNCryptor实现。

感谢Rob Napier和Duncan Jones的工作!


你好,我也想在Android平台中使用Spongycastle实现相同的功能。我应该使用RNCryptor吗?非常感谢您帮助我解决这个问题。 - Crack_Code

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