主题:Android、iPhone和Java三个平台一致的加密工具

时间:2022-09-18 21:21:20

先前一直在做安卓,最近要开发iPhone客户端,这其中遇到的最让人纠结的要属Java、Android和iPhone三个平台加解密不一致的问题。因为手机端后台通常是用JAVA开发的Web Service,Android和iPhone客户端调用同样的Web Service接口,为了数据安全考虑,要对数据进行加密。头疼的问题就来了,很难编写出一套加密程序,在3个平台间加解密的结果一致,总不能为Android和iPhone两个客户端各写一套Web Service接口吧?我相信还会有很多朋友为此困惑,在此分享一套3DES加密程序,能够实现Java、Android和iPhone三个平台加解密一致

首先是JAVA端的加密工具类,它同样适用于Android端,无需任何修改,即可保证Java与Android端的加解密一致,并且中文不会乱码。

  1. package org.liuyq.des3;
  2. import java.security.Key;
  3. import javax.crypto.Cipher;
  4. import javax.crypto.SecretKeyFactory;
  5. import javax.crypto.spec.DESedeKeySpec;
  6. import javax.crypto.spec.IvParameterSpec;
  7. /**
  8. * 3DES加密工具类
  9. *
  10. * @author liufeng
  11. * @date 2012-10-11
  12. */
  13. public class Des3 {
  14. // 密钥
  15. private final static String secretKey = "liuyunqiang@lx100$#365#$";
  16. // 向量
  17. private final static String iv = "01234567";
  18. // 加解密统一使用的编码方式
  19. private final static String encoding = "utf-8";
  20. /**
  21. * 3DES加密
  22. *
  23. * @param plainText 普通文本
  24. * @return
  25. * @throws Exception
  26. */
  27. public static String encode(String plainText) throws Exception {
  28. Key deskey = null;
  29. DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
  30. SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
  31. deskey = keyfactory.generateSecret(spec);
  32. Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
  33. IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
  34. cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
  35. byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
  36. return Base64.encode(encryptData);
  37. }
  38. /**
  39. * 3DES解密
  40. *
  41. * @param encryptText 加密文本
  42. * @return
  43. * @throws Exception
  44. */
  45. public static String decode(String encryptText) throws Exception {
  46. Key deskey = null;
  47. DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());
  48. SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
  49. deskey = keyfactory.generateSecret(spec);
  50. Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
  51. IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
  52. cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
  53. byte[] decryptData = cipher.doFinal(Base64.decode(encryptText));
  54. return new String(decryptData, encoding);
  55. }
  56. }

上面的加密工具类会使用到Base64这个类,该类的源代码如下:

  1. package org.liuyq.des3;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. /**
  6. * Base64编码工具类
  7. *
  8. * @author liufeng
  9. * @date 2012-10-11
  10. */
  11. public class Base64 {
  12. private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
  13. public static String encode(byte[] data) {
  14. int start = 0;
  15. int len = data.length;
  16. StringBuffer buf = new StringBuffer(data.length * 3 / 2);
  17. int end = len - 3;
  18. int i = start;
  19. int n = 0;
  20. while (i <= end) {
  21. int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 0x0ff) << 8) | (((int) data[i + 2]) & 0x0ff);
  22. buf.append(legalChars[(d >> 18) & 63]);
  23. buf.append(legalChars[(d >> 12) & 63]);
  24. buf.append(legalChars[(d >> 6) & 63]);
  25. buf.append(legalChars[d & 63]);
  26. i += 3;
  27. if (n++ >= 14) {
  28. n = 0;
  29. buf.append(" ");
  30. }
  31. }
  32. if (i == start + len - 2) {
  33. int d = ((((int) data[i]) & 0x0ff) << 16) | ((((int) data[i + 1]) & 255) << 8);
  34. buf.append(legalChars[(d >> 18) & 63]);
  35. buf.append(legalChars[(d >> 12) & 63]);
  36. buf.append(legalChars[(d >> 6) & 63]);
  37. buf.append("=");
  38. } else if (i == start + len - 1) {
  39. int d = (((int) data[i]) & 0x0ff) << 16;
  40. buf.append(legalChars[(d >> 18) & 63]);
  41. buf.append(legalChars[(d >> 12) & 63]);
  42. buf.append("==");
  43. }
  44. return buf.toString();
  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. }
  65. /**
  66. * Decodes the given Base64 encoded String to a new byte array. The byte array holding the decoded data is returned.
  67. */
  68. public static byte[] decode(String s) {
  69. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  70. try {
  71. decode(s, bos);
  72. } catch (IOException e) {
  73. throw new RuntimeException();
  74. }
  75. byte[] decodedBytes = bos.toByteArray();
  76. try {
  77. bos.close();
  78. bos = null;
  79. } catch (IOException ex) {
  80. System.err.println("Error while decoding BASE64: " + ex.toString());
  81. }
  82. return decodedBytes;
  83. }
  84. private static void decode(String s, OutputStream os) throws IOException {
  85. int i = 0;
  86. int len = s.length();
  87. while (true) {
  88. while (i < len && s.charAt(i) <= ' ')
  89. i++;
  90. if (i == len)
  91. break;
  92. int tri = (decode(s.charAt(i)) << 18) + (decode(s.charAt(i + 1)) << 12) + (decode(s.charAt(i + 2)) << 6) + (decode(s.charAt(i + 3)));
  93. os.write((tri >> 16) & 255);
  94. if (s.charAt(i + 2) == '=')
  95. break;
  96. os.write((tri >> 8) & 255);
  97. if (s.charAt(i + 3) == '=')
  98. break;
  99. os.write(tri & 255);
  100. i += 4;
  101. }
  102. }
  103. }

接下来是iPhone端的加密程序,当然是用Ojbective-C写的3DES加密程序,源代码如下:

  1. //
  2. //  DES3Util.h
  3. //  lx100-gz
  4. //
  5. //  Created by  柳峰 on 12-10-10.
  6. //  Copyright 2012 http://blog.csdn.net/lyq8479. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. @interface DES3Util : NSObject {
  10. }
  11. // 加密方法
  12. + (NSString*)encrypt:(NSString*)plainText;
  13. // 解密方法
  14. + (NSString*)decrypt:(NSString*)encryptText;
  15. @end
  1. //
  2. //  DES3Util.m
  3. //  lx100-gz
  4. //
  5. //  Created by  柳峰 on 12-9-17.
  6. //  Copyright 2012 http://blog.csdn.net/lyq8479. All rights reserved.
  7. //
  8. #import "DES3Util.h"
  9. #import <CommonCrypto/CommonCryptor.h>
  10. #import "GTMBase64.h"
  11. #define gkey            @"liuyunqiang@lx100$#365#$"
  12. #define gIv             @"01234567"
  13. @implementation DES3Util
  14. // 加密方法
  15. + (NSString*)encrypt:(NSString*)plainText {
  16. NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
  17. size_t plainTextBufferSize = [data length];
  18. const void *vplainText = (const void *)[data bytes];
  19. CCCryptorStatus ccStatus;
  20. uint8_t *bufferPtr = NULL;
  21. size_t bufferPtrSize = 0;
  22. size_t movedBytes = 0;
  23. bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
  24. bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
  25. memset((void *)bufferPtr, 0x0, bufferPtrSize);
  26. const void *vkey = (const void *) [gkey UTF8String];
  27. const void *vinitVec = (const void *) [gIv UTF8String];
  28. ccStatus = CCCrypt(kCCEncrypt,
  29. kCCAlgorithm3DES,
  30. kCCOptionPKCS7Padding,
  31. vkey,
  32. kCCKeySize3DES,
  33. vinitVec,
  34. vplainText,
  35. plainTextBufferSize,
  36. (void *)bufferPtr,
  37. bufferPtrSize,
  38. &movedBytes);
  39. NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
  40. NSString *result = [GTMBase64 stringByEncodingData:myData];
  41. return result;
  42. }
  43. // 解密方法
  44. + (NSString*)decrypt:(NSString*)encryptText {
  45. NSData *encryptData = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];
  46. size_t plainTextBufferSize = [encryptData length];
  47. const void *vplainText = [encryptData bytes];
  48. CCCryptorStatus ccStatus;
  49. uint8_t *bufferPtr = NULL;
  50. size_t bufferPtrSize = 0;
  51. size_t movedBytes = 0;
  52. bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
  53. bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
  54. memset((void *)bufferPtr, 0x0, bufferPtrSize);
  55. const void *vkey = (const void *) [gkey UTF8String];
  56. const void *vinitVec = (const void *) [gIv UTF8String];
  57. ccStatus = CCCrypt(kCCDecrypt,
  58. kCCAlgorithm3DES,
  59. kCCOptionPKCS7Padding,
  60. vkey,
  61. kCCKeySize3DES,
  62. vinitVec,
  63. vplainText,
  64. plainTextBufferSize,
  65. (void *)bufferPtr,
  66. bufferPtrSize,
  67. &movedBytes);
  68. NSString *result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
  69. length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding] autorelease];
  70. return result;
  71. }
  72. @end

iPhone端的加密工具类中引入了“GTMBase64.h”,这是iOS平台的Base64编码工具类,就不在这里贴出相关代码了,需要的百度一下就能找到,实在找不到就回复留言给我。

好了,赶紧试一下吧,JAVA,Android和iPhone三个平台的加密不一致问题是不是解决了呢?其实,对此问题,还有一种更好的实现方式,那就是用C语言写一套加密程序,这样在iOS平台是可以直接使用C程序的,而在Java和Android端通过JNI去调用C语言编写的加密方法,这是不是就实现了3个平台调用同一套加密程序呢?