iPhone应用程序中的3DES加密始终会产生与Java中3DES加密不同的结果

时间:2012-02-19 15:52:42

标签: java iphone objective-c encryption 3des

我必须在我的iPhone应用程序中加密字符串。加密方案是3DES / CBC / PKCS5填充,我必须在objective-c转换这个Java代码:

public class MessageEncrypt {

public String encryptString(String message, String seckey) throws Exception{
    byte[] encData = encrypt(message, seckey);

    return this.getHexString(encData, "");
}

public String decryptString(String message, String seckey) throws Exception{
    return decrypt(this.getBArray(message), seckey);
}

private byte[] encrypt(String message, String seckey) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest(seckey.getBytes("utf-8"));
    final byte[] keyBytes = acopyof(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);

    final byte[] plainTextBytes = message.getBytes("utf-8");
    final byte[] cipherText = cipher.doFinal(plainTextBytes);
    // final String encodedCipherText = new sun.misc.BASE64Encoder()
    // .encode(cipherText);

    return cipherText;
}

private String decrypt(byte[] message, String seckey) throws Exception {
    final MessageDigest md = MessageDigest.getInstance("md5");
    final byte[] digestOfPassword = md.digest(seckey.getBytes("utf-8"));
    final byte[] keyBytes = acopyof(digestOfPassword, 24);
    for (int j = 0, k = 16; j < 8;) {
        keyBytes[k++] = keyBytes[j++];
    }

    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    decipher.init(Cipher.DECRYPT_MODE, key, iv);

    final byte[] plainText = decipher.doFinal(message);

    return new String(plainText, "UTF-8");
}

private String getHexString(byte[] barray, String delim) {
    StringBuffer buffer = new StringBuffer();


    for (int i = 0; i < barray.length; i++) {
        int ii = barray[i] & 0xFF;
        String bInt = Integer.toHexString(ii);
        if (ii < 16) {
            bInt = "0" + bInt.toUpperCase();
        }
        buffer.append(bInt);
        if (i < barray.length - 1) {
            buffer.append(delim);
        }
    }

    return buffer.toString().toUpperCase();
}

private byte[] getBArray(String bString) {
    byte[] retBytes;

    if (bString.length() % 2 != 0) {
        return new byte[0];
    }
    retBytes = new byte[bString.length() / 2];

    for (int i = 0; i < bString.length() / 2; i++) {
        retBytes[i] = (byte) ((Character.digit(bString.charAt(2 * i), 16) << 4) + Character.digit(bString.charAt(2 * i + 1), 16));
    }
    return retBytes;
}

public static byte[] acopyof(byte[] orig, int newlength){
    byte[] copya = new byte[newlength];
    for(int i=0;i< orig.length;i++){
        copya[i]=orig[i];
    }
    for(int i=orig.length;i<newlength;i++){
        copya[i]=0x0;
    }
    return copya;
}

}

我使用了这个Objective-c方法来匹配这些规范:

+(NSString*)doCipher:(NSString*)sTextIn:(CCOperation)encryptOrDecrypt {

// const void * vplainText;    // size_t plainTextBufferSize;

NSMutableData *dTextIn;

if (encryptOrDecrypt == kCCDecrypt)
{



}
else
{

    dTextIn = [[sTextIn dataUsingEncoding: NSASCIIStringEncoding]mutableCopy];

}

NSLog(@"************** Init encrypting **********************************");

NSLog(@"This is data to encrypt %@",dTextIn);

CCCryptorStatus ccStatus;
uint8_t *bufferPtr = NULL;
size_t bufferPtrSize = 0;
size_t movedBytes = 0;
//  uint8_t ivkCCBlockSize3DES;

bufferPtrSize = ([dTextIn length] + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x00, bufferPtrSize);



// Initialization vector; in this case 8 bytes.

uint8_t iv[kCCBlockSize3DES];
memset((void *) iv, 0x8, (size_t) sizeof(iv));



UserAndPassword *userPass = [[UserAndPassword alloc]init];

NSString *userPassword = userPass.password;

NSLog(@"This is my password %@",userPassword);

NSString *key = [userPassword MD5String];

NSLog(@"This is MD5 key %@",key);


NSMutableData *_keyData = [[key dataUsingEncoding:NSASCIIStringEncoding]mutableCopy];

unsigned char *bytePtr = (unsigned char *)[_keyData bytes];

NSLog(@"Bytes of key are %s ", bytePtr);

NSLog(@"******** This is my key length %d *******",[_keyData length]);

[_keyData setLength:24];

 unsigned char *bytePtr1 = (unsigned char *)[_keyData bytes];

 NSLog(@"******** Bytes of key are %s ************", bytePtr1);

 NSLog(@"*********  This is key length %d ***********",[_keyData length]);



ccStatus = CCCrypt(encryptOrDecrypt, // CCoperation op
                   kCCAlgorithm3DES, // CCAlgorithm alg
                   kCCOptionPKCS7Padding, // CCOptions
                   [_keyData bytes], // const void *key
                   kCCKeySize3DES, // 3DES key size length 24 bit
                   iv,  //const void *iv,
                   [dTextIn bytes], // const void *dataIn  
                   [dTextIn length], // size_t dataInLength
                   (void *)bufferPtr, // void *dataOut
                   bufferPtrSize, // size_t dataOutAvailable
                   &movedBytes); // size_t *dataOutMoved

if (ccStatus == kCCParamError) return @"PARAM ERROR";
else if (ccStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
else if (ccStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
else if (ccStatus == kCCAlignmentError) return @"ALIGNMENT";
else if (ccStatus == kCCDecodeError) return @"DECODE ERROR";
else if (ccStatus == kCCUnimplemented) return @"UNIMPLEMENTED";


NSString *result;

if (encryptOrDecrypt == kCCDecrypt)
{

    // result = [[NSString alloc] initWithData: [NSData dataWithBytes:(const void *)bufferPtr length:[(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding]];
    result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding] autorelease];
}
else
{
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];

    NSLog(@"This is my encrypted bytes %@", myData);

    result = [NSString dataToHex:myData];

    NSLog(@"This is my encrypted string %@", result);

    NSLog(@"********************** Encryption is finished ************");

}
return result;

}

我没有设法匹配使用Java代码获得的3DES加密,我不明白哪个是问题。

提前谢谢你, 墩

3 个答案:

答案 0 :(得分:2)

Java版本使用IV为0,而Objective-C版本使用8s。

使用一轮MD5并且没有盐从密码中获取密钥是不安全的。使用密钥派生算法,如PBKDF2。

答案 1 :(得分:1)

我没有查看所有代码,但跳出来的第一件事是输入字符串的字符编码方案是不同的。在您的Java算法中,您将所有字符串编码为UTF-8,但在您的ObjC算法中,您将字符串编码为ASCII,除了最简单的输入字符串之外,这是一个潜在的问题。

答案 2 :(得分:1)

看起来你有一个字符编码问题。您的Objective-C代码基于ASCII(8位)字符,但您需要在将Java字符串解析为字节时切换(16位)UNICODE字符解码。另一方面,根据您正在处理的CPU架构(Little或Big Endianness),考虑阵列中的字节排序可能是个好主意。