IOS、java支持DES加密

来源:互联网 发布:韩国在线直播软件 编辑:程序博客网 时间:2024/04/28 04:06

最近在考虑数据加密方面的需求,所以对数据加密简单的看了一下,当然不是看的原理,只是看看怎么能够实现。现在我们需要实现的是移动端和后台(java)数据加解密的配合,开始的时候考虑的使用RSA,因为RSA是非对称加密,更加安全点,但是RSA加密的过程中,ios公钥加密的数据,后台java是能够解密成功,但是后台java私钥加密的东西,前端ios,就没有解密成功,实验了很多方法,最终也没有成功,所以就放弃了,转向了安全性差一点的DES加密。

对于DES、RSA的介绍,自己百度去吧,因为我也说不明白。(上面我没有提Android,因为Android使用的是java,所以应该跟后台一致)

下面废话不多说,直接贴上代码:

IOS,需要引入GTMBase64.h、GTMBase64.m、GTMDefines.h,这个github上面有我,自己搜搜吧,还有<CommonCrypto/CommonCryptor.h>。

[objc] view plain copy
  1. #import "ViewController.h"  
  2. #import <CommonCrypto/CommonCryptor.h>  
  3. #import "GTMBase64.h"  
  4.   
  5. @interface ViewController ()  
  6.   
  7. @end  
  8.   
  9. @implementation ViewController  
  10.   
  11. - (void)viewDidLoad {  
  12.     [super viewDidLoad];  
  13.       
  14.     NSString *key = @"这是个key";  
  15.     NSString *encryptedData = [self encryptUseDES:@"this is a text" key:key];  
  16.     NSLog(@"加密后的数据是:%@", encryptedData);  
  17.     NSLog(@"解密后的数据是:%@", [self decryptUseDES:encryptedData key:key]);  
  18. }  
  19.   
  20. - (void)didReceiveMemoryWarning {  
  21.     [super didReceiveMemoryWarning];  
  22.     // Dispose of any resources that can be recreated.  
  23. }  
  24.   
  25. /*字符串加密 
  26.  *参数 
  27.  *plainText : 加密明文 
  28.  *key        : 密钥 64位 
  29.  */  
  30. - (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key  
  31. {  
  32.     NSString *ciphertext = nil;  
  33.     const charchar *textBytes = [plainText UTF8String];  
  34.     NSUInteger dataLength = [plainText length];  
  35.     unsigned char buffer[1024];  
  36.     memset(buffer, 0sizeof(char));  
  37.     Byte iv[] = {1,2,3,4,5,6,7,8};  
  38.     size_t numBytesEncrypted = 0;  
  39.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,  
  40.                                           kCCOptionPKCS7Padding,  
  41.                                           [key UTF8String], kCCKeySizeDES,  
  42.                                           iv,  
  43.                                           textBytes, dataLength,  
  44.                                           buffer, 1024,  
  45.                                           &numBytesEncrypted);  
  46.     if (cryptStatus == kCCSuccess) {  
  47.         NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted];  
  48.           
  49.         ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding];  
  50.     }  
  51.     return ciphertext;  
  52. }  
  53.   
  54. //解密  
  55. - (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key  
  56. {  
  57.     NSData* cipherData = [GTMBase64 decodeString:cipherText];  
  58.     unsigned char buffer[1024];  
  59.     memset(buffer, 0sizeof(char));  
  60.     size_t numBytesDecrypted = 0;  
  61.     Byte iv[] = {1,2,3,4,5,6,7,8};  
  62.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,  
  63.                                           kCCAlgorithmDES,  
  64.                                           kCCOptionPKCS7Padding,  
  65.                                           [key UTF8String],  
  66.                                           kCCKeySizeDES,  
  67.                                           iv,  
  68.                                           [cipherData bytes],  
  69.                                           [cipherData length],  
  70.                                           buffer,  
  71.                                           1024,  
  72.                                           &numBytesDecrypted);  
  73.     NSString* plainText = nil;  
  74.     if (cryptStatus == kCCSuccess) {  
  75.         NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];  
  76.         plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];  
  77.     }  
  78.     return plainText;  
  79. }  
  80.   
  81.   
  82. @end  
java 代码:需要自己引入sun.misc.BASE64Decoder.jar

[java] view plain copy
  1. package com.yue;  
  2.   
  3. import java.io.IOException;  
  4. import java.security.SecureRandom;  
  5.   
  6. import javax.crypto.Cipher;  
  7. import javax.crypto.SecretKey;  
  8. import javax.crypto.SecretKeyFactory;  
  9. import javax.crypto.spec.DESKeySpec;  
  10.   
  11. import Decoder.BASE64Decoder;  
  12. import Decoder.BASE64Encoder;  
  13.    
  14.    
  15. public class DesUtil {  
  16.    
  17.     private final static String DES = "DES";  
  18.    
  19.     public static void main(String[] args) throws Exception {  
  20.         String data = "123 456";  
  21.         String key = "abcdefgh";  
  22.         System.err.println(encrypt(data, key));  
  23.         System.err.println(decrypt(encrypt(data, key), key));  
  24.           
  25.         System.out.println(decrypt("JF5dX/TlOg529KAhh+vywjzIp5Msktmf", key));  
  26.    
  27.     }  
  28.        
  29.     /** 
  30.      * Description 根据键值进行加密 
  31.      * @param data  
  32.      * @param key  加密键byte数组 
  33.      * @return 
  34.      * @throws Exception 
  35.      */  
  36.     public static String encrypt(String data, String key) throws Exception {  
  37.         byte[] bt = encrypt(data.getBytes(), key.getBytes());  
  38.         String strs = new BASE64Encoder().encode(bt);  
  39.         return strs;  
  40.     }  
  41.    
  42.     /** 
  43.      * Description 根据键值进行解密 
  44.      * @param data 
  45.      * @param key  加密键byte数组 
  46.      * @return 
  47.      * @throws IOException 
  48.      * @throws Exception 
  49.      */  
  50.     public static String decrypt(String data, String key) throws IOException,  
  51.             Exception {  
  52.         if (data == null)  
  53.             return null;  
  54.         BASE64Decoder decoder = new BASE64Decoder();  
  55.         byte[] buf = decoder.decodeBuffer(data);  
  56.         byte[] bt = decrypt(buf,key.getBytes());  
  57.         return new String(bt);  
  58.     }  
  59.    
  60.     /** 
  61.      * Description 根据键值进行加密 
  62.      * @param data 
  63.      * @param key  加密键byte数组 
  64.      * @return 
  65.      * @throws Exception 
  66.      */  
  67.     private static byte[] encrypt(byte[] data, byte[] key) throws Exception {  
  68.         // 生成一个可信任的随机数源  
  69.         SecureRandom sr = new SecureRandom();  
  70.    
  71.         // 从原始密钥数据创建DESKeySpec对象  
  72.         DESKeySpec dks = new DESKeySpec(key);  
  73.    
  74.         // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象  
  75.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);  
  76.         SecretKey securekey = keyFactory.generateSecret(dks);  
  77.    
  78.         // Cipher对象实际完成加密操作  
  79.         Cipher cipher = Cipher.getInstance(DES);  
  80.    
  81.         // 用密钥初始化Cipher对象  
  82.         cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);  
  83.    
  84.         return cipher.doFinal(data);  
  85.     }  
  86.        
  87.        
  88.     /** 
  89.      * Description 根据键值进行解密 
  90.      * @param data 
  91.      * @param key  加密键byte数组 
  92.      * @return 
  93.      * @throws Exception 
  94.      */  
  95.     private static byte[] decrypt(byte[] data, byte[] key) throws Exception {  
  96.         // 生成一个可信任的随机数源  
  97.         SecureRandom sr = new SecureRandom();  
  98.    
  99.         // 从原始密钥数据创建DESKeySpec对象  
  100.         DESKeySpec dks = new DESKeySpec(key);  
  101.    
  102.         // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象  
  103.         SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);  
  104.         SecretKey securekey = keyFactory.generateSecret(dks);  
  105.    
  106.         // Cipher对象实际完成解密操作  
  107.         Cipher cipher = Cipher.getInstance(DES);  
  108.    
  109.         // 用密钥初始化Cipher对象  
  110.         cipher.init(Cipher.DECRYPT_MODE, securekey, sr);  
  111.    
  112.         return cipher.doFinal(data);  
  113.     }  
  114. }  

1 0
原创粉丝点击