Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6378623
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:01:55+00:00 2026-05-25T02:01:55+00:00

I’m having an issue with PBEWithMD5AndDES encryption in iOS. I’ve got my strings encrypting

  • 0

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) {
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:01:56+00:00Added an answer on May 25, 2026 at 2:01 am

    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
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.