iOS Android DES 加密不一致

我这里的不一致仅仅就如下代码而言

先看代码


+ (NSString *)desEncodeContent:(NSString *)content key:(NSString *)key
{
   NSString *ciphertext = nil;
   const char *textBytes = [content UTF8String];
   NSUInteger dataLength = [content length];
   unsigned char buffer[1024];
   memset(buffer, 0, sizeof(char));
   size_t numBytesEncrypted = 0;
//    Byte iv[] = {1,2,3,4,5,6,7,8};
   CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                         kCCAlgorithmDES,
                                         kCCOptionPKCS7Padding,
                                         [key UTF8String],
                                         kCCKeySizeDES,
                                         NULL,
                                         textBytes,
                                         dataLength,
                                         buffer,
                                         1024,
                                         &numBytesEncrypted);
   if (cryptStatus == kCCSuccess) {
       NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
       
       ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];
   }
   return ciphertext;
}





private static String encode(String key, byte[] data) {
       try {
           DESKeySpec dks = new DESKeySpec(key.getBytes());
           SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
           
           Key secretKey = keyFactory.generateSecret(dks);
           Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
           IvParameterSpec iv = new IvParameterSpec("12312312".getBytes());
           AlgorithmParameterSpec paramSpec = iv;
           cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
           byte[] bytes = cipher.doFinal(data);
           return Base64.encodeToString(bytes, 0);
       } catch (Exception e) {


           e.printStackTrace();
           return null;
       }
   }


不是向量的问题

不知道读者动是iOS还是java, 我是iOS, 我对java DES这个API看不懂, 但是语法什么的没问题, 仿佛Android是加了向量, 其实不然, 我尝试OC加向量,结果是不行.

是kCCOptionPKCS7Padding的问题, 将其改为kCCOptionPKCS7Padding | kCCOptionECBMode, 就ok了

你可能感兴趣的:(iOS Android DES 加密不一致)