转载请注明博客地址:http://blog.csdn.net/mengxiangyue/article/details/40015727
近期在考虑数据加密方面的需求,所以对数据加密简单的看了一下,当然不是看的原理,仅仅是看看怎么可以实现。如今我们须要实现的是移动端和后台(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>。
#import "ViewController.h" #import <CommonCrypto/CommonCryptor.h> #import "GTMBase64.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSString *key = @"这是个key"; NSString *encryptedData = [self encryptUseDES:@"this is a text" key:key]; NSLog(@"加密后的数据是:%@", encryptedData); NSLog(@"解密后的数据是:%@", [self decryptUseDES:encryptedData key:key]); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /*字符串加密 *參数 *plainText : 加密明文 *key : 密钥 64位 */ - (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key { NSString *ciphertext = nil; const char *textBytes = [plainText UTF8String]; NSUInteger dataLength = [plainText length]; unsigned char buffer[1024]; memset(buffer, 0, sizeof(char)); Byte iv[] = {1,2,3,4,5,6,7,8}; size_t numBytesEncrypted = 0; CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, textBytes, dataLength, buffer, 1024, &numBytesEncrypted); if (cryptStatus == kCCSuccess) { NSData *data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesEncrypted]; ciphertext = [[NSString alloc] initWithData:[GTMBase64 encodeData:data] encoding:NSUTF8StringEncoding]; } return ciphertext; } //解密 - (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key { NSData* cipherData = [GTMBase64 decodeString:cipherText]; unsigned char buffer[1024]; memset(buffer, 0, sizeof(char)); size_t numBytesDecrypted = 0; Byte iv[] = {1,2,3,4,5,6,7,8}; CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, [cipherData bytes], [cipherData length], buffer, 1024, &numBytesDecrypted); NSString* plainText = nil; if (cryptStatus == kCCSuccess) { NSData* data = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted]; plainText = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; } return plainText; } @endjava 代码:须要自己引入sun.misc.BASE64Decoder.jar
package com.yue; import java.io.IOException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import Decoder.BASE64Decoder; import Decoder.BASE64Encoder; public class DesUtil { private final static String DES = "DES"; public static void main(String[] args) throws Exception { String data = "123 456"; String key = "abcdefgh"; System.err.println(encrypt(data, key)); System.err.println(decrypt(encrypt(data, key), key)); System.out.println(decrypt("JF5dX/TlOg529KAhh+vywjzIp5Msktmf", key)); } /** * Description 依据键值进行加密 * @param data * @param key 加密键byte数组 * @return * @throws Exception */ public static String encrypt(String data, String key) throws Exception { byte[] bt = encrypt(data.getBytes(), key.getBytes()); String strs = new BASE64Encoder().encode(bt); return strs; } /** * Description 依据键值进行解密 * @param data * @param key 加密键byte数组 * @return * @throws IOException * @throws Exception */ public static String decrypt(String data, String key) throws IOException, Exception { if (data == null) return null; BASE64Decoder decoder = new BASE64Decoder(); byte[] buf = decoder.decodeBuffer(data); byte[] bt = decrypt(buf,key.getBytes()); return new String(bt); } /** * Description 依据键值进行加密 * @param data * @param key 加密键byte数组 * @return * @throws Exception */ private static byte[] encrypt(byte[] data, byte[] key) throws Exception { // 生成一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密钥数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完毕加密操作 Cipher cipher = Cipher.getInstance(DES); // 用密钥初始化Cipher对象 cipher.init(Cipher.ENCRYPT_MODE, securekey, sr); return cipher.doFinal(data); } /** * Description 依据键值进行解密 * @param data * @param key 加密键byte数组 * @return * @throws Exception */ private static byte[] decrypt(byte[] data, byte[] key) throws Exception { // 生成一个可信任的随机数源 SecureRandom sr = new SecureRandom(); // 从原始密钥数据创建DESKeySpec对象 DESKeySpec dks = new DESKeySpec(key); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES); SecretKey securekey = keyFactory.generateSecret(dks); // Cipher对象实际完毕解密操作 Cipher cipher = Cipher.getInstance(DES); // 用密钥初始化Cipher对象 cipher.init(Cipher.DECRYPT_MODE, securekey, sr); return cipher.doFinal(data); } }
代码下载地址:http://download.csdn.net/detail/mengxiangyue/8028311