关于 Des加密(Android与ios 与后台java服务器之间的加密解密)

关于 Des加密(Android与ios  与后台java服务器之间的加密解密)

http://blog.sina.com.cn/s/blog_7c8dc2d50101id91.html

(2013-04-17 11:47:23)

  分类: iPhone开发

最近做了一个移动项目,是有服务器和客户端类型的项目,客户端是要登录才行的,登录的密码要用DES加密,服务器是用Java开发的,客户端要同时支持多平台(Android、iOS),在处理iOS的DES加密的时候遇到了一些问题,起初怎么调都调不成和Android端生成的密文相同。最终一个忽然的想法让我找到了问题的所在,现在将代码总结一下,以备自己以后查阅。

首先,Java端的DES加密的实现方式,代码如下:

 1 public class DES {
 2     private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
 3
 4     public static String encryptDES(String encryptString, String encryptKey)
 5             throws Exception {
 6         IvParameterSpec zeroIv = new IvParameterSpec(iv);
 7         SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
 8         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
 9         cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
10         byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
11         return Base64.encode(encryptedData);
12     }
13 }

上述代码用到了一个Base64的编码类,其代码的实现方式如下:

 1 public class Base64 {
 2     private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
 3             .toCharArray();
 4
 5
11     public static String encode(byte[] data) {
12         int start = 0;
13         int len = data.length;
14         StringBuffer buf = new StringBuffer(data.length * 3 / 2);
15
16         int end = len - 3;
17         int i = start;
18         int n = 0;
19
20         while (i <= end) {
21             int d = ((((int) data[i]) & 0x0ff) << 16)
22                     | ((((int) data[i + 1]) & 0x0ff) << 8)
23                     | (((int) data[i + 2]) & 0x0ff);
24
25             buf.append(legalChars[(d >> 18) & 63]);
26             buf.append(legalChars[(d >> 12) & 63]);
27             buf.append(legalChars[(d >> 6) & 63]);
28             buf.append(legalChars[d & 63]);
29
30             i += 3;
31
32             if (n++ >= 14) {
33                 n = 0;
34                 buf.append(" ");
35             }
36         }
37
38         if (i == start + len - 2) {
39             int d = ((((int) data[i]) & 0x0ff) << 16)
40                     | ((((int) data[i + 1]) & 255) << 8);
41
42             buf.append(legalChars[(d >> 18) & 63]);
43             buf.append(legalChars[(d >> 12) & 63]);
44             buf.append(legalChars[(d >> 6) & 63]);
45             buf.append("=");
46         } else if (i == start + len - 1) {
47             int d = (((int) data[i]) & 0x0ff) << 16;
48
49             buf.append(legalChars[(d >> 18) & 63]);
50             buf.append(legalChars[(d >> 12) & 63]);
51             buf.append("==");
52         }
53
54         return buf.toString();
55     }
56 }

以上便是Java端的DES加密方法的全部实现过程。

我还编写了一个将byte的二进制转换成16进制的方法,以便调试的时候使用打印输出加密后的byte数组的内容,这个方法不是加密的部分,只是为调试而使用的:

 1
 5     public static String parseByte2HexStr(byte buf[]) {
 6             StringBuffer sb = new StringBuffer();
 7             for (int i = 0; i < buf.length; i++) {
 8                     String hex = Integer.toHexString(buf[i] & 0xFF);
 9                     if (hex.length() == 1) {
10                             hex = ‘0‘ + hex;
11                     }
12                     sb.append(hex.toUpperCase());
13             }
14             return sb.toString();
15     }

下面是Objective-c在iOS上实现的DES加密算法:

 1 static Byte iv[] = {1,2,3,4,5,6,7,8};
 2 +(NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key
 3 {
 4     NSString *ciphertext = nil;
 5     const char *textBytes = [plainText UTF8String];
 6     NSUInteger dataLength = [plainText length];
 7     unsigned char buffer[1024];
 8     memset(buffer, 0, sizeof(char));
 9     size_t numBytesEncrypted = 0;
10     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
11                                           kCCOptionPKCS7Padding,
12                                           [key UTF8String], kCCKeySizeDES,
13                                           iv,
14                                           textBytes, dataLength,
15                                           buffer, 1024,
16                                           &numBytesEncrypted);
17     if (cryptStatus == kCCSuccess) {
18         NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];
19         ciphertext = [data base64Encoding];
20     }
21     return ciphertext;
22 }

下面是一个关键的类:NSData的Category实现,关于Category的实现网上很多说明不再讲述。

 1 static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 2 - (NSString *)base64Encoding;
 3 {
 4     if (self.length == 0)
 5         return @"";
 6
 7     char *characters = malloc(self.length*3/2);
 8
 9     if (characters == NULL)
10         return @"";
11
12     int end = self.length - 3;
13     int index = 0;
14     int charCount = 0;
15     int n = 0;
16
17     while (index <= end) {
18         int d = (((int)(((char *)[self bytes])[index]) & 0x0ff) << 16)
19         | (((int)(((char *)[self bytes])[index + 1]) & 0x0ff) << 8)
20         | ((int)(((char *)[self bytes])[index + 2]) & 0x0ff);
21
22         characters[charCount++] = encodingTable[(d >> 18) & 63];
23         characters[charCount++] = encodingTable[(d >> 12) & 63];
24         characters[charCount++] = encodingTable[(d >> 6) & 63];
25         characters[charCount++] = encodingTable[d & 63];
26
27         index += 3;
28
29         if(n++ >= 14)
30         {
31             n = 0;
32             characters[charCount++] = ‘ ‘;
33         }
34     }
35
36     if(index == self.length - 2)
37     {
38         int d = (((int)(((char *)[self bytes])[index]) & 0x0ff) << 16)
39         | (((int)(((char *)[self bytes])[index + 1]) & 255) << 8);
40         characters[charCount++] = encodingTable[(d >> 18) & 63];
41         characters[charCount++] = encodingTable[(d >> 12) & 63];
42         characters[charCount++] = encodingTable[(d >> 6) & 63];
43         characters[charCount++] = ‘=‘;
44     }
45     else if(index == self.length - 1)
46     {
47         int d = ((int)(((char *)[self bytes])[index]) & 0x0ff) << 16;
48         characters[charCount++] = encodingTable[(d >> 18) & 63];
49         characters[charCount++] = encodingTable[(d >> 12) & 63];
50         characters[charCount++] = ‘=‘;
51         characters[charCount++] = ‘=‘;
52     }
53     NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];
54     return rtnStr;
55 }

这个方法和java端的那个Base64的encode方法基本上是一个算法,只是根据语言的特点不同有少许的改动。

下面也是Objective-c的一个二进制转换为16进制的方法,也是为了测试方便查看写的:

 1 +(NSString *) parseByte2HexString:(Byte *) bytes
 2 {
 3     NSMutableString *hexStr = [[NSMutableString alloc]init];
 4     int i = 0;
 5     if(bytes)
 6     {
 7         while (bytes[i] != ‘\0‘)
 8         {
 9             NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数10             if([hexByte length]==1)
11                 [hexStr appendFormat:@"0%@", hexByte];
12             else
13                 [hexStr appendFormat:@"%@", hexByte];
14
15             i++;
16         }
17     }
18     NSLog(@"bytes 的16进制数为:%@",hexStr);
19     return hexStr;
20 }
21
22 +(NSString *) parseByteArray2HexString:(Byte[]) bytes
23 {
24     NSMutableString *hexStr = [[NSMutableString alloc]init];
25     int i = 0;
26     if(bytes)
27     {
28         while (bytes[i] != ‘\0‘)
29         {
30             NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数31             if([hexByte length]==1)
32                 [hexStr appendFormat:@"0%@", hexByte];
33             else
34                 [hexStr appendFormat:@"%@", hexByte];
35
36             i++;
37         }
38     }
39     NSLog(@"bytes 的16进制数为:%@",hexStr);
40     return hexStr;
41 }

以上的加密方法所在的包是CommonCrypto/CommonCryptor.h。

以上便实现了Objective-c和Java下在相同的明文和密钥的情况下生成相同明文的算法。

Base64的算法可以用你们自己写的那个,不一定必须使用我提供的这个。解密的时候还要用Base64进行密文的转换。

我的解密算法如下:

 1   private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
 2   public static String decryptDES(String decryptString, String decryptKey)
 3             throws Exception {
 4         byte[] byteMi = Base64.decode(decryptString);
 5         IvParameterSpec zeroIv = new IvParameterSpec(iv);
 6         SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
 7         Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
 8         cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
 9         byte decryptedData[] = cipher.doFinal(byteMi);
10
11         return new String(decryptedData);
12     }

Base64的decode方法如下:

 1   public static byte[] decode(String s) {
 2
 3         ByteArrayOutputStream bos = new ByteArrayOutputStream();
 4         try {
 5             decode(s, bos);
 6         } catch (IOException e) {
 7             throw new RuntimeException();
 8         }
 9         byte[] decodedBytes = bos.toByteArray();
10         try {
11             bos.close();
12             bos = null;
13         } catch (IOException ex) {
14             System.err.println("Error while decoding BASE64: " + ex.toString());
15         }
16         return decodedBytes;
17     }
18     private static void decode(String s, OutputStream os) throws IOException {
19         int i = 0;
20
21         int len = s.length();
22
23         while (true) {
24             while (i < len && s.charAt(i) <= ‘ ‘)
25                 i++;
26
27             if (i == len)
28                 break;
29
30             int tri = (decode(s.charAt(i)) << 18)
31                     + (decode(s.charAt(i + 1)) << 12)
32                     + (decode(s.charAt(i + 2)) << 6)
33                     + (decode(s.charAt(i + 3)));
34
35             os.write((tri >> 16) & 255);
36             if (s.charAt(i + 2) == ‘=‘)
37                 break;
38             os.write((tri >> 8) & 255);
39             if (s.charAt(i + 3) == ‘=‘)
40                 break;
41             os.write(tri & 255);
42
43             i += 4;
44         }
45     }
46     private static int decode(char c) {
47         if (c >= ‘A‘ && c <= ‘Z‘)
48             return ((int) c) - 65;
49         else if (c >= ‘a‘ && c <= ‘z‘)
50             return ((int) c) - 97 + 26;
51         else if (c >= ‘0‘ && c <= ‘9‘)
52             return ((int) c) - 48 + 26 + 26;
53         else
54             switch (c) {
55             case ‘+‘:
56                 return 62;
57             case ‘/‘:
58                 return 63;
59             case ‘=‘:
60                 return 0;
61             default:
62                 throw new RuntimeException("unexpected code: " + c);
63             }
64     }

以上便实现了DES加密后的密文的解密。

Java端的测试代码如下:

1     String plaintext = "abcd";
2     String ciphertext = DES.encryptDES(plaintext, "20120401");
3     System.out.println("明文:" + plaintext);
4     System.out.println("密钥:" + "20120401");
5     System.out.println("密文:" + ciphertext);
6     System.out.println("解密后:" + DES.decryptDES(ciphertext, "20120401"));

输出结果:

明文:abcd
密钥:20120401
密文:W7HR43/usys=
解密后:abcd

Objective-c端的测试代码如下:

1     NSString *plaintext = @"abcd";
2     NSString *ciphertext = [EncryptUtil encryptUseDES:plaintext key:@"20120401"];
3     NSLog(@"明文:%@",plaintext);
4     NSLog(@"秘钥:%@",@"20120401");
5     NSLog(@"密文:%@",ciphertext);

输出结果:

1 2012-04-05 12:00:47.348 TestEncrypt[806:f803] 明文:abcd
2 2012-04-05 12:00:47.350 TestEncrypt[806:f803] 秘钥:20120401
3 2012-04-05 12:00:47.350 TestEncrypt[806:f803] 密文:W7HR43/usys=

分享:

11

喜欢

1

赠金笔

阅读(7688)┊ 评论 (2)┊ 收藏(4) ┊禁止转载 ┊ 喜欢 ┊打印举报

前一篇:Mac配置Android开发环境变量及工具安装图

后一篇:ios高级面试

时间: 2024-08-02 02:49:50

关于 Des加密(Android与ios 与后台java服务器之间的加密解密)的相关文章

iOS 与 Java 服务器之间 SSL 握手失败的解决:Cipher Suites

太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公用协议 转载请保留此句:太阳火神的美丽人生 -  本博客专注于 敏捷开发及移动和物联设备研究:iOS.Android.Html5.Arduino.pcDuino,否则,出自本博客的文章拒绝转载或再转载,谢谢合作. 先挖个坑,有机会填,没机会填也属正常,毕竟地球表面也布满了坑,只不过我们叫盆地或高山而已. Cipher Suites :加密套件?也许这么翻译也

三重Des对称加密在Android、Ios 和Java 平台的实现

引言 如今手机app五彩缤纷,确保手机用户的数据安全是开发人员必须掌握的技巧,下面通过实例介绍DES在android.ios.java平台的使用方法: DES加密是目前最常用的对称加密方式,性能优于非对称加密(RSA),是手机app请求数据加密的优先选择.   DES简介: DES全称为Data Encryption Standard,即数据加密标准,是一种使用密钥加密的块算法, 算法的入口参数有三个:Key.Data.Mode. Key:为7个字节共56位,是DES算法的工作密钥; Data:

JAVA生成RSA非对称型加密的公钥和私钥(利用JAVA API)

非对称型加密非常适合多个客户端和服务器之间的秘密通讯,客户端使用同一个公钥将明文加密,而这个公钥不能逆向的解密,密文发送到服务器后有服务器端用私钥解密,这样就做到了明文的加密传送. 非对称型加密也有它先天的缺点,加密.解密速度慢制约了它的发挥,如果你有大量的文字需要加密传送,建议你通过非对称型加密来把对称型‘密钥’分发到客户端,及时更新对称型‘密钥’. package com.paul.module.common.util; import sun.misc.BASE64Decoder; impo

支持APP手机应用(android和ios)接口调用 ,传输验证可用 shiro 的 MD5、SHA 等加密

请认准本正版代码,售后技术有保障,代码有持续更新.(盗版可耻,违者必究)         此为本公司团队开发 ------------------------------------------------------------------------------------------------------------------------- 1. 有 oracle .msyql.spring3.0.spring4.0  一共 4 套版本全部提供没有打jar没有加密的源代码(最下面截图2

iOS开发之 AES+Base64数据混合加密与解密

2016-04-08 09:03 编辑: liubinqww 分类:iOS开发 来源:liubinqww 投稿 4 889 "APP的数据安全已经牵动着我们开发者的心,简单的MD5/Base64等已经难以满足当下的数据安全标准,本文简单的介绍下AES与Base64的混合加密与解密" AES:高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准.这个标准用来替代原先的DES

张高兴的 Xamarin.Forms 开发笔记:为 Android 与 iOS 引入 UWP 风格的汉堡菜单 ( MasterDetailPage )

所谓 UWP 样式的汉堡菜单,我曾在"张高兴的 UWP 开发笔记:汉堡菜单进阶"里说过,也就是使用 Segoe MDL2 Assets 字体作为左侧 Icon,并且左侧使用填充颜色的矩形用来表示 ListView 的选中.如下图 但怎样通过 Xamarin.Forms ,将这一样式的汉堡菜单带入到 Android 与 iOS 中呢? 一.大纲-细节模式简介 讲代码前首先来说说这种导航模式,官方称"大纲-细节模式"(MasterDetail).左侧的汉堡菜单称为&qu

结合活体检测,人脸识别在Android、IOS、服务器中的应用

随着深度学习方法的应用,人工智能的发展,人脸识别技术的识别率已经得到质的提升,通过反复开发试验,目前我司的人脸识别技术率已经达到99%.人脸识别技术与其他生物特征识别技术相吃比,在实际应用中具有天然独到的优势:通过摄像头直接获取,在非接触的方式完成识别过程.通过人脸识别与证件识别的比对,目前我司的人脸识别技术已应用在金融.教育.景区.旅运.社保等领域. 人脸识别技术简介 人脸识别技术主要分为两部分: 第一部为前端人脸活体检测技术,主要支持android.ios平台,在前端通过眨眼.张嘴.摇头.点

关于Android和iOS之间个人不(ch&#250;n)吐(cu&#236;)不(t&#249;)快(c&#225;o)的看法

这是一个我很久就想说的话题,这是一个我不吐不快的话题,先交待下本人是做Android开发的,虽然最近也有在整iOS的事情,不过毕竟不像Android那么熟悉,当然这主要是从开发的层面.其次,我要声明下这只是我的个人观点和看法,如果有失偏颇,还请各位提出建议或给予更正,对于我的个人观点,您可以不认同或者发表您的不同意见,我都乐意接纳,但请各位在看的同时注意文明用语,谢谢! 如果只说喜好,我更喜欢Andorid,iOS虽然说不上讨厌,但起码我是觉着用着难受! Android和iOS之间的争议从来就没

小结Android和iOS中LocalNotification

用Unity开发游戏,总难免要用到Native Development,比如Notification功能. 本文只对LocalNotification进行小结,iOS上RemoteNotification在此未讨论.(后面发现Unity已经把iOS部分给封装好了) Notification大致提供了两个功能:Register和Cancel,没找到Update的API,后来自己想了个Update的方法,就是先Cancel再Register. iOS: 1 //由于c#用long类型传递秒数,而lo