iOS中的PBEWithMD5AndDES加密 [英] PBEWithMD5AndDES Encryption in iOS

查看:165
本文介绍了iOS中的PBEWithMD5AndDES加密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



我现在在不同的类中有两个相同的方法相同的方法,并且我们并排运行它们。他们得到不同的加密值,而不能解密他人。我很。愧于此。



这是加密/解密的帮助类。

  @实现CryptoHelper 

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

}
return self;
}

#pragma mark -
#pragma mark String具体方法

/ **
*加密一个字符串进行社会爆炸服务。
*
* @param plainString要加密的字符串;
*
* @return NSString加密的字符串。
* /
- (NSString *)encryptString:(NSString *)plainString {

//将字符串转换为数据并加密
NSData * data = [self encryptPBEWithMD5AndDESData :[plainString dataUsingEncoding:NSUTF8StringEncoding] password:@1111];



//从数据获取加密的字符串
return [data base64EncodingWithLineLength:1024];

}


/ **
*从社会爆炸服务中描述一个字符串。
*
* @param plainString要解密的字符串;
*
* @return NSString解密的字符串。
* /
- (NSString *)decryptString :( NSString *)encryptedString {

//解密数据
NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:@1111];

//提取和返回字符串
return [NSString stringWithUTF8String:[data bytes]];

}


#pragma mark -
#pragma mark加密方法

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


- (NSData *)decryptPBEWithMD5AndDESData ; (NSString *)密码方向:(int)方向
{
NSLog(@)
$ b - (NSData *)encodePBEWithMD5AndDESData :( NSData *)inData password: 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; //分配结果存储
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();

//需要设置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) ))
{

EVP_CIPHER_CTX_set_padding(& cipherCtx,1);

int blockSize = EVP_CIPHER_CTX_block_size(& cipherCtx);
int allocLen = mDataLen + blockSize + 1; //加1对解密的空终止符
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:\\\
\tlib:%s\\\
\tfunction:%s\\\
\treason:%s\\\

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(@加密结果:%@ \\\
,[encryptedData base64EncodingWithLineLength:1024]);

EVP_cleanup();

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

}

@end

m尝试复制这个java函数的结果。我有相同的盐。

  public DesEncrypter(String passPhrase){
try {
//创建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());

//准备参数到密码
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,iterationCount);

//创建密码
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){
}
}


解决方案

不知道协议在这里接受答案/ upvoting他们。如果我这样做错了,我很抱歉。答案原来是盐中没有最后一个字节。我实际上并不需要使用3DES加密的IV。我提出了另一个答案,因为它有助于更​​多地了解加密。



这是c类的最终目标。

  @implementation CryptoHelper 

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

}
return self;
}

#pragma mark -
#pragma mark String具体方法

/ **
*加密一个字符串进行社会爆炸服务。
*
* @param plainString要加密的字符串;
*
* @return NSString加密的字符串。
* /
- (NSString *)encryptString:(NSString *)plainString {

//将字符串转换为数据并加密
NSData * data = [self encryptPBEWithMD5AndDESData :[plainString dataUsingEncoding:NSUTF8StringEncoding] password:@1111];



//从数据获取加密的字符串
return [data base64EncodingWithLineLength:1024];

}


/ **
*从社会爆炸服务中描述一个字符串。
*
* @param plainString要解密的字符串;
*
* @return NSString解密的字符串。
* /
- (NSString *)decryptString :( NSString *)encryptedString {

//解密数据
NSData * data = [self decryptPBEWithMD5AndDESData:[NSData dataWithBase64EncodedString:encryptedString] password:@1111];

//提取和返回字符串
return [NSString stringWithUTF8String:[data bytes]];

}


#pragma mark -
#pragma mark加密方法

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


- (NSData *)decryptPBEWithMD5AndDESData ; (NSString *)密码方向:(int)方向
{
NSLog(@)
$ b - (NSData *)encodePBEWithMD5AndDESData :( NSData *)inData password: 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; //分配结果存储
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) ))
{

EVP_CIPHER_CTX_set_padding(& cipherCtx,1);

int blockSize = EVP_CIPHER_CTX_block_size(& cipherCtx);
int allocLen = mDataLen + blockSize + 1; //加1对解密的空终止符
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:\\\
\tlib:%s\\\
\tfunction:%s\\\
\treason:%s\\\

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(@加密结果:%@ \\\
,[encryptedData base64EncodingWithLineLength:1024]);

EVP_cleanup();

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

}

@end


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) {
    }
}

解决方案

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

这篇关于iOS中的PBEWithMD5AndDES加密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆