iOS 中的 PBEWithMD5AndDES 加密

发布于 2024-11-30 20:58:39 字数 6342 浏览 1 评论 0原文

我在 iOS 中遇到 PBEWithMD5AndDES 加密问题。我已经使用它加密和解密了字符串, https://gist.github.com/788840/24bc73ecd0ac3134cbd242892c74a06ac561d37b

问题是我得到不同的加密值,具体取决于我的方法所在的类。例如,我将所有加密方法移至辅助类中并运行它。我注意到我得到了不同的加密值。

我现在在不同的类中有相同方法的两个相同版本,并且我并排运行它们。他们得到不同的加密值,并且一个人无法解密另一个人的。我对此有点困惑。

这是执行加密/解密的帮助程序类。

@implementation CryptoHelper

#pragma mark -
#pragma mark Init Methods
- (id)init
{
    if(self = [super init])
    {

    }
    return self;
}

#pragma mark -
#pragma mark String Specific Methods

/** 
 *  Encrypts a string for social blast service. 
 *  
 *  @param  plainString The string to encrypt;
 *
 *  @return NSString    The encrypted string. 
 */
- (NSString *)encryptString: (NSString *) plainString{

    // Convert string to data and encrypt
    NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:@"1111"];



    // Get encrypted string from data
    return [data base64EncodingWithLineLength:1024];

}


/** 
 *  Descrypts a string from social blast service. 
 *  
 *  @param  plainString The string to decrypt;
 *
 *  @return NSString    The decrypted string. 
 */
- (NSString *)decryptString: (NSString *) encryptedString{

    // decrypt the data
    NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:@"1111"];

    // extract and return string
    return [NSString stringWithUTF8String:[data bytes]];

}


#pragma mark -
#pragma mark Crypto Methods

- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}

- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}

- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
    NSLog(@"helper data = %@", inData);

    static const char gSalt[] =
    {
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA
    };

    unsigned char *salt = (unsigned char *)gSalt;
    int saltLen = strlen(gSalt);
    int iterations = 15;

    EVP_CIPHER_CTX cipherCtx;


    unsigned char *mResults; // allocated storage of results
    int mResultsLen = 0;

    const char *cPassword = [password UTF8String];

    unsigned char *mData = (unsigned char *)[inData bytes];
    int mDataLen = [inData length];


    SSLeay_add_all_algorithms();
    /*X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
                                          iterations, salt, saltLen);*/
        const EVP_CIPHER *cipher = EVP_des_cbc();

    // Need to set with iv
    X509_ALGOR *algorithm = PKCS5_pbe2_set_iv(cipher, iterations, 
                                          salt, saltLen, salt, NID_hmacWithMD5);


    memset(&cipherCtx, 0, sizeof(cipherCtx));

    if (algorithm != NULL)
    {
        EVP_CIPHER_CTX_init(&(cipherCtx));



        if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
                               algorithm->parameter, &(cipherCtx), direction))
        {

            EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);

            int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
            int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
            mResults = (unsigned char *)OPENSSL_malloc(allocLen);


            unsigned char *in_bytes = mData;
            int inLen = mDataLen;
            unsigned char *out_bytes = mResults;
            int outLen = 0;



            int outLenPart1 = 0;
            if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
            {
                out_bytes += outLenPart1;
                int outLenPart2 = 0;
                if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
                {
                    outLen += outLenPart1 + outLenPart2;
                    mResults[outLen] = 0;
                    mResultsLen = outLen;
                }
            } else {
                unsigned long err = ERR_get_error();

                ERR_load_crypto_strings();
                ERR_load_ERR_strings();
                char errbuff[256];
                errbuff[0] = 0;
                ERR_error_string_n(err, errbuff, sizeof(errbuff));
                NSLog(@"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
                      ERR_lib_error_string(err),
                      ERR_func_error_string(err),
                      ERR_reason_error_string(err));
                ERR_free_strings();
            }


            NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;


            //NSLog(@"encryption result: %@\n", [encryptedData base64EncodingWithLineLength:1024]);

            EVP_cleanup();

            return encryptedData;
        }
    }
    EVP_cleanup();
    return nil;

}

@end

我正在尝试复制这个 java 函数的结果。我有同样的盐。

public DesEncrypter(String passPhrase) {
    try {
        // Create the key
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance(
            "PBEWithMD5AndDES").generateSecret(keySpec);
        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

        // Create the ciphers
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
}

I'm having an issue with PBEWithMD5AndDES encryption in iOS. I've got my strings encrypting and decrypting using this, https://gist.github.com/788840/24bc73ecd0ac3134cbd242892c74a06ac561d37b.

The problem is I get different encrypted values depending on which class my methods are in. For example, I moved all the encryption methods into a helper class and ran it. I noticed I was getting a different encrypted value.

I now have two identical versions of the same method in different classes and I'm running them side by side. They get different encrypted values, and one cannot decrypt the others'. I'm kind of stumped on this.

Here's the helper class that does encryption/decryption.

@implementation CryptoHelper

#pragma mark -
#pragma mark Init Methods
- (id)init
{
    if(self = [super init])
    {

    }
    return self;
}

#pragma mark -
#pragma mark String Specific Methods

/** 
 *  Encrypts a string for social blast service. 
 *  
 *  @param  plainString The string to encrypt;
 *
 *  @return NSString    The encrypted string. 
 */
- (NSString *)encryptString: (NSString *) plainString{

    // Convert string to data and encrypt
    NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:@"1111"];



    // Get encrypted string from data
    return [data base64EncodingWithLineLength:1024];

}


/** 
 *  Descrypts a string from social blast service. 
 *  
 *  @param  plainString The string to decrypt;
 *
 *  @return NSString    The decrypted string. 
 */
- (NSString *)decryptString: (NSString *) encryptedString{

    // decrypt the data
    NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:@"1111"];

    // extract and return string
    return [NSString stringWithUTF8String:[data bytes]];

}


#pragma mark -
#pragma mark Crypto Methods

- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}

- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}

- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
    NSLog(@"helper data = %@", inData);

    static const char gSalt[] =
    {
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA
    };

    unsigned char *salt = (unsigned char *)gSalt;
    int saltLen = strlen(gSalt);
    int iterations = 15;

    EVP_CIPHER_CTX cipherCtx;


    unsigned char *mResults; // allocated storage of results
    int mResultsLen = 0;

    const char *cPassword = [password UTF8String];

    unsigned char *mData = (unsigned char *)[inData bytes];
    int mDataLen = [inData length];


    SSLeay_add_all_algorithms();
    /*X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
                                          iterations, salt, saltLen);*/
        const EVP_CIPHER *cipher = EVP_des_cbc();

    // Need to set with iv
    X509_ALGOR *algorithm = PKCS5_pbe2_set_iv(cipher, iterations, 
                                          salt, saltLen, salt, NID_hmacWithMD5);


    memset(&cipherCtx, 0, sizeof(cipherCtx));

    if (algorithm != NULL)
    {
        EVP_CIPHER_CTX_init(&(cipherCtx));



        if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
                               algorithm->parameter, &(cipherCtx), direction))
        {

            EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);

            int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
            int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
            mResults = (unsigned char *)OPENSSL_malloc(allocLen);


            unsigned char *in_bytes = mData;
            int inLen = mDataLen;
            unsigned char *out_bytes = mResults;
            int outLen = 0;



            int outLenPart1 = 0;
            if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
            {
                out_bytes += outLenPart1;
                int outLenPart2 = 0;
                if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
                {
                    outLen += outLenPart1 + outLenPart2;
                    mResults[outLen] = 0;
                    mResultsLen = outLen;
                }
            } else {
                unsigned long err = ERR_get_error();

                ERR_load_crypto_strings();
                ERR_load_ERR_strings();
                char errbuff[256];
                errbuff[0] = 0;
                ERR_error_string_n(err, errbuff, sizeof(errbuff));
                NSLog(@"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
                      ERR_lib_error_string(err),
                      ERR_func_error_string(err),
                      ERR_reason_error_string(err));
                ERR_free_strings();
            }


            NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;


            //NSLog(@"encryption result: %@\n", [encryptedData base64EncodingWithLineLength:1024]);

            EVP_cleanup();

            return encryptedData;
        }
    }
    EVP_cleanup();
    return nil;

}

@end

I'm trying to duplicate the results of this java function. I have the same salt.

public DesEncrypter(String passPhrase) {
    try {
        // Create the key
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
        SecretKey key = SecretKeyFactory.getInstance(
            "PBEWithMD5AndDES").generateSecret(keySpec);
        ecipher = Cipher.getInstance(key.getAlgorithm());
        dcipher = Cipher.getInstance(key.getAlgorithm());

        // Prepare the parameter to the ciphers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

        // Create the ciphers
        ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
        dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
    } catch (java.security.InvalidAlgorithmParameterException e) {
    } catch (java.security.spec.InvalidKeySpecException e) {
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

菊凝晚露 2024-12-07 20:58:39

接受的答案似乎使用了 iOS SDK 中未包含的 OpenSSL。这是一个使用附带的 CommonCrypto 库(在 libSystem 中)的加密和解密解决方案。我是一个 ObjC n00b,所以对这段代码持保留态度。顺便说一下,这段代码将成功解密使用java的PBEWithMD5AndDES密码加密的数据。希望这能为其他人节省一两天的时间。

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonCryptor.h>


+(NSData*) cryptPBEWithMD5AndDES:(CCOperation)op usingData:(NSData*)data withPassword:(NSString*)password andSalt:(NSData*)salt andIterating:(int)numIterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH];
    memset(md5, 0, CC_MD5_DIGEST_LENGTH);
    NSData* passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [passwordData bytes], [passwordData length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (int i=1; i<numIterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    size_t cryptoResultDataBufferSize = [data length] + kCCBlockSizeDES;
    unsigned char cryptoResultDataBuffer[cryptoResultDataBufferSize];
    size_t dataMoved = 0;

    unsigned char iv[kCCBlockSizeDES];
    memcpy(iv, md5 + (CC_MD5_DIGEST_LENGTH/2), sizeof(iv)); //iv is the second half of the MD5 from building the key

    CCCryptorStatus status =
        CCCrypt(op, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, (CC_MD5_DIGEST_LENGTH/2), iv, [data bytes], [data length],
            cryptoResultDataBuffer, cryptoResultDataBufferSize, &dataMoved);

    if(0 == status) {
        return [NSData dataWithBytes:cryptoResultDataBuffer length:dataMoved];
    } else {
        return NULL;
    }
}

The accepted answer appears to use OpenSSL which is not included in the iOS SDK. Here is an encrypting and decrypting solution that uses the included CommonCrypto library (in libSystem). I'm a bit of an ObjC n00b, so take this code with a grain of salt. By the way, this code will successfully decrypt data encrypted using java's PBEWithMD5AndDES cipher. Hopefully this will save a day or two for someone else.

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonCryptor.h>


+(NSData*) cryptPBEWithMD5AndDES:(CCOperation)op usingData:(NSData*)data withPassword:(NSString*)password andSalt:(NSData*)salt andIterating:(int)numIterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH];
    memset(md5, 0, CC_MD5_DIGEST_LENGTH);
    NSData* passwordData = [password dataUsingEncoding:NSUTF8StringEncoding];

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [passwordData bytes], [passwordData length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (int i=1; i<numIterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    size_t cryptoResultDataBufferSize = [data length] + kCCBlockSizeDES;
    unsigned char cryptoResultDataBuffer[cryptoResultDataBufferSize];
    size_t dataMoved = 0;

    unsigned char iv[kCCBlockSizeDES];
    memcpy(iv, md5 + (CC_MD5_DIGEST_LENGTH/2), sizeof(iv)); //iv is the second half of the MD5 from building the key

    CCCryptorStatus status =
        CCCrypt(op, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, (CC_MD5_DIGEST_LENGTH/2), iv, [data bytes], [data length],
            cryptoResultDataBuffer, cryptoResultDataBufferSize, &dataMoved);

    if(0 == status) {
        return [NSData dataWithBytes:cryptoResultDataBuffer length:dataMoved];
    } else {
        return NULL;
    }
}
假情假意假温柔 2024-12-07 20:58:39

问题是你没有为你的加密指定IV,这样会自动为你生成一个随机数,这也是你每次得到不同结果的原因。

尝试使用 PKCS5_pbe2_set_iv 而不是 PKCS5_pbe2_set 提供显式 IV 值,您可以随机选择该值,就像您的盐值一样。

The problem is that you are not specifying an IV for your encryption, this way a random number will automatically be generated for you, that's also the reason why you get a different result each time.

Try using PKCS5_pbe2_set_iv instead of PKCS5_pbe2_set providing an explicit IV value, that you may randomly choose, much like your salt value.

岁月如刀 2024-12-07 20:58:39

根据 johwayner 的回复,我对此进行了一些修复,以便从 jasypt 解密 Java 的 PBEWithMD5AndDES。这就是我最终得到的结果:

@interface NSData (PBEEncryption)

/**
 * Decrypt the receiver using PKCS#5 PBE with MD5 and DES assuming that the salt is prefixed into the first 8 bytes of
 * the data and the number of key obtention iterations is 1000. This is compatible with Java's PBEWithMD5AndDES
 * encryption when the encryption generates a random salt for the data (the default when providing no salt).
 */
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password;

/**
 * Decrypt the receiver using PKCS#5 PBE with MD5 and DES. Explicitly provide the salt and number of key obtention
 * iterations.
 */
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations;

@end


@implementation NSData (PBEEncryption)

- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password {
    NSData *salt = nil;
    NSData *input = self;
    if ([input length] > 8) {
        salt = [input subdataWithRange:NSMakeRange(0, 8)];
        input = [input subdataWithRange:NSMakeRange(8, [input length] - 8)];
    }
    return [input decrytpPBEWithMD5AndDESUsingPassword:password salt:salt iterations:1000];
}

- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH] = {};

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [password bytes], [password length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (NSUInteger i = 1; i < iterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    // initialization vector is the second half of the MD5 from building the key
    unsigned char iv[kCCBlockSizeDES];
    assert(kCCBlockSizeDES == CC_MD5_DIGEST_LENGTH / 2);
    memcpy(iv, md5 + kCCBlockSizeDES, sizeof(iv));

    NSMutableData *output = [NSMutableData dataWithLength:([self length] + kCCBlockSize3DES)];
    size_t outputLength = 0;
    CCCryptorStatus status =
        CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, kCCBlockSizeDES, iv,
                [self bytes], [self length], [output mutableBytes], [output length], &outputLength);

    if (status == kCCSuccess) { [output setLength:outputLength]; }
    else { output = nil; }

    return output;
}

@end

像这样使用:

NSString *password = @"myTopSecretPassword";
NSData *inputData = [NSData dataFromBase64String:@"base64string"];
NSData *outputData = [inputData decrytpPBEWithMD5AndDESUsingPassword:
                      [password dataUsingEncoding:NSUTF8StringEncoding]];

Using johwayner's response, I fixed this up a little for my purposes of decrypting Java's PBEWithMD5AndDES from jasypt. Here's what I ended up with:

@interface NSData (PBEEncryption)

/**
 * Decrypt the receiver using PKCS#5 PBE with MD5 and DES assuming that the salt is prefixed into the first 8 bytes of
 * the data and the number of key obtention iterations is 1000. This is compatible with Java's PBEWithMD5AndDES
 * encryption when the encryption generates a random salt for the data (the default when providing no salt).
 */
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password;

/**
 * Decrypt the receiver using PKCS#5 PBE with MD5 and DES. Explicitly provide the salt and number of key obtention
 * iterations.
 */
- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations;

@end


@implementation NSData (PBEEncryption)

- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password {
    NSData *salt = nil;
    NSData *input = self;
    if ([input length] > 8) {
        salt = [input subdataWithRange:NSMakeRange(0, 8)];
        input = [input subdataWithRange:NSMakeRange(8, [input length] - 8)];
    }
    return [input decrytpPBEWithMD5AndDESUsingPassword:password salt:salt iterations:1000];
}

- (NSData *)decrytpPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH] = {};

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [password bytes], [password length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (NSUInteger i = 1; i < iterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    // initialization vector is the second half of the MD5 from building the key
    unsigned char iv[kCCBlockSizeDES];
    assert(kCCBlockSizeDES == CC_MD5_DIGEST_LENGTH / 2);
    memcpy(iv, md5 + kCCBlockSizeDES, sizeof(iv));

    NSMutableData *output = [NSMutableData dataWithLength:([self length] + kCCBlockSize3DES)];
    size_t outputLength = 0;
    CCCryptorStatus status =
        CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, kCCBlockSizeDES, iv,
                [self bytes], [self length], [output mutableBytes], [output length], &outputLength);

    if (status == kCCSuccess) { [output setLength:outputLength]; }
    else { output = nil; }

    return output;
}

@end

Use like so:

NSString *password = @"myTopSecretPassword";
NSData *inputData = [NSData dataFromBase64String:@"base64string"];
NSData *outputData = [inputData decrytpPBEWithMD5AndDESUsingPassword:
                      [password dataUsingEncoding:NSUTF8StringEncoding]];
So要识趣 2024-12-07 20:58:39

不确定这里接受答案/投票的协议是什么。如果我做错了,我深表歉意。答案是盐中缺少最后一个字节。实际上我不需要 3DES 加密的 IV。我赞成另一个答案,因为它有助于更​​多地了解加密。

这是最终的目标 c 类。

@implementation CryptoHelper

#pragma mark -
#pragma mark Init Methods
- (id)init
{
    if(self = [super init])
    {

    }
    return self;
}

#pragma mark -
#pragma mark String Specific Methods

/** 
 *  Encrypts a string for social blast service. 
 *  
 *  @param  plainString The string to encrypt;
 *
 *  @return NSString    The encrypted string. 
 */
- (NSString *)encryptString: (NSString *) plainString{

    // Convert string to data and encrypt
    NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:@"1111"];



    // Get encrypted string from data
    return [data base64EncodingWithLineLength:1024];

}


/** 
 *  Descrypts a string from social blast service. 
 *  
 *  @param  plainString The string to decrypt;
 *
 *  @return NSString    The decrypted string. 
 */
- (NSString *)decryptString: (NSString *) encryptedString{

    // decrypt the data
    NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:@"1111"];

    // extract and return string
    return [NSString stringWithUTF8String:[data bytes]];

}


#pragma mark -
#pragma mark Crypto Methods

- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}

- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}

- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
    NSLog(@"helper data = %@", inData);

    static const char gSalt[] =
    {
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
        (unsigned char)0x00
    };

    unsigned char *salt = (unsigned char *)gSalt;
    int saltLen = strlen(gSalt);
    int iterations = 15;

    EVP_CIPHER_CTX cipherCtx;


    unsigned char *mResults; // allocated storage of results
    int mResultsLen = 0;

    const char *cPassword = [password UTF8String];

    unsigned char *mData = (unsigned char *)[inData bytes];
    int mDataLen = [inData length];


    SSLeay_add_all_algorithms();
    X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
                                          iterations, salt, saltLen);



    memset(&cipherCtx, 0, sizeof(cipherCtx));

    if (algorithm != NULL)
    {
        EVP_CIPHER_CTX_init(&(cipherCtx));



        if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
                               algorithm->parameter, &(cipherCtx), direction))
        {

            EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);

            int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
            int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
            mResults = (unsigned char *)OPENSSL_malloc(allocLen);


            unsigned char *in_bytes = mData;
            int inLen = mDataLen;
            unsigned char *out_bytes = mResults;
            int outLen = 0;



            int outLenPart1 = 0;
            if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
            {
                out_bytes += outLenPart1;
                int outLenPart2 = 0;
                if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
                {
                    outLen += outLenPart1 + outLenPart2;
                    mResults[outLen] = 0;
                    mResultsLen = outLen;
                }
            } else {
                unsigned long err = ERR_get_error();

                ERR_load_crypto_strings();
                ERR_load_ERR_strings();
                char errbuff[256];
                errbuff[0] = 0;
                ERR_error_string_n(err, errbuff, sizeof(errbuff));
                NSLog(@"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
                      ERR_lib_error_string(err),
                      ERR_func_error_string(err),
                      ERR_reason_error_string(err));
                ERR_free_strings();
            }


            NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;


            //NSLog(@"encryption result: %@\n", [encryptedData base64EncodingWithLineLength:1024]);

            EVP_cleanup();

            return encryptedData;
        }
    }
    EVP_cleanup();
    return nil;

}

@end

Not sure what the protocol is here for accepting answers/upvoting them. I apologize if I'm doing this wrong. The answer turned out to be the lack of a final byte in the salt. I actually didn't need the IV with the 3DES encryption. I upvoted the other answer because it was helpful in understanding more about encryption.

Here's the final objective c class.

@implementation CryptoHelper

#pragma mark -
#pragma mark Init Methods
- (id)init
{
    if(self = [super init])
    {

    }
    return self;
}

#pragma mark -
#pragma mark String Specific Methods

/** 
 *  Encrypts a string for social blast service. 
 *  
 *  @param  plainString The string to encrypt;
 *
 *  @return NSString    The encrypted string. 
 */
- (NSString *)encryptString: (NSString *) plainString{

    // Convert string to data and encrypt
    NSData *data = [self encryptPBEWithMD5AndDESData:[plainString dataUsingEncoding:NSUTF8StringEncoding] password:@"1111"];



    // Get encrypted string from data
    return [data base64EncodingWithLineLength:1024];

}


/** 
 *  Descrypts a string from social blast service. 
 *  
 *  @param  plainString The string to decrypt;
 *
 *  @return NSString    The decrypted string. 
 */
- (NSString *)decryptString: (NSString *) encryptedString{

    // decrypt the data
    NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:@"1111"];

    // extract and return string
    return [NSString stringWithUTF8String:[data bytes]];

}


#pragma mark -
#pragma mark Crypto Methods

- (NSData *)encryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:1];
}

- (NSData *)decryptPBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password {
    return [self encodePBEWithMD5AndDESData:inData password:password direction:0];
}

- (NSData *)encodePBEWithMD5AndDESData:(NSData *)inData password:(NSString *)password direction:(int)direction
{
    NSLog(@"helper data = %@", inData);

    static const char gSalt[] =
    {
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
        (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA, (unsigned char)0xAA,
        (unsigned char)0x00
    };

    unsigned char *salt = (unsigned char *)gSalt;
    int saltLen = strlen(gSalt);
    int iterations = 15;

    EVP_CIPHER_CTX cipherCtx;


    unsigned char *mResults; // allocated storage of results
    int mResultsLen = 0;

    const char *cPassword = [password UTF8String];

    unsigned char *mData = (unsigned char *)[inData bytes];
    int mDataLen = [inData length];


    SSLeay_add_all_algorithms();
    X509_ALGOR *algorithm = PKCS5_pbe_set(NID_pbeWithMD5AndDES_CBC,
                                          iterations, salt, saltLen);



    memset(&cipherCtx, 0, sizeof(cipherCtx));

    if (algorithm != NULL)
    {
        EVP_CIPHER_CTX_init(&(cipherCtx));



        if (EVP_PBE_CipherInit(algorithm->algorithm, cPassword, strlen(cPassword),
                               algorithm->parameter, &(cipherCtx), direction))
        {

            EVP_CIPHER_CTX_set_padding(&cipherCtx, 1);

            int blockSize = EVP_CIPHER_CTX_block_size(&cipherCtx);
            int allocLen = mDataLen + blockSize + 1; // plus 1 for null terminator on decrypt
            mResults = (unsigned char *)OPENSSL_malloc(allocLen);


            unsigned char *in_bytes = mData;
            int inLen = mDataLen;
            unsigned char *out_bytes = mResults;
            int outLen = 0;



            int outLenPart1 = 0;
            if (EVP_CipherUpdate(&(cipherCtx), out_bytes, &outLenPart1, in_bytes, inLen))
            {
                out_bytes += outLenPart1;
                int outLenPart2 = 0;
                if (EVP_CipherFinal(&(cipherCtx), out_bytes, &outLenPart2))
                {
                    outLen += outLenPart1 + outLenPart2;
                    mResults[outLen] = 0;
                    mResultsLen = outLen;
                }
            } else {
                unsigned long err = ERR_get_error();

                ERR_load_crypto_strings();
                ERR_load_ERR_strings();
                char errbuff[256];
                errbuff[0] = 0;
                ERR_error_string_n(err, errbuff, sizeof(errbuff));
                NSLog(@"OpenSLL ERROR:\n\tlib:%s\n\tfunction:%s\n\treason:%s\n",
                      ERR_lib_error_string(err),
                      ERR_func_error_string(err),
                      ERR_reason_error_string(err));
                ERR_free_strings();
            }


            NSData *encryptedData = [NSData dataWithBytes:mResults length:mResultsLen]; //(NSData *)encr_buf;


            //NSLog(@"encryption result: %@\n", [encryptedData base64EncodingWithLineLength:1024]);

            EVP_cleanup();

            return encryptedData;
        }
    }
    EVP_cleanup();
    return nil;

}

@end
原来分手还会想你 2024-12-07 20:58:39

我要感谢wbyyoung。他的回答帮助我解开了如何从 iOS 加密数据并从 Java 解密数据的谜团。以下是我对其代码所做的补充。

诀窍是获取用于加密数据的盐,并将其添加到结果中。然后 Java 将能够解密它。

@implementation NSData (PBEEncryption)

- (NSData *)encryptPBEWithMD5AndDESUsingPassword:(NSData *)password {
    unsigned char gSalt[] =
    {
        (unsigned char)0x18, (unsigned char)0x79, (unsigned char)0x6D, (unsigned char)0x6D,
        (unsigned char)0x35, (unsigned char)0x3A, (unsigned char)0x6A, (unsigned char)0x60,
        (unsigned char)0x00
    };

    NSData *salt = nil;
    salt = [NSData dataWithBytes:gSalt length:strlen(gSalt)];

    NSData* encrypted = [self encryptPBEWithMD5AndDESUsingPassword:password salt:salt iterations:1000];
    NSMutableData* result = [NSMutableData dataWithData:salt];
    [result appendData:encrypted];
    return [NSData dataWithData:result];

}

- (NSData *)encryptPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH] = {};

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [password bytes], [password length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (NSUInteger i = 1; i < iterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    // initialization vector is the second half of the MD5 from building the key
    unsigned char iv[kCCBlockSizeDES];
    assert(kCCBlockSizeDES == CC_MD5_DIGEST_LENGTH / 2);
    memcpy(iv, md5 + kCCBlockSizeDES, sizeof(iv));

    NSMutableData *output = [NSMutableData dataWithLength:([self length] + kCCBlockSize3DES)];
    size_t outputLength = 0;
    CCCryptorStatus status =
    CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, kCCBlockSizeDES, iv,
            [self bytes], [self length], [output mutableBytes], [output length], &outputLength);

    if (status == kCCSuccess) { [output setLength:outputLength]; }
    else { output = nil; }

    return output;
}


@end

加密字符串的相应 Swift 代码:

static func encryptForOverTheWire(string: String) -> String {
    let stringData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    let passwordData = PASSWORD.dataUsingEncoding(NSUTF8StringEncoding)
    let encryptedData = stringData?.encryptPBEWithMD5AndDESUsingPassword(passwordData)
    let base64 = encryptedData?.base64EncodedDataWithOptions(NSDataBase64EncodingOptions())

    guard base64 != nil else { return "" }

    let result = String(data: base64!, encoding: NSUTF8StringEncoding)
    return result ?? ""
}

I want to thank wbyoung. His answer helped me solve the mystery for how to encrypt Data from iOS and have it decrypted from Java. Below are the additions I made to his Code.

The trick is to take the salt used to encrypt the Data, and prepend it to the result. Java will then be able to decrypt it.

@implementation NSData (PBEEncryption)

- (NSData *)encryptPBEWithMD5AndDESUsingPassword:(NSData *)password {
    unsigned char gSalt[] =
    {
        (unsigned char)0x18, (unsigned char)0x79, (unsigned char)0x6D, (unsigned char)0x6D,
        (unsigned char)0x35, (unsigned char)0x3A, (unsigned char)0x6A, (unsigned char)0x60,
        (unsigned char)0x00
    };

    NSData *salt = nil;
    salt = [NSData dataWithBytes:gSalt length:strlen(gSalt)];

    NSData* encrypted = [self encryptPBEWithMD5AndDESUsingPassword:password salt:salt iterations:1000];
    NSMutableData* result = [NSMutableData dataWithData:salt];
    [result appendData:encrypted];
    return [NSData dataWithData:result];

}

- (NSData *)encryptPBEWithMD5AndDESUsingPassword:(NSData *)password salt:(NSData *)salt iterations:(NSUInteger)iterations {
    unsigned char md5[CC_MD5_DIGEST_LENGTH] = {};

    CC_MD5_CTX ctx;
    CC_MD5_Init(&ctx);
    CC_MD5_Update(&ctx, [password bytes], [password length]);
    CC_MD5_Update(&ctx, [salt bytes], [salt length]);
    CC_MD5_Final(md5, &ctx);

    for (NSUInteger i = 1; i < iterations; i++) {
        CC_MD5(md5, CC_MD5_DIGEST_LENGTH, md5);
    }

    // initialization vector is the second half of the MD5 from building the key
    unsigned char iv[kCCBlockSizeDES];
    assert(kCCBlockSizeDES == CC_MD5_DIGEST_LENGTH / 2);
    memcpy(iv, md5 + kCCBlockSizeDES, sizeof(iv));

    NSMutableData *output = [NSMutableData dataWithLength:([self length] + kCCBlockSize3DES)];
    size_t outputLength = 0;
    CCCryptorStatus status =
    CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, md5, kCCBlockSizeDES, iv,
            [self bytes], [self length], [output mutableBytes], [output length], &outputLength);

    if (status == kCCSuccess) { [output setLength:outputLength]; }
    else { output = nil; }

    return output;
}


@end

The Corresponding Swift Code to Encrypt a String:

static func encryptForOverTheWire(string: String) -> String {
    let stringData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
    let passwordData = PASSWORD.dataUsingEncoding(NSUTF8StringEncoding)
    let encryptedData = stringData?.encryptPBEWithMD5AndDESUsingPassword(passwordData)
    let base64 = encryptedData?.base64EncodedDataWithOptions(NSDataBase64EncodingOptions())

    guard base64 != nil else { return "" }

    let result = String(data: base64!, encoding: NSUTF8StringEncoding)
    return result ?? ""
}
放血 2024-12-07 20:58:39

顺便说一句,我可以让它与 Swift 一起工作。我面临的唯一问题是我从 Objective C 模块获取一个 Data 对象,但是当我尝试转换为 String 时,它给了我 nil。这是代码。请让我知道我在这里做错了什么

static func encrypt(inString: String) -> String? {

    let passwordStr = "blablalba"
    let iterations:Int32 = 19
    let salt = [0x44,  0x44,  0x22,  0x22,  0x56,  0x35,  0xE3, 0x03] as [UInt8]
    let operation: CCOperation = UInt32(kCCEncrypt)
    let saltData = NSData(bytes: salt, length: salt.count)

    let out = CryptoHelper.cryptPBE(withMD5AndDES: operation, using: inString.data(using: .utf8), withPassword: passwordStr, andSalt: saltData as Data, andIterating: iterations) as Data

    let outString = String.init(data: out, encoding: .utf8)

    return outString
}

By the way I am able to get it working with Swift. Only issue I am facing is I am getting a Data object from the objective C module, but when I try to convert to String, it gives me nil. here is the code. Please let me know what is that I am doing wrong here

static func encrypt(inString: String) -> String? {

    let passwordStr = "blablalba"
    let iterations:Int32 = 19
    let salt = [0x44,  0x44,  0x22,  0x22,  0x56,  0x35,  0xE3, 0x03] as [UInt8]
    let operation: CCOperation = UInt32(kCCEncrypt)
    let saltData = NSData(bytes: salt, length: salt.count)

    let out = CryptoHelper.cryptPBE(withMD5AndDES: operation, using: inString.data(using: .utf8), withPassword: passwordStr, andSalt: saltData as Data, andIterating: iterations) as Data

    let outString = String.init(data: out, encoding: .utf8)

    return outString
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文