与Java相比,Objective C中的3DES解密产生不同的结果

时间:2014-07-31 12:30:33

标签: java ios objective-c encryption 3des

我必须在Objective C中解密一个字符串。加密方案是DES / ECB / NoPadding,我正在为这个Java代码提供正确的输出,并带有以下输入 data = 741DCDDF1C216EEF和key = D9C44F6D2589255E,输出应为34160D6EADAD6D86

public static String decrypt3DES(String Key, String data) throws Exception
{
    Cipher cipher = null;
    byte[] text = null;
    byte[] desKey = null;
    Key keySpec = null;
    try {

        if (Key.length() <= 16) {
            cipher = Cipher.getInstance("DES/ECB/NoPadding");
            desKey = byteConvertor(Key);
            keySpec = new SecretKeySpec(desKey, "DES");
        } else if (Key.length() >= 32) {
            cipher = Cipher.getInstance("DESede/ECB/NoPadding");
            desKey = byteConvertor(Key);
            keySpec = new SecretKeySpec(desKey, "DESede");
        }
        cipher.init(Cipher.DECRYPT_MODE, keySpec);

        text = cipher.doFinal(byteConvertor(data));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return alpha2Hex(byteArr2String(text));
}

目标C代码:

NSString *token = @"741DCDDF1C216EEF";

NSString *key = @"D9C44F6D2589255E";

const void *vplainText;

size_t plainTextBufferSize;

NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:token options:0];
plainTextBufferSize = [EncryptData length]+1;
vplainText = [EncryptData bytes];

//plainTextBufferSize = [token length];
//vplainText = (const void *)[token UTF8String];

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

bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
memset((void *)bufferPtr, 0x0, bufferPtrSize);

NSString *initVec = @"init Vec";
const void *vkey = (const void *)[key UTF8String];
const void *vinitVec;
vinitVec = (const void *) [initVec UTF8String];

//uint8_t initVect[8];
//bzero(initVect, 8);

ccStatus = CCCrypt(kCCDecrypt,
                   kCCAlgorithmDES,
                   kCCOptionECBMode|0x0000,
                   vkey, //"123456789012345678901234", //key
                   kCCKeySizeDES,
                   NULL,// vinitVec, //"init Vec", //iv,
                   vplainText, //"Your Name", //plainText,
                   plainTextBufferSize,
                   (void *)bufferPtr,
                   bufferPtrSize,
                   &movedBytes);

NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
NSString *decodedString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
NSLog(@"dis is data %@",decodedString);

我在java中获得正确的输出而不是在目标c.please为目标c代码提供解决方案

0 个答案:

没有答案