2017-01-20 15:22:02 qq_30254057 阅读数 243
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25330 人正在学习 去看看 邵发

/*

 

 加密

 

 */

+ (NSString *)encrypt3DES:(NSString *)src key:(NSString *)key{

    const void *vplainText;

    size_t plainTextBufferSize;

    NSData* data = [src dataUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];

    plainTextBufferSize = [data length];

    vplainText = (const void *)[data bytes];

    CCCryptorStatus ccStatus;

    uint8_t *bufferPtr = NULL;

    size_t bufferPtrSize = 0;

    size_t movedBytes = 0;

    

    bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);

    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));

    memset((void *)bufferPtr, 0x0, bufferPtrSize);

    const void *vkey = (const void *)[key UTF8String];

    

    ccStatus = CCCrypt(kCCEncrypt,

                       kCCAlgorithmDES,

                       kCCOptionPKCS7Padding | kCCOptionECBMode,

                       vkey,

                       kCCKeySizeDES,

                       nil,

                       vplainText,

                       plainTextBufferSize,

                       (void *)bufferPtr,

                       bufferPtrSize,

                       &movedBytes);

    

    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];

    return [self NSDataToHexString:myData];

}



/*

 

 解密

 

*/

+ (NSString *)decrypt3DES:(NSString *)src key:(NSString *)key{

    const void *vplainText;

    size_t plainTextBufferSize;

    NSData *EncryptData = [self hexStrToNSData:src];

    plainTextBufferSize = [EncryptData length];

    vplainText = [EncryptData bytes];

    CCCryptorStatus ccStatus;

    uint8_t *bufferPtr = NULL;

    size_t bufferPtrSize = 0;

    size_t movedBytes = 0;

    

    bufferPtrSize = (plainTextBufferSize + kCCBlockSizeDES) & ~(kCCBlockSizeDES - 1);

    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));

    memset((void *)bufferPtr, 0x0, bufferPtrSize);

    const void *vkey = (const void *)[key UTF8String];

    ccStatus = CCCrypt(kCCDecrypt,

                       kCCAlgorithmDES,

                       kCCOptionPKCS7Padding | kCCOptionECBMode,

                       vkey,

                       kCCKeySizeDES,

                       nil,

                       vplainText,

                       plainTextBufferSize,

                       (void *)bufferPtr,

                       bufferPtrSize,

                       &movedBytes);

    

    NSData *dataBuf = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];

    return [[NSString alloc] initWithData:dataBuf

                                 encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)]

    ;

}



//十六进制字符串转化为二进制

- (NSData *)hexStrToNSData:(NSString *)hexStr{

    NSMutableData* data = [NSMutableData data];

    for (int i = 0; i+2 <= hexStr.length; i+=2) {

        NSRange range = NSMakeRange(i, 2);

        NSString* ch = [hexStr substringWithRange:range];

        NSScanner* scanner = [NSScanner scannerWithString:ch];

        unsigned int intValue;

        [scanner scanHexInt:&intValue];

        [data appendBytes:&intValue length:1];

    }

    

    return data;

}



//二进制转化为十六进制

- (NSString *)NSDataToHexString:(NSData *)data{

    if (data == nil) {

        return nil;

    }

    

    NSMutableString* hexString = [NSMutableString string];

    const unsigned char *p = [data bytes];

    for (int i=0; i < [data length]; i++) {

        [hexString appendFormat:@"%02x", *p++];

    }

    

    return [hexString uppercaseString];

}


2017-07-28 16:28:38 liuq0725 阅读数 412
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25330 人正在学习 去看看 邵发

android端的加密代码:

public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

private static String encode(String key, byte[] data) throws Exception {
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data);
        return Base64.encodeToString(bytes, 0);
    } catch (Exception e) {
        throw new Exception(e);
    }
}

首先要关注的是 ALGORITHM_DES = “DES/CBC/PKCS5Padding”这个变量,从中我们可以看出这是DES的CBC加密模式,用的是PKCS5Padding的填充模式。

之后代码使用ALGORITHM_DES来变量初始化Cipher

Cipher cipher = Cipher.getInstance(ALGORITHM_DES);

OC段加密代码

CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                      kCCOptionPKCS7Padding,
                                      [key UTF8String], kCCKeySizeDES,
                                      iv,
                                      textBytes, dataLength,
                                      buffer, 1024,
                                      &numBytesEncrypted);

参数说明:

kCCEncrypt:告诉函数执行加密过程,对应的也存在解密过程;
kCCAlgorithmDES:告诉函数执行DES加密;
kCCOptionPKCS7Padding:运用CBC加密模式,并且使用PKCS7Padding的填充模式;
[key UTF8String]:秘钥;
kCCKeySizeDES:秘钥的大小,(kCCKeySizeDES=8) ;
iv:可选的初始矢量 ;
textBytes:要加密的源数据;
dataLength: 数据的大小 ;
buffer:加密后的返回数据;
numBytesEncrypted:返回的数据大小;

JAVA和OC的差异说明:

对于iOS来说,只有PKCS7Padding这一种填充方式,而JAVA有多种。iOS的DES中加密数据包单位长度是8字节,8字节的情况下PKCS7Padding等价与JAVA的PKCS5Padding填充方式。

具体OC代码如下:

//DES加密
+ (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));
    const void *iv = (const void *)[key UTF8String];
    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 = [data base64EncodedStringWithOptions:0];
    }
    return ciphertext;
}

//DES解密
- (NSString *) decryptUseDES:(NSString*)cipherText key:(NSString*)key
{
    NSData *cipherData = [[NSData alloc] initWithBase64EncodedString:self options:0];
    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;
}

头文件:

#import <CommonCrypto/CommonCryptor.h>

结尾:

两边需要同步的地方:

1、算法:都是DES;
2、模式:
CBC = kCCOptionPKCS7Padding
EBC = kCCOptionPKCS7Padding|kCCOptionECBMode
3、秘钥:例如:tianwanggaidihu
4、IV变量:
JAVA:
IvParameterSpec iv = new IvParameterSpec(“12347890”.getBytes());
OC:
Byte iv[] = {1,2,3,4,7,8,9,0};
5、编码模式:base64。

参考链接:

DES:
http://blog.csdn.net/u010184533/article/details/38975871
http://blog.csdn.net/dqmj2/article/details/47983351

3DES:
http://blog.csdn.net/lyq8479/article/details/8062867#

2017-08-23 18:08:19 tanhoqi451 阅读数 1596
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25330 人正在学习 去看看 邵发


首先是JAVA端的加密工具类,它同样适用于Android端,无需任何修改,即可保证Java与Android端的加解密一致,并且中文不会乱码。我经过和IOS共同测试,是没有问题的大笑

iOS端  代码       iOS端的加密工具类中引入了“GTMBase64.h”,下面 我写的demo里面 有该类。。

#import 

@interface DES3Util : NSObject {

}

// 加密方法

+ (NSString*)encrypt:(NSString*)plainText;

// 解密方法

+ (NSString*)decrypt:(NSString*)encryptText;

@end
#import"DES3Util.h"

#import

#import"GTMBase64.h"

#define gkey@"Mozhe@lx100$#365#$"

#define gIv@"01234567"

@implementationDES3Util

//加密方法

+ (NSString*)encrypt:(NSString*)plainText {

NSData* data = [plainTextdataUsingEncoding:NSUTF8StringEncoding];

size_tplainTextBufferSize = [datalength];

constvoid*vplainText = (constvoid*)[databytes];

CCCryptorStatusccStatus;

uint8_t*bufferPtr =NULL;

size_tbufferPtrSize =0;

size_tmovedBytes =0;

bufferPtrSize = (plainTextBufferSize +kCCBlockSize3DES) & ~(kCCBlockSize3DES-1);

bufferPtr =malloc( bufferPtrSize *sizeof(uint8_t));

memset((void*)bufferPtr,0x0, bufferPtrSize);

constvoid*vkey = (constvoid*) [gkeyUTF8String];

constvoid*vinitVec = (constvoid*) [gIvUTF8String];

ccStatus =CCCrypt(kCCEncrypt,

kCCAlgorithm3DES,

kCCOptionPKCS7Padding,

vkey,

kCCKeySize3DES,

vinitVec,

vplainText,

plainTextBufferSize,

(void*)bufferPtr,

bufferPtrSize,

&movedBytes);

NSData*myData = [NSDatadataWithBytes:(constvoid*)bufferPtrlength:(NSUInteger)movedBytes];

NSString*result = [GTMBase64stringByEncodingData:myData];

returnresult;

}

//解密方法

+ (NSString*)decrypt:(NSString*)encryptText {

NSData*encryptData = [GTMBase64decodeData:[encryptTextdataUsingEncoding:NSUTF8StringEncoding]];

size_tplainTextBufferSize = [encryptDatalength];

constvoid*vplainText = [encryptDatabytes];

CCCryptorStatusccStatus;

uint8_t*bufferPtr =NULL;

size_tbufferPtrSize =0;

size_tmovedBytes =0;

bufferPtrSize = (plainTextBufferSize +kCCBlockSize3DES) & ~(kCCBlockSize3DES-1);

bufferPtr =malloc( bufferPtrSize *sizeof(uint8_t));

memset((void*)bufferPtr,0x0, bufferPtrSize);

constvoid*vkey = (constvoid*) [gkeyUTF8String];

constvoid*vinitVec = (constvoid*) [gIvUTF8String];

ccStatus =CCCrypt(kCCDecrypt,

kCCAlgorithm3DES,

kCCOptionPKCS7Padding,

vkey,

kCCKeySize3DES,

vinitVec,

vplainText,

plainTextBufferSize,

(void*)bufferPtr,

bufferPtrSize,

&movedBytes);

NSString*result = [[NSStringalloc]initWithData:[NSDatadataWithBytes:(constvoid*)bufferPtr

length:(NSUInteger)movedBytes]encoding:NSUTF8StringEncoding];

returnresult;

}

@end



Java端

package encrypt;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class Des3 {
	// 密钥

	private final static String secretKey = "liuyunqiang@lx100$#365#$";


	// 向量

	private final static String iv = "01234567";

	// 加解密统一使用的编码方式

	private final static String encoding = "utf-8";

	/**
	 * 
	 * 3DES加密
	 * 
	 *
	 * 
	 * @param plainText
	 *            普通文本
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */

	public static String encode(String plainText) throws Exception {

		Key deskey = null;

		DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());

		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");

		deskey = keyfactory.generateSecret(spec);

		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");

		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());

		cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);

		byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));

		return Base64.encode(encryptData);

	}

	/**
	 * 
	 * 3DES解密
	 * 
	 *
	 * 
	 * @param encryptText
	 *            加密文本
	 * 
	 * @return
	 * 
	 * @throws Exception
	 */

	public static String decode(String encryptText) throws Exception {

		Key deskey = null;

		DESedeKeySpec spec = new DESedeKeySpec(secretKey.getBytes());

		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");

		deskey = keyfactory.generateSecret(spec);

		Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");

		IvParameterSpec ips = new IvParameterSpec(iv.getBytes());

		cipher.init(Cipher.DECRYPT_MODE, deskey, ips);

		byte[] decryptData = cipher.doFinal(Base642.decode(encryptText));

		return new String(decryptData, encoding);

	}
	public static void main(String[] args) throws Exception {
	
		String tt="测试";
		
		System.out.println(encode(tt));
		System.out.println(decode(encode(tt)));
	}

}

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

package encrypt;

public class Base64 {

	private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

	.toCharArray();

	public static String encode(byte[] data) {

		int start = 0;

		int len = data.length;

		StringBuffer buf = new StringBuffer(data.length * 3 / 2);

		int end = len - 3;

		int i = start;

		int n = 0;

		while (i <= end) {

			int d = ((((int) data[i]) & 0x0ff) << 16)

			| ((((int) data[i + 1]) & 0x0ff) << 8)

			| (((int) data[i + 2]) & 0x0ff);

			buf.append(legalChars[(d >> 18) & 63]);

			buf.append(legalChars[(d >> 12) & 63]);

			buf.append(legalChars[(d >> 6) & 63]);

			buf.append(legalChars[d & 63]);

			i += 3;

			if (n++ >= 14) {

				n = 0;

				buf.append(" ");

			}

		}

		if (i == start + len - 2) {

			int d = ((((int) data[i]) & 0x0ff) << 16)

			| ((((int) data[i + 1]) & 255) << 8);

			buf.append(legalChars[(d >> 18) & 63]);

			buf.append(legalChars[(d >> 12) & 63]);

			buf.append(legalChars[(d >> 6) & 63]);

			buf.append("=");

		} else if (i == start + len - 1) {

			int d = (((int) data[i]) & 0x0ff) << 16;

			buf.append(legalChars[(d >> 18) & 63]);

			buf.append(legalChars[(d >> 12) & 63]);

			buf.append("==");

		}

		return buf.toString();

	}

}

#import

@interfaceDES3Util :NSObject

//加密方法

+ (NSString*)encrypt:(NSString*)plainText;

//解密方法

+ (NSString*)decrypt:(NSString*)encryptText;

@end#import

@interfaceDES3Util :NSObject

//加密方法

+ (NSString*)encrypt:(NSString*)plainText;

//解密方法

+ (NSString*)decrypt:(NSString*)encryptText;

@end
作者:默着
链接:http://www.jianshu.com/p/630e5899582d
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2019-03-19 14:20:12 lpCrazyBoy 阅读数 435
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25330 人正在学习 去看看 邵发

IOS常用加密技术有三种:3DES、SHA1和MD5。其中,对称加密技术有:3DES和SHA1;非对称加密技术有:MD5;

对称加密:加密解密用的是同一个密钥。

非对称加密:生成公有密钥和私有密钥。一个加密,一个解密。

 

本篇介绍的是3DES加密解密技术:

1、创建HeaderFile文件My3DES.h。然后,添加以下代码,引用相关的头文件:

#import <CommonCrypto/CommonCrypto.h>

2、在BuildSetting面板中设置Objective-C Bridging Header的Value值为第1步创建的桥接文件所在的位置。比如:项目名/文件名.h。

3、配置好了之后,下面就开始使用了。

import UIKit

class ViewController: UIViewController {

    private let randomStringArray:[Character] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".map({$0});
    
    var key:String!;
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        let data:Data = encrypt(encryptData: "http://www.baidu.com");
        decrypt(inputData: data);
    }

    func randomStringOfLength(_ length:Int) -> String {
        var string = "";
        for _ in(1...length) {
            string.append(randomStringArray[Int(arc4random_uniform(UInt32(randomStringArray.count) - 1))]);
        }
        return string;
    }
    
    //加密
    func encrypt(encryptData:String) -> Data {
        key = randomStringOfLength(kCCKeySize3DES);
        let inputData:Data = encryptData.data(using: String.Encoding.utf8)!;
        
        let keyData:Data = key.data(using: String.Encoding.utf8, allowLossyConversion: false)!;
        let keyBytes = UnsafeMutableRawPointer(mutating: (keyData as NSData).bytes);
        let keyLength = size_t(kCCKeySize3DES);
        
        let dataLength = Int(inputData.count);
        let dataBytes = UnsafeRawPointer((inputData as NSData).bytes);
        let bufferData = NSMutableData(length: Int(dataLength) + kCCKeySize3DES)!;
        let bufferPointer = UnsafeMutableRawPointer(bufferData.mutableBytes);
        let bufferLength = size_t(bufferData.length);
        var bytesDecrypted = Int(0);
        
        let cryptStatus = CCCrypt(
            UInt32(kCCEncrypt),
            UInt32(kCCAlgorithm3DES),
            UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding),
            keyBytes,
            keyLength,
            nil,
            dataBytes,
            dataLength,
            bufferPointer,
            bufferLength,
            &bytesDecrypted
            );
        
        if Int32(cryptStatus) == Int32(kCCSuccess) {
            bufferData.length = bytesDecrypted;
            print("encrypt success");
            
        } else {
            print("加密过程出错\(cryptStatus)");
        }
        return bufferData as Data;
    }
    
    //解密
    func decrypt(inputData:Data) {
        let keyData:Data = key.data(using: String.Encoding.utf8, allowLossyConversion: false)!;
        let keyBytes = UnsafeMutableRawPointer(mutating: (keyData as NSData).bytes);
        let keyLength = size_t(kCCKeySize3DES);
        
        let dataLength = Int(inputData.count);
        let dataBytes = UnsafeRawPointer((inputData as NSData).bytes);
        let bufferData = NSMutableData(length: Int(dataLength) + kCCKeySize3DES)!;
        let bufferPointer = UnsafeMutableRawPointer(bufferData.mutableBytes);
        let bufferLength = size_t(bufferData.length);
        var bytesDecrypted = Int(0);
        
        let cryptStatus = CCCrypt(
            UInt32(kCCDecrypt),
            UInt32(kCCAlgorithm3DES),
            UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding),
            keyBytes,
            keyLength,
            nil,
            dataBytes,
            dataLength,
            bufferPointer,
            bufferLength,
            &bytesDecrypted
        );
        
        if Int32(cryptStatus) == Int32(kCCSuccess) {
            bufferData.length = bytesDecrypted;
            let clearDataAsString = NSString(data: bufferData as Data, encoding: String.Encoding.utf8.rawValue);
            print("解密后的内容:\(clearDataAsString! as String)");
        } else {
            print("解密过程出错\(cryptStatus)");
        }
    }

}

输出结果为:

encrypt success
解密后的内容:http://www.baidu.com

2016-09-08 15:51:00 YZP664521 阅读数 0
  • 《C语言/C++学习指南》加密解密篇(安全相关算法)

    本套视频教程介绍加密解密相关的常见算法,指出每种算法的应用场景,并给出使用示例。具体包含: (1) 数据转换(HEX和base64) (2) 对称加密 (DES, 3DES, AES) (3) 校验 CRC, MD5摘要, SHA1摘要 (4) 数字签名(HMAC-SHA1) , 并介绍了crypto++这个算法库的使用方法。

    25330 人正在学习 去看看 邵发

  转载请注明原文出处

     生成同名的Des.h文件和Des.m文件后,拷贝下方的代码可直接使用。注意在Des.m文件中将key值修改为项目所需的key。---》  #define DesKey

  过程很简单,将字符串加密转成16进制字符串,以及将16进制字符串转成字符串。

  以下是.h文件内容:

  

//
//  Des.h
//  desIOS
//
//  Created by wusiping on 16/6/13.
//  Copyright © 2016年 wusiping. All rights reserved.
//

#import <Foundation/Foundation.h>

/******字符串转base64(包括DES加密)******/
#define __DesEncodeString( string )        [Des hexStringFromText:string]

/******base64(通过DES解密)转字符串******/
#define __DesDecodeString( HexString )        [Des textFromHexString:HexString]

@interface Des : NSObject

/**
 *  字符串加密转成16进制字符串
 */
+ (NSString *)hexStringFromText:(NSString *)string;

/**
 *  16进制解密生成字符串
 */
+ (NSString *)textFromHexString:(NSString *)HexString;


+ (NSString *)base64EncodedStringFromData:(NSData *)data;
+ (NSString *)textFrombase64String:(NSString *)base64;

@end

 以下是.m文件内容:

//
//  Des.m
//  desIOS
//
//  Created by wusiping on 16/6/13.
//  Copyright © 2016年 wusiping. All rights reserved.
//

#import "Des.h"

//引入IOS自带密码库
#import <CommonCrypto/CommonCryptor.h>

//空字符串
#define     LocalStr_None           @""

#define DesKey @"com.nokia.parts"

static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/";

@implementation Des

/**
 *  字符串des加密转成16进制
 */
+ (NSString *)hexStringFromText:(NSString *)string
{
//    string = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if (string && ![string isEqualToString:LocalStr_None]) {
        //取项目的bundleIdentifier作为KEY
        NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
        //IOS 自带DES加密 Begin
        data = [self DESEncrypt:data WithKey:DesKey];
        //IOS 自带DES加密 End
        return [self hexStringEncodedStringFromData:data];
    }
    else {
        return LocalStr_None;
    }
}


/**
 *  把data 进行des加密成16进制
 */
+ (NSString *)hexStringEncodedStringFromData:(NSData *)data
{
    
    Byte *bytes = (Byte *)[data bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    
    for(int i=0;i<[data length];i++)
        
    {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        
        else
            
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
    
}


/**
 *  des解密16进制 转成字符串
 */
+ (NSString *)textFromHexString:(NSString *)HexString
{
    

    NSInteger len = [HexString length] / 2;    // Target length
    unsigned char *buf = malloc(len);
    unsigned char *whole_byte = buf;
    char byte_chars[3] = {'\0','\0','\0'};
    
    int i;
    for (i=0; i < [HexString length] / 2; i++) {
        byte_chars[0] = [HexString characterAtIndex:i*2];
        byte_chars[1] = [HexString characterAtIndex:i*2+1];
        *whole_byte = strtol(byte_chars, NULL, 16);
        whole_byte++;
    }
    
    NSData *result = [NSData dataWithBytes:buf length:len];
    free(buf);
    
    result = [self DESDecrypt:result WithKey:DesKey];
    return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];

}


//base64解密转string
+ (NSString *)textFrombase64String:(NSString *)base64
{
        if (base64 && ![base64 isEqualToString:LocalStr_None]) {
            //取项目的bundleIdentifier作为KEY
            NSData *data = [self dataWithBase64EncodedString:base64];
            //IOS 自带DES解密 Begin
            data = [self DESDecrypt:data WithKey:DesKey];
            //IOS 自带DES加密 End
            return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
        else {
            return LocalStr_None;
        }

}

/************************************************************
 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
 函数描述 : 文本数据进行DES加密
 输入参数 : (NSData *)data
 (NSString *)key
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 : 此函数不可用于过长文本
 **********************************************************/
+ (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesEncrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    
    free(buffer);
    return nil;
}

/************************************************************
 函数名称 : + (NSData *)DESEncrypt:(NSData *)data WithKey:(NSString *)key
 函数描述 : 文本数据进行DES解密
 输入参数 : (NSData *)data
 (NSString *)key
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 : 此函数不可用于过长文本
 **********************************************************/
+ (NSData *)DESDecrypt:(NSData *)data WithKey:(NSString *)key
{
    char keyPtr[kCCKeySizeAES256+1];
    bzero(keyPtr, sizeof(keyPtr));
    
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];
    
    NSUInteger dataLength = [data length];
    
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
                                          kCCOptionPKCS7Padding | kCCOptionECBMode,
                                          keyPtr, kCCBlockSizeDES,
                                          NULL,
                                          [data bytes], dataLength,
                                          buffer, bufferSize,
                                          &numBytesDecrypted);
    
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    
    free(buffer);
    return nil;
}

/************************************************************
 函数名称 : + (NSData *)dataWithBase64EncodedString:(NSString *)string
 函数描述 : base64格式字符串转换为文本数据
 输入参数 : (NSString *)string
 输出参数 : N/A
 返回参数 : (NSData *)
 备注信息 :
 **********************************************************/
+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (string == nil)
        [NSException raise:NSInvalidArgumentException format:@""];
    if ([string length] == 0)
        return [NSData data];
    
    static char *decodingTable = NULL;
    if (decodingTable == NULL)
    {
        decodingTable = malloc(256);
        if (decodingTable == NULL)
            return nil;
        memset(decodingTable, CHAR_MAX, 256);
        NSUInteger i;
        for (i = 0; i < 64; i++)
            decodingTable[(short)encodingTable[i]] = i;
    }
    
    const char *characters = [string cStringUsingEncoding:NSASCIIStringEncoding];
    if (characters == NULL)     //  Not an ASCII string!
        return nil;
    char *bytes = malloc((([string length] + 3) / 4) * 3);
    if (bytes == NULL)
        return nil;
    NSUInteger length = 0;
    
    NSUInteger i = 0;
    while (YES)
    {
        char buffer[4];
        short bufferLength;
        for (bufferLength = 0; bufferLength < 4; i++)
        {
            if (characters[i] == '\0')
                break;
            if (isspace(characters[i]) || characters[i] == '=')
                continue;
            buffer[bufferLength] = decodingTable[(short)characters[i]];
            if (buffer[bufferLength++] == CHAR_MAX)      //  Illegal character!
            {
                free(bytes);
                return nil;
            }
        }
        
        if (bufferLength == 0)
            break;
        if (bufferLength == 1)      //  At least two characters are needed to produce one byte!
        {
            free(bytes);
            return nil;
        }
        
        //  Decode the characters in the buffer to bytes.
        bytes[length++] = (buffer[0] << 2) | (buffer[1] >> 4);
        if (bufferLength > 2)
            bytes[length++] = (buffer[1] << 4) | (buffer[2] >> 2);
        if (bufferLength > 3)
            bytes[length++] = (buffer[2] << 6) | buffer[3];
    }
    
    bytes = realloc(bytes, length);
    return [NSData dataWithBytesNoCopy:bytes length:length];
}

/**
 *  加密生成base64
 */
+ (NSString *)base64EncodedStringFromData:(NSData *)data{
        if ([data length] == 0)
            return @"";
    
        char *characters = malloc((([data length] + 2) / 3) * 4);
        if (characters == NULL)
            return nil;
        NSUInteger length = 0;
    
        NSUInteger i = 0;
        while (i < [data length])
        {
            char buffer[3] = {0,0,0};
            short bufferLength = 0;
            while (bufferLength < 3 && i < [data length])
                buffer[bufferLength++] = ((char *)[data bytes])[i++];
    
            //  Encode the bytes in the buffer to four characters, including padding "=" characters if necessary.
            characters[length++] = encodingTable[(buffer[0] & 0xFC) >> 2];
            characters[length++] = encodingTable[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
            if (bufferLength > 1)
                characters[length++] = encodingTable[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
            else characters[length++] = '=';
            if (bufferLength > 2)
                characters[length++] = encodingTable[buffer[2] & 0x3F];
            else characters[length++] = '=';
        }
    
        return [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];

}



@end

 

转载于:https://www.cnblogs.com/onlyMyRailGun/p/5853344.html

没有更多推荐了,返回首页