16进制 aes ios

2015-12-04 14:26:41 lanzeng_in_sz 阅读数 1028

+ (NSString *) encryptUseDES:(NSString *)plainText key:(NSString *)key

{


    NSString *ciphertext = nil;

    const char *textBytes = [plainText UTF8String];

    size_t dataLength = [plainText length];

    //==================

    

    uint8_t *bufferPtr = NULL;

    size_t bufferPtrSize = 0;

    size_t movedBytes = 0;

    

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

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

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


    

    NSString *testString = @"f7afc629";

    NSData *testData = [testString dataUsingEncoding: NSUTF8StringEncoding];

    Byte *iv = (Byte *)[testData bytes];

     

 

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES,

                                          kCCOptionPKCS7Padding,

                                          iv, kCCKeySizeDES,

                                          iv,

                                          textBytes, dataLength,

                                          (void *)bufferPtr, bufferPtrSize,

                                          &movedBytes);

    if (cryptStatus == kCCSuccess) {

        

  

        

    ciphertext= [des parseByte2HexString:bufferPtr :(int)movedBytes];

    

    }

    ciphertext=[ciphertext uppercaseString];//字符变大写

    

    

    return ciphertext ;

 

    

}



//十六进制转字符串

+(NSString *) parseByte2HexString:(Byte *) bytes  :(int)len{

    

    

    NSString *hexStr = @"";

    

    if(bytes)

    {

        for(int i=0;i<len;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;

}





2016-04-06 16:57:55 JimmieYE 阅读数 1826
[objc] view plain copy
  1. //////////////AES加密方式: AES 128 ECB PKCS7Padding 16进制加密解密  //////////////  
  2.     NSString *originalStr=@"AES";  
  3.   
  4.     //加密  
  5.     NSString *encryStr = [AES128Util AES128Encrypt:originalStr key:AES_KEY];  
  6.     //解密  
  7.     NSString *decryStr = [AES128Util AES128Decrypt:encryStr key:AES_KEY];  
  8.       
  9.     NSLog(@"\n加密前:%@\n加密后:%@ \n解密后:%@",originalStr,encryStr,decryStr);  


[objc] view plain copy
  1. //  
  2. //  AES128Util.h  
  3. //  ASE128Demo  
  4. //  
  5. //  Created by zhenghaishu on 11/11/13.  
  6. //  Copyright (c) 2013 Youku.com inc. All rights reserved.  
  7. //  
  8.   
  9. #import <Foundation/Foundation.h>  
  10.   
  11. @interface AES128Util : NSObject  
  12.   
  13. +(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key;  
  14.   
  15. +(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key;  
  16.   
  17. @end  


[objc] view plain copy
  1. //  
  2. //  AES128Util.m  
  3. //  ASE128Demo  
  4. //  
  5. //  Created by zhenghaishu on 11/11/13.  
  6. //  Copyright (c) 2013 Youku.com inc. All rights reserved.  
  7. //  
  8.   
  9. #import "AES128Util.h"  
  10. #import <CommonCrypto/CommonCryptor.h>  
  11. #import "GTMBase64.h"  
  12.   
  13. @implementation AES128Util  
  14.   
  15. +(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key  
  16. {  
  17.     char keyPtr[kCCKeySizeAES128+1];  
  18.     memset(keyPtr, 0sizeof(keyPtr));  
  19.     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
  20.       
  21.     NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];  
  22.     NSUInteger dataLength = [data length];  
  23.       
  24.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  25.     voidvoid *buffer = malloc(bufferSize);  
  26.     size_t numBytesEncrypted = 0;  
  27.     CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,  
  28.                                           kCCAlgorithmAES128,  
  29.                                           kCCOptionPKCS7Padding|kCCOptionECBMode,  
  30.                                           keyPtr,  
  31.                                           kCCBlockSizeAES128,  
  32.                                           NULL,  
  33.                                           [data bytes],  
  34.                                           dataLength,  
  35.                                           buffer,  
  36.                                           bufferSize,  
  37.                                           &numBytesEncrypted);  
  38.     if (cryptStatus == kCCSuccess) {  
  39.         NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];  
  40.         //return [GTMBase64 stringByEncodingData:resultData];  
  41.         return [self hexStringFromData:resultData];  
  42.   
  43.     }  
  44.     free(buffer);  
  45.     return nil;  
  46. }  
  47.   
  48.   
  49. +(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key  
  50. {  
  51.     char keyPtr[kCCKeySizeAES128 + 1];  
  52.     memset(keyPtr, 0sizeof(keyPtr));  
  53.     [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
  54.       
  55.     //NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];  
  56.       
  57.     NSData *data=[self dataForHexString:encryptText];  
  58.       
  59.     NSUInteger dataLength = [data length];  
  60.     size_t bufferSize = dataLength + kCCBlockSizeAES128;  
  61.     voidvoid *buffer = malloc(bufferSize);  
  62.       
  63.     size_t numBytesCrypted = 0;  
  64.     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,  
  65.                                           kCCAlgorithmAES128,  
  66.                                           kCCOptionPKCS7Padding|kCCOptionECBMode,  
  67.                                           keyPtr,  
  68.                                           kCCBlockSizeAES128,  
  69.                                           NULL,  
  70.                                           [data bytes],  
  71.                                           dataLength,  
  72.                                           buffer,  
  73.                                           bufferSize,  
  74.                                           &numBytesCrypted);  
  75.     if (cryptStatus == kCCSuccess) {  
  76.         NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];  
  77.         return [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];  
  78.     }  
  79.     free(buffer);  
  80.     return nil;  
  81. }  
  82.   
  83. // 普通字符串转换为十六进  
  84. + (NSString *)hexStringFromData:(NSData *)data {  
  85.     Byte *bytes = (Byte *)[data bytes];  
  86.     // 下面是Byte 转换为16进制。  
  87.     NSString *hexStr = @"";  
  88.     for(int i=0; i<[data length]; i++) {  
  89.         NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i] & 0xff]; //16进制数  
  90.         newHexStr = [newHexStr uppercaseString];  
  91.           
  92.         if([newHexStr length] == 1) {  
  93.             newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];  
  94.         }  
  95.           
  96.         hexStr = [hexStr stringByAppendingString:newHexStr];  
  97.           
  98.     }  
  99.     return hexStr;  
  100. }  
  101.   
  102. //参考:http://blog.csdn.net/linux_zkf/article/details/17124577  
  103. //十六进制转Data  
  104. + (NSData*)dataForHexString:(NSString*)hexString  
  105. {  
  106.     if (hexString == nil) {  
  107.           
  108.         return nil;  
  109.     }  
  110.       
  111.     const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];  
  112.     NSMutableData* data = [NSMutableData data];  
  113.     while (*ch) {  
  114.         if (*ch == ' ') {  
  115.             continue;  
  116.         }  
  117.         char byte = 0;  
  118.         if ('0' <= *ch && *ch <= '9') {  
  119.               
  120.             byte = *ch - '0';  
  121.         }else if ('a' <= *ch && *ch <= 'f') {  
  122.               
  123.             byte = *ch - 'a' + 10;  
  124.         }else if ('A' <= *ch && *ch <= 'F') {  
  125.               
  126.             byte = *ch - 'A' + 10;  
  127.               
  128.         }  
  129.           
  130.         ch++;  
  131.           
  132.         byte = byte << 4;  
  133.           
  134.         if (*ch) {  
  135.               
  136.             if ('0' <= *ch && *ch <= '9') {  
  137.                   
  138.                 byte += *ch - '0';  
  139.                   
  140.             } else if ('a' <= *ch && *ch <= 'f') {  
  141.                   
  142.                 byte += *ch - 'a' + 10;  
  143.                   
  144.             }else if('A' <= *ch && *ch <= 'F'){  
  145.                   
  146.                 byte += *ch - 'A' + 10;  
  147.                   
  148.             }  
  149.               
  150.             ch++;  
  151.               
  152.         }  
  153.           
  154.         [data appendBytes:&byte length:1];  
  155.           
  156.     }  
  157.       
  158.     return data;  
  159. }  
  160.   
  161. @end  

AES在线加密工具

http://www.seacha.com/tools/aes.html?src=wenhan123455678888050i33i206279278&mode=ECB&keylen=128&key=1234567890123456&iv=1234567890123456&bpkcs=pkcs7padding&session=FH4xlZr0LlqsJVtwfbVw&aes=ac518f9f8429369bf129da6d6633cbb2&encoding=hex&type=0

参考工程:https://github.com/zhenghaishu/AES128-for-iOS



http://pan.baidu.com/s/1jHmo9Pc

2015-07-16 14:01:24 wj731236239 阅读数 1459

 我想关于AES算法大家应该都已经了解了,我就不多介绍了。这是本人第一次写技术博文,如果有不对之处欢迎大家指正,共同讨论,一起学习!

      之前在项目上用到AES256加密解密算法,刚开始在java端加密解密都没有问题,在iOS端加密解密也没有问题。但是奇怪的是在java端加密后的文件在iOS端无法正确解密打开,然后简单测试了一下,发现在java端和iOS端采用相同明文,相同密钥加密后的密文不一样!上网查了资料后发现iOS中AES加密算法采用的填充是PKCS7Padding,而java不支持PKCS7Padding,只支持PKCS5Padding。我们知道加密算法由算法+模式+填充组成,所以这两者不同的填充算法导致相同明文相同密钥加密后出现密文不一致的情况。那么我们需要在java中用PKCS7Padding来填充,这样就可以和iOS端填充算法一致了。

      要实现在java端用PKCS7Padding填充,需要用到bouncycastle组件来实现,下面我会提供该包的下载。啰嗦了一大堆,下面是一个简单的测试,上代码!

package com.encrypt.file;
 
 
import java.io.UnsupportedEncodingException;
import java.security.Key;  
import java.security.Security;
 
import javax.crypto.Cipher;  
import javax.crypto.SecretKey;  
import javax.crypto.spec.SecretKeySpec;  
 
public class AES256Encryption{  
     
         /** 
         * 密钥算法 
         * java6支持56位密钥,bouncycastle支持64位 
         * */ 
        public static final String KEY_ALGORITHM="AES";  
           
        /** 
         * 加密/解密算法/工作模式/填充方式 
         *  
         * JAVA6 支持PKCS5PADDING填充方式 
         * Bouncy castle支持PKCS7Padding填充方式 
         * */ 
        public static final String CIPHER_ALGORITHM="AES/ECB/PKCS7Padding";  
           
        /** 
         *  
         * 生成密钥,java6只支持56位密钥,bouncycastle支持64位密钥 
         * @return byte[] 二进制密钥 
         * */ 
        public static byte[] initkey() throws Exception{  
               
//          //实例化密钥生成器  
//          Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
//          KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM, "BC");  
//          //初始化密钥生成器,AES要求密钥长度为128位、192位、256位  
////            kg.init(256);  
//          kg.init(128); 
//          //生成密钥  
//          SecretKey secretKey=kg.generateKey();  
//          //获取二进制密钥编码形式  
//          return secretKey.getEncoded();  
            //为了便于测试,这里我把key写死了,如果大家需要自动生成,可用上面注释掉的代码
            return new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c,
                    0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a, 0x04, 0x0f,
                    0x06, 0x0f, 0x0e, 0x09, 0x05, 0x01, 0x0a, 0x0a, 0x01, 0x09,
                    0x06, 0x07, 0x09, 0x0d };
        }
 
        /** 
         * 转换密钥 
         * @param key 二进制密钥 
         * @return Key 密钥 
         * */ 
        public static Key toKey(byte[] key) throws Exception{  
            //实例化DES密钥  
            //生成密钥  
            SecretKey secretKey=new SecretKeySpec(key,KEY_ALGORITHM);  
            return secretKey;  
        }  
           
        /** 
         * 加密数据 
         * @param data 待加密数据 
         * @param key 密钥 
         * @return byte[] 加密后的数据 
         * */ 
        public static byte[] encrypt(byte[] data,byte[] key) throws Exception{  
            //还原密钥  
            Key k=toKey(key);  
            /** 
             * 实例化 
             * 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现 
             * Cipher.getInstance(CIPHER_ALGORITHM,"BC") 
             */ 
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM, "BC");  
            //初始化,设置为加密模式  
            cipher.init(Cipher.ENCRYPT_MODE, k);  
            //执行操作  
            return cipher.doFinal(data);  
        }  
        /** 
         * 解密数据 
         * @param data 待解密数据 
         * @param key 密钥 
         * @return byte[] 解密后的数据 
         * */ 
        public static byte[] decrypt(byte[] data,byte[] key) throws Exception{  
            //欢迎密钥  
            Key k =toKey(key);  
            /** 
             * 实例化 
             * 使用 PKCS7PADDING 填充方式,按如下方式实现,就是调用bouncycastle组件实现 
             * Cipher.getInstance(CIPHER_ALGORITHM,"BC") 
             */ 
            Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM);  
            //初始化,设置为解密模式
            cipher.init(Cipher.DECRYPT_MODE, k);  
            //执行操作  
            return cipher.doFinal(data);  
        }  
        /** 
         * @param args 
         * @throws UnsupportedEncodingException 
         * @throws Exception  
         */ 
        public static void main(String[] args) throws UnsupportedEncodingException{  
             
            String str="AES";  
            System.out.println("原文:"+str);  
 
            //初始化密钥  
            byte[] key;
            try {
                key = AES256Encryption.initkey();
                System.out.print("密钥:");  
                for(int i = 0;i<key.length;i++){
                    System.out.printf("%x", key[i]);
                }
                System.out.print("\n");
                //加密数据  
                byte[] data=AES256Encryption.encrypt(str.getBytes(), key);  
                System.out.print("加密后:"); 
                for(int i = 0;i<data.length;i++){
                    System.out.printf("%x", data[i]);
                }
                System.out.print("\n");
                 
                //解密数据  
                data=AES256Encryption.decrypt(data, key);  
                System.out.println("解密后:"+new String(data)); 
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
              
        }  
    }

运行程序后的结果截图:


上图可以看到密钥和密文,好了,我们来看看iOS端实现AES256加密解密的方法,有点复杂,大家耐心点看就好。

EncryptAndDecrypt.h文件

//
//  EncryptAndDecrypt.h
//  AES256EncryptionDemo
//
//  Created by rich sun on 12-12-13.
//  Copyright (c) 2012年 rich sun. All rights reserved.
//
 
#import <Foundation/Foundation.h>
 
@class NSString;
 
@interface NSData (Encryption)
 
- (NSData *)AES256EncryptWithKey:(NSData *)key;   //加密
- (NSData *)AES256DecryptWithKey:(NSData *)key;   //解密
- (NSString *)newStringInBase64FromData;            //追加64编码
+ (NSString*)base64encode:(NSString*)str;           //同上64编码
 
@end


EncryptAndDecrypt.m文件

//
//  EncryptAndDecrypt.m
//  AES256EncryptionDemo
//
//  Created by rich sun on 12-12-13.
//  Copyright (c) 2012年 rich sun. All rights reserved.
//
 
#import "EncryptAndDecrypt.h"
#import <CommonCrypto/CommonCrypto.h>
static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
@implementation NSData (Encryption)
 
- (NSData *)AES256EncryptWithKey:(NSData *)key   //加密
{
 
    //AES256加密,密钥应该是32位的
    const void * keyPtr2 = [key bytes];
    char (*keyPtr)[32] = keyPtr2;
 
    //对于块加密算法,输出大小总是等于或小于输入大小加上一个块的大小
    //所以在下边需要再加上一个块的大小
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
 
    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding/*这里就是刚才说到的PKCS7Padding填充了*/ | kCCOptionECBMode,
                                          [key bytes], kCCKeySizeAES256,
                                          NULL,/* 初始化向量(可选) */
                                          [self bytes], dataLength,/*输入*/
                                          buffer, bufferSize,/* 输出 */
                                          &numBytesEncrypted);
 
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);//释放buffer
    return nil;
}
 
 
- (NSData *)AES256DecryptWithKey:(NSData *)key   //解密
{
 
    //同理,解密中,密钥也是32位的
    const void * keyPtr2 = [key bytes];
    char (*keyPtr)[32] = keyPtr2;
 
    //对于块加密算法,输出大小总是等于或小于输入大小加上一个块的大小
    //所以在下边需要再加上一个块的大小
    NSUInteger dataLength = [self length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
 
    size_t numBytesDecrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                          kCCOptionPKCS7Padding/*这里就是刚才说到的PKCS7Padding填充了*/ | kCCOptionECBMode,
                                          keyPtr, kCCKeySizeAES256,
                                          NULL,/* 初始化向量(可选) */
                                          [self bytes], dataLength,/* 输入 */
                                          buffer, bufferSize,/* 输出 */
                                          &numBytesDecrypted);
    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesDecrypted];
    }
    free(buffer);
    return nil;
}
 
 
- (NSString *)newStringInBase64FromData            //追加64编码
{
    NSMutableString *dest = [[NSMutableString alloc] initWithString:@""];
    unsigned char * working = (unsigned char *)[self bytes];
    int srcLen = [self length];
    for (int i=0; i<srcLen; i += 3) {
        for (int nib=0; nib<4; nib++) {
            int byt = (nib == 0)?0:nib-1;
            int ix = (nib+1)*2;
            if (i+byt >= srcLen) break;
            unsigned char curr = ((working[i+byt] << (8-ix)) & 0x3F);
            if (i+nib < srcLen) curr |= ((working[i+nib] >> ix) & 0x3F);
            [dest appendFormat:@"%c", base64[curr]];
        }
    }
    return dest;
}
 
+ (NSString*)base64encode:(NSString*)str
{
    if ([str length] == 0)
        return @"";
    const char *source = [str UTF8String];
    int strlength  = strlen(source);
    char *characters = malloc(((strlength + 2) / 3) * 4);
    if (characters == NULL)
        return nil;
    NSUInteger length = 0;
    NSUInteger i = 0;
    while (i < strlength) {
        char buffer[3] = {0,0,0};
        short bufferLength = 0;
        while (bufferLength < 3 && i < strlength)
            buffer[bufferLength++] = source[i++];
        characters[length++] = base64[(buffer[0] & 0xFC) >> 2];
        characters[length++] = base64[((buffer[0] & 0x03) << 4) | ((buffer[1] & 0xF0) >> 4)];
        if (bufferLength > 1)
            characters[length++] = base64[((buffer[1] & 0x0F) << 2) | ((buffer[2] & 0xC0) >> 6)];
        else characters[length++] = '=';
        if (bufferLength > 2)
            characters[length++] = base64[buffer[2] & 0x3F];
        else characters[length++] = '=';
    }
    NSString *g = [[NSString alloc] initWithBytesNoCopy:characters length:length encoding:NSASCIIStringEncoding freeWhenDone:YES];
    return g;
}
 
@end


ViewController.m文件

//  ViewController.m
//  AES256EncryptionDemo
//
//  Created by 孙 裔 on 12-12-13.
//  Copyright (c) 2012年 rich sun. All rights reserved.
//
 
#import "ViewController.h"
#import "EncryptAndDecrypt.h"
 
@interface ViewController ()
 
@end
 
@implementation ViewController
@synthesize plainTextField;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
 
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//这个函数实现了用户输入完后点击视图背景,关闭键盘
- (IBAction)backgroundTap:(id)sender{
    [plainTextField resignFirstResponder];
}
 
- (IBAction)encrypt:(id)sender {
     
    NSString *plainText = plainTextField.text;//明文
    NSData *plainTextData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
     
    //为了测试,这里先把密钥写死
    Byte keyByte[] = {0x08,0x08,0x04,0x0b,0x02,0x0f,0x0b,0x0c,0x01,0x03,0x09,0x07,0x0c,0x03,
        0x07,0x0a,0x04,0x0f,0x06,0x0f,0x0e,0x09,0x05,0x01,0x0a,0x0a,0x01,0x09,
        0x06,0x07,0x09,0x0d};
    //byte转换为NSData类型,以便下边加密方法的调用
    NSData *keyData = [[NSData alloc] initWithBytes:keyByte length:32];
    //
    NSData *cipherTextData = [plainTextData AES256EncryptWithKey:keyData];
    Byte *plainTextByte = (Byte *)[cipherTextData bytes];
    for(int i=0;i<[cipherTextData length];i++){
        printf("%x",plainTextByte[i]);
    }
 
}
@end

大家可以看到这里的密文和java端的密文是一致的,这样我们就成功完成了。只要密文和密钥是一致的,那么解密应该就不会有什么问题了后面如果有需要解密的可以自己调用解密的那个方法就可以了。

      如有什么不明之处欢迎大家留言,互相学习!很遗憾这里无法上传附件,代码中需要的包只能以链接的方式让各位去下了:

jce_policy-6.zip 下载链接:http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html

下载解压后将里边的两个jar包(local_policy.jar,US_export_policy.jar)替换掉jdk安装路径下security文件夹中的两个包。

bcprov-jdk16-139.jar 下载链接:http://www.bouncycastle.org

原文出处:http://my.oschina.net/nicsun/blog/95632


2014-04-24 12:40:55 micro_cai 阅读数 2642

以下代码源自网络,本人稍作整理,供各位参考,所有权归原作者。


1、================= 3DES加密 / 解密 =================

1)加密

/**
 *  3DES加密
 *
 *  @param plainText 明文
 *  @param key       密钥
 *
 *  @return 加密结果
 */
- (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] autorelease];
    }
    
    return ciphertext;
}

2)解密

/**
 *  3DES解密
 *
 *  @param cipherText 密文
 *  @param key        密钥
 *
 *  @return 解密结果
 */
- (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] autorelease];
    }
    
    return plainText;
}

2、================= MD5加密 =================

1)32位MD5加密

/**
 *  32位MD5加密
 *
 *  @param string           加密字符串
 *  @param LetterCaseOption 加密选项 {1:大写;2:小写}
 *
 *  @return 加密后的字符串
 */
- (NSString *)encodeUsingMD5ByString:(NSString *)plainText letterCaseOption:(NSInteger)letterCaseOption{
    const char *cStr = [plainText UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, strlen(cStr), digest );
    NSMutableString *encodeString = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [encodeString appendFormat:@"%02x", digest[i]];
    
    NSString *cipherText = nil;
    
    if (letterCaseOption == 1) {
        cipherText = [encodeString uppercaseString];
    }else{
        cipherText = [encodeString lowercaseString];
    }
    
    return cipherText;
}

2)16位MD5加密

/**
 *  16位MD5加密
 *
 *  @param plainText        明文
 *  @param letterCaseOption 大小写选项
 *
 *  @return 加密结果
 */
- (NSString *)encodeUsing16BitsMD5ByString:(NSString *)plainText letterCaseOption:(NSInteger)letterCaseOption{
    const char *cStr = [plainText UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result);
    
    NSString *encodeString = [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                              result[0], result[1], result[2], result[3],
                              result[4], result[5], result[6], result[7],
                              result[8], result[9], result[10], result[11],
                              result[12], result[13], result[14], result[15]
                              ];
    
    NSString *cipherText = nil;
    
    if (letterCaseOption == 1) {
        cipherText = [encodeString uppercaseString];
    }else{
        cipherText = [encodeString lowercaseString];
    }
    
    return cipherText;
}


注:MD5加密不可逆,所以没有MD5解密

3、================= Base64编码 / 解码 =================

/**
 *  Base64编码
 *
 *  @param data 源信息
 *
 *  @return 编码结果
 */
- (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++];
        }
        
        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++] = '=';
        }
    }
    
    NSString *formatString = [[NSString alloc] initWithBytesNoCopy:characters
                                                            length:length
                                                          encoding:NSUTF8StringEncoding
                                                      freeWhenDone:YES];
    return formatString;
}

注:Base64不是一种加密方式,只是一种编码规范,考虑到在加密 / 解密的过程中经常用到Base64,故添加到本文中。

(未完待续)

2017-02-16 11:36:27 L_weiguo 阅读数 903

1.使用

 NSString *originalStr=@"AES";  
  
    //加密  
    NSString *encryStr = [AES128Util AES128Encrypt:originalStr key:AES_KEY];  
    //解密  
    NSString *decryStr = [AES128Util AES128Decrypt:encryStr key:AES_KEY];  
      
    NSLog(@"\n加密前:%@\n加密后:%@ \n解密后:%@",originalStr,encryStr,decryStr);

2.具体实现类  .h文件

#import <Foundation/Foundation.h>  
  
@interface AES128Util : NSObject  
  
+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key;  
  
+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key;  
  
@end  

.m 文件

#import "AES128Util.h"  
#import <CommonCrypto/CommonCryptor.h>  
#import "GTMBase64.h"  
  
@implementation AES128Util  
  
+(NSString *)AES128Encrypt:(NSString *)plainText key:(NSString *)key  
{  
    char keyPtr[kCCKeySizeAES128+1];  
    memset(keyPtr, 0, sizeof(keyPtr));  
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
      
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];  
    NSUInteger dataLength = [data length];  
      
    size_t bufferSize = dataLength + kCCBlockSizeAES128;  
    voidvoid *buffer = malloc(bufferSize);  
    size_t numBytesEncrypted = 0;  
    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,  
                                          kCCAlgorithmAES128,  
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,  
                                          keyPtr,  
                                          kCCBlockSizeAES128,  
                                          NULL,  
                                          [data bytes],  
                                          dataLength,  
                                          buffer,  
                                          bufferSize,  
                                          &numBytesEncrypted);  
    if (cryptStatus == kCCSuccess) {  
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];  
        //return [GTMBase64 stringByEncodingData:resultData];  
        return [self hexStringFromData:resultData];  
  
    }  
    free(buffer);  
    return nil;  
}  
  
  
+(NSString *)AES128Decrypt:(NSString *)encryptText key:(NSString *)key  
{  
    char keyPtr[kCCKeySizeAES128 + 1];  
    memset(keyPtr, 0, sizeof(keyPtr));  
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];  
      
    //NSData *data = [GTMBase64 decodeData:[encryptText dataUsingEncoding:NSUTF8StringEncoding]];  
      
    NSData *data=[self dataForHexString:encryptText];  
      
    NSUInteger dataLength = [data length];  
    size_t bufferSize = dataLength + kCCBlockSizeAES128;  
    voidvoid *buffer = malloc(bufferSize);  
      
    size_t numBytesCrypted = 0;  
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,  
                                          kCCAlgorithmAES128,  
                                          kCCOptionPKCS7Padding|kCCOptionECBMode,  
                                          keyPtr,  
                                          kCCBlockSizeAES128,  
                                          NULL,  
                                          [data bytes],  
                                          dataLength,  
                                          buffer,  
                                          bufferSize,  
                                          &numBytesCrypted);  
    if (cryptStatus == kCCSuccess) {  
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];  
        return [[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding] autorelease];  
    }  
    free(buffer);  
    return nil;  
}  
  
// 普通字符串转换为十六进  
+ (NSString *)hexStringFromData:(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进制数  
        newHexStr = [newHexStr uppercaseString];  
          
        if([newHexStr length] == 1) {  
            newHexStr = [NSString stringWithFormat:@"0%@",newHexStr];  
        }  
          
        hexStr = [hexStr stringByAppendingString:newHexStr];  
          
    }  
    return hexStr;  
}  
  
//参考:http://blog.csdn.net/linux_zkf/article/details/17124577  
//十六进制转Data  
+ (NSData*)dataForHexString:(NSString*)hexString  
{  
    if (hexString == nil) {  
          
        return nil;  
    }  
      
    const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];  
    NSMutableData* data = [NSMutableData data];  
    while (*ch) {  
        if (*ch == ' ') {  
            continue;  
        }  
        char byte = 0;  
        if ('0' <= *ch && *ch <= '9') {  
              
            byte = *ch - '0';  
        }else if ('a' <= *ch && *ch <= 'f') {  
              
            byte = *ch - 'a' + 10;  
        }else if ('A' <= *ch && *ch <= 'F') {  
              
            byte = *ch - 'A' + 10;  
              
        }  
          
        ch++;  
          
        byte = byte << 4;  
          
        if (*ch) {  
              
            if ('0' <= *ch && *ch <= '9') {  
                  
                byte += *ch - '0';  
                  
            } else if ('a' <= *ch && *ch <= 'f') {  
                  
                byte += *ch - 'a' + 10;  
                  
            }else if('A' <= *ch && *ch <= 'F'){  
                  
                byte += *ch - 'A' + 10;  
                  
            }  
              
            ch++;  
              
        }  
          
        [data appendBytes:&byte length:1];  
          
    }  
      
    return data;  
}  


iOS AES加密

阅读数 598

iOS AES128加解密

阅读数 8868