项组密码算(des:每块组加密? 3DES:每块组加三同密)
? ? ? ? ? ? ? ? ? ? ? vkey,? //密钥? ? 加密解密密钥必须致
? ? ? ? ? ? ? ? ? ? ? kCCKeySizeDES,//? DES 密钥(kCCKeySizeDES=8)
? ? ? ? ? ? ? ? ? ? ? iv, //? 选初始矢量
? ? ? ? ? ? ? ? ? ? ? dataIn, // 数据存储单元
? ? ? ? ? ? ? ? ? ? ? dataInLength,// 数据
? ? ? ? ? ? ? ? ? ? ? (void *)dataOut,// 用于返数据
? ? ? ? ? ? ? ? ? ? ? dataOutAvailable,
? ? ? ? ? ? ? ? ? ? ? &dataOutMoved);
? ?
? ? NSString *result = nil;
? ?
? ? if (encryptOperation == kCCDecrypt)//encryptOperation==1? 解码
? ? {
? ? ? ? //解密data数据改变utf-8字符串
? ? ? ? result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved] encoding:NSUTF8StringEncoding];
? ? }
? ? else //encryptOperation==0? (加密程加密数据转base64)
? ? {
? ? ? ? //编码 base64
? ? ? ? NSData *data = [NSData dataWithBytes:(const void *)dataOut length:(NSUInteger)dataOutMoved];
? ? ? ? result = [GTMBase64 stringByEncodingData:data];
? ? }
? ?
? ? return [result UTF8String];
? ?
}
+(NSString*)encryptWithContent:(NSString*)content type:(CCOperation)type key:(NSString*)aKey
{
? ? const char * contentChar =[content UTF8String];
? ? char * keyChar =(char*)[aKey UTF8String];
? ? const char *miChar;
? ? miChar = encryptWithKeyAndType(contentChar, type, keyChar);
? ? return? [NSString stringWithCString:miChar encoding:NSUTF8StringEncoding];
}
?
Android代码
?
? ? ? ? //加密
? ? ? ? public static String DecryptDoNet(String message, String key)
? ? ? ? ? ? ? ? throws Exception {
? ? ? ? ? ? byte[] bytesrc = Base64.decode(message.getBytes(), Base64.DEFAULT);
? ? ? ? ? ? Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
? ? ? ? ? ? DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
? ? ? ? ? ? SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
? ? ? ? ? ? SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
? ? ? ? ? ? IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
? ? ? ? ? ? cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
? ? ? ? ? ? byte[] retByte = cipher.doFinal(bytesrc);
? ? ? ? ? ? return new String(retByte);
? ? ? ? }
? ? ? ? // 解密
? ? ? ? public static String EncryptAsDoNet(String message, String key)
? ? ? ? ? ? ? ? throws Exception {
? ? ? ? ? ? Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
? ? ? ? ? ? DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
? ? ? ? ? ? SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
? ? ? ? ? ? SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
? ? ? ? ? ? IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
? ? ? ? ? ? cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
? ? ? ? ? ? byte[] encryptbyte = cipher.doFinal(message.getBytes());
? ? ? ? ? ? return new String(Base64.encode(encryptbyte, Base64.DEFAULT));
? ? ? ? }
? 最后还要注意一下,一般在客户端调用接口时,请求的是URL地址,参数需要加密,比如token,如果token里含有+号,URL会转码为空格,这时在.net端接收到token时,需要把token中的空格替换为+号:token = Regex.Replace(token, @"\s", "+");这样接收到的token才能正常的解密。