码迷,mamicode.com
首页 > 移动开发 > 详细

DES非对称加密解密跨平台(C#,安卓,ios)

时间:2017-09-13 11:56:39      阅读:422      评论:0      收藏:0      [点我收藏+]

标签:--   sizeof   char*   tao   nslog   oar   throws   res   amp   

 

#region   跨平台加解密(c# 安卓 IOS)
        public static string sKey = "123456";
        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="pToDecrypt">要解密的以Base64</param>
        /// <param name="sKey">密钥,且必须为8位</param>
        /// <returns>已解密的字符串</returns>
        public static string DesDecrypt(string pToDecrypt)
        {
            //转义特殊字符
            pToDecrypt = pToDecrypt.Replace("-", "+");
            pToDecrypt = pToDecrypt.Replace("_", "/");
            pToDecrypt = pToDecrypt.Replace("~", "=");
            byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
            using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
            {
                des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
                des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(inputByteArray, 0, inputByteArray.Length);
                    cs.FlushFinalBlock();
                    cs.Close();
                }
                string str = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                return str;
            }
        }

        /// <summary>
        /// 对字符串进行DES加密
        /// </summary>
        /// <param name="sourceString">待加密的字符串</param>
        /// <returns>加密后的BASE64编码的字符串</returns>
        public static string Encrypt(string sourceString)
        {
            byte[] btKey = Encoding.UTF8.GetBytes(sKey);
            byte[] btIV = Encoding.UTF8.GetBytes(sKey);
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] inData = Encoding.UTF8.GetBytes(sourceString);
                try
                {
                    using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV), CryptoStreamMode.Write))
                    {
                        cs.Write(inData, 0, inData.Length);
                        cs.FlushFinalBlock();
                    }

                    return Convert.ToBase64String(ms.ToArray());
                }
                catch
                {
                    throw;
                }
            }
        }

        #endregion




        // 安卓---------------------------------------------------------------------------
        //    // 解密
        //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));
        //}

        /*

       //Ios --------------------------------------------------------------------------------------------------------------------       //加密
       +(NSString*)decryptWithContent:(NSString*)content
       {

           char* keyChar = (char*)[@"加密key" UTF8String];
               NSString* jm = [NSString stringWithCString: encryptWithKeyAndType([content UTF8String], kCCEncrypt, keyChar) encoding:NSUTF8StringEncoding];
               
           return [NSString stringWithFormat:@"%@", jm];

       }
       //解密
       +(NSData*)encryptWithContent:(NSData*)content
       {
           NSString* contentStr = [[NSString alloc] initWithData:content encoding:NSUTF8StringEncoding];

           if (contentStr == nil || [contentStr isEqualToString:@""]) {
               return nil;
           }

       contentStr= [contentStr substringWithRange:NSMakeRange(4, contentStr.length - 8)];

           const char* contentChar =[contentStr UTF8String];
       char* keyChar = (char*)[@"加密key" UTF8String];
       const char* miChar;
       miChar = encryptWithKeyAndType(contentChar, kCCDecrypt, keyChar);
           if (miChar == nil) {
               miChar = "";
           }

           NSString* zmStr = [NSString stringWithCString: miChar encoding: NSUTF8StringEncoding];
           if (zmStr == nil) {
               zmStr =@"";
           }
           return [zmStr dataUsingEncoding:NSUTF8StringEncoding];
       }


       static const char* encryptWithKeyAndType(const char * text, CCOperation encryptOperation, char * key)
       {
           NSString* textString =[[NSString alloc]initWithCString:text encoding:NSUTF8StringEncoding];
           //      NSLog(@"[[item.url description] UTF8String=%@",textString);
           const void* dataIn;
       size_t dataInLength;

           if (encryptOperation == kCCDecrypt)//传递过来的是decrypt 解码
           {
               //解码 base64
               NSData* decryptData = [GTMBase64 decodeData:[textString dataUsingEncoding: NSUTF8StringEncoding]];//转成utf-8并decode
       dataInLength = [decryptData length];
               dataIn = [decryptData bytes];
           }
           else  //encrypt
           {
               NSData* encryptData = [textString dataUsingEncoding: NSUTF8StringEncoding];
       dataInLength = [encryptData length];
               dataIn = (const void*)[encryptData bytes];
           }


           CCCryptorStatus ccStatus;
       uint8_t* dataOut = NULL; //可以理解位type/typedef 的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义)
       size_t dataOutAvailable = 0; //size_t  是操作符sizeof返回的结果类型
       size_t dataOutMoved = 0;

       dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
           dataOut = malloc(dataOutAvailable* sizeof(uint8_t));
           memset((void*)dataOut, 00, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0

           //NSString *initIv = @"12345678";
           const void* vkey = key;
       const void* iv = (const void*) key; //[initIv UTF8String];

           //CCCrypt函数 加密/解密
           ccStatus = CCCrypt(encryptOperation,//  加密/解密
                              kCCAlgorithmDES,//  加密根据哪个标准(des,3des,aes。。。。)
                              kCCOptionPKCS7Padding,//  选项分组密码算法(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];

       }
       


       //Ios --------------------------------------------------------------------------------------------------------------------       static const char* encryptWithKeyAndType(const char * text, CCOperation encryptOperation, char * key)
       {
           NSString* textString =[[NSString alloc]initWithCString:text encoding:NSUTF8StringEncoding];
           //      NSLog(@"[[item.url description] UTF8String=%@",textString);
           const void* dataIn;
       size_t dataInLength;

           if (encryptOperation == kCCDecrypt)//传递过来的是decrypt 解码
           {
               //解码 base64
               NSData* decryptData = [GTMBase64 decodeData:[textString dataUsingEncoding: NSUTF8StringEncoding]];//转成utf-8并decode
       dataInLength = [decryptData length];
               dataIn = [decryptData bytes];
           }
           else  //encrypt
           {
               NSData* encryptData = [textString dataUsingEncoding: NSUTF8StringEncoding];
       dataInLength = [encryptData length];
               dataIn = (const void*)[encryptData bytes];
           }


           CCCryptorStatus ccStatus;
       uint8_t* dataOut = NULL; //可以理解位type/typedef 的缩写(有效的维护了代码,比如:一个人用int,一个人用long。最好用typedef来定义)
       size_t dataOutAvailable = 0; //size_t  是操作符sizeof返回的结果类型
       size_t dataOutMoved = 0;

       dataOutAvailable = (dataInLength + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);
           dataOut = malloc(dataOutAvailable* sizeof(uint8_t));
           memset((void*)dataOut, 00, dataOutAvailable);//将已开辟内存空间buffer的首 1 个字节的值设为值 0

           //NSString *initIv = @"12345678";
           const void* vkey = key;
       const void* iv = (const void*) key; //[initIv UTF8String];

           //CCCrypt函数 加密/解密
           ccStatus = CCCrypt(encryptOperation,//  加密/解密
                              kCCAlgorithmDES,//  加密根据哪个标准(des,3des,aes。。。。)
                              kCCOptionPKCS7Padding,//  选项分组密码算法(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];
       }
       */

 

亲测可用:附带一份ios源码

https://files.cnblogs.com/files/xiang-wei/ios_des%E5%8A%A0%E5%AF%86.zip

DES非对称加密解密跨平台(C#,安卓,ios)

标签:--   sizeof   char*   tao   nslog   oar   throws   res   amp   

原文地址:http://www.cnblogs.com/xiang-wei/p/7513983.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!