java版本:
public static String encode(String encryptString, String encryptKey)
throws Exception {
if (encryptString.length() == 0) {
return "";
}
DESKeySpec dks = new DESKeySpec(encryptKey.getBytes());
Key secretKey = SecretKeyFactory.getInstance("DES").generateSecret(dks);
IvParameterSpec paramSpec = new IvParameterSpec(encryptKey.substring(encryptKey.length() - 8).getBytes());
Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
byte[] bytes = cipher.doFinal(encryptString.getBytes("UTF-8"));
String result = new String(Base64.encode(bytes, Base64.DEFAULT), "UTF-8");
if (result.endsWith("\n")) {
result = result.substring(0, result.length() - 1);
}
return result;
}
ios版本:
+(NSString *) encryptUseDES:(NSString *)clearText key:(NSString *)key
{
NSData *data = [clearText dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
unsigned char buffer[1024];
memset(buffer, 0, sizeof(char));
size_t numBytesEncrypted = 0;
NSString * ivStr = [key substringFromIndex:key.length -8];
NSData *testData = [ivStr dataUsingEncoding: NSUTF8StringEncoding];
Byte *testByte = (Byte *)[testData bytes];
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmDES,
kCCOptionPKCS7Padding , --》注意这个不要把kCCOptionECBMode模式加进去就可行了
[key UTF8String],
kCCKeySizeDES,
testByte,
[data bytes],
[data length],
buffer,
1024,
&numBytesEncrypted);
NSString* plainText = nil;
if (cryptStatus == kCCSuccess) {
NSData *dataTemp = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
plainText = [GTMBase64 stringByEncodingData:dataTemp];
}else{
NSLog(@"DES加密失败");
}
return plainText;
}
--------------------------------》
以为是因为 ios只有: kCCOptionPKCS7Padding , 而java 之后kCCOptionPKCS5Padding 导致 这样就可以得到一样的结果了
网友评论