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

本文介绍了如何在Java和iOS平台上实现DES加密解密的同步,包括Java端和iOS端的代码实现,以及加密解密过程中的关键步骤。通过这些方法,可以确保Android和iOS客户端与Java服务器之间的数据安全传输。
摘要由CSDN通过智能技术生成

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

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

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

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

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

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

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

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

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

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

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

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

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

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

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

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

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

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

我的解密算法如下:

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

Base64的decode方法如下:

a4c26d1e5885305701be709a3d33442f.png

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 }

a4c26d1e5885305701be709a3d33442f.png

以上便实现了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=

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值