Object-C AES128 Encrypt And Decrypt

/**
Base64.h
**/

#import <Foundation/Foundation.h>

@interface NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
- (NSString *)base64EncodedString;

@end

@interface NSString (Base64)

+ (NSString *)stringWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
- (NSString *)base64EncodedString;
- (NSString *)base64DecodedString;
- (NSData *)base64DecodedData;

@end
/**
Base64.m
**/

#import "Base64.h"

#pragma GCC diagnostic ignored "-Wselector"

#import <Availability.h>
#if !__has_feature(objc_arc)
#error This library requires automatic reference counting
#endif

@implementation NSData (Base64)

+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
    if (![string length]) return nil;

    NSData *decoded = nil;

#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0

    if (![NSData instancesRespondToSelector:@selector(initWithBase64EncodedString:options:)])
    {
        decoded = [[self alloc] initWithBase64Encoding:[string stringByReplacingOccurrencesOfString:@"[^A-Za-z0-9+/=]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, [string length])]];
    }
    else

#endif

    {
        decoded = [[self alloc] initWithBase64EncodedString:string options:NSDataBase64DecodingIgnoreUnknownCharacters];
    }

    return [decoded length]? decoded: nil;
}

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    if (![self length]) return nil;

    NSString *encoded = nil;

#if __MAC_OS_X_VERSION_MIN_REQUIRED < __MAC_10_9 || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_7_0

    if (![NSData instancesRespondToSelector:@selector(base64EncodedStringWithOptions:)])
    {
        //encoded = [self base64Encoding];
        encoded = [self base64EncodedString];
    }
    else

#endif

    {
        switch (wrapWidth)
        {
            case 64:
            {
                return [self base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            }
            case 76:
            {
                return [self base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength];
            }
            default:
            {
                encoded = [self base64EncodedStringWithOptions:(NSDataBase64EncodingOptions)0];
            }
        }
    }

    if (!wrapWidth || wrapWidth >= [encoded length])
    {
        return encoded;
    }

    wrapWidth = (wrapWidth / 4) * 4;
    NSMutableString *result = [NSMutableString string];
    for (NSUInteger i = 0; i < [encoded length]; i+= wrapWidth)
    {
        if (i + wrapWidth >= [encoded length])
        {
            [result appendString:[encoded substringFromIndex:i]];
            break;
        }
        [result appendString:[encoded substringWithRange:NSMakeRange(i, wrapWidth)]];
        [result appendString:@"\r\n"];
    }

    return result;
}

- (NSString *)base64EncodedString
{
    return [self base64EncodedStringWithWrapWidth:0];
}

@end

@implementation NSString (Base64)

+ (NSString *)stringWithBase64EncodedString:(NSString *)string
{
    NSData *data = [NSData dataWithBase64EncodedString:string];
    if (data)
    {
        return [[self alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return nil;
}

- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data base64EncodedStringWithWrapWidth:wrapWidth];
}

- (NSString *)base64EncodedString
{
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    return [data base64EncodedString];
}

- (NSString *)base64DecodedString
{
    return [NSString stringWithBase64EncodedString:self];
}

- (NSData *)base64DecodedData
{
    return [NSData dataWithBase64EncodedString:self];
}

@end
/**
AES128.h
**/

#import <Foundation/Foundation.h>

@interface AES128 : NSObject
+(NSString *)AES128Encrypt:(NSString *)plainText withKey:(NSString *)key;
+(NSString *)processDecodedString:(NSString *)decoded;
+(NSString *)AES128Decrypt:(NSString *)encryptText withKey:(NSString *)key;

@end
/**
AES128.h
**/

#import "AES128.h"
#import <CommonCrypto/CommonCryptor.h>
#import "Base64.h"

@implementation AES128

+(NSString *)AES128Encrypt:(NSString *)plainText withKey:(NSString *)key
{

    if( ![self validKey:key] ){
        return nil;
    }

    char keyPtr[kCCKeySizeAES128+1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128+1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [key getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    NSUInteger dataLength = [data length];

    int diff = kCCKeySizeAES128 - (dataLength % kCCKeySizeAES128);
    unsigned long newSize = 0;

    if(diff > 0)
    {
        newSize = dataLength + diff;
    }

    char dataPtr[newSize];
    memcpy(dataPtr, [data bytes], [data length]);
    for(int i = 0; i < diff; i++)
    {
        dataPtr[i + dataLength] =0x0000;
    }

    size_t bufferSize = newSize + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);
    memset(buffer, 0, bufferSize);

    size_t numBytesCrypted = 0;

    CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,
                                          [key UTF8String],
                                          kCCKeySizeAES128,
                                          [key UTF8String],
                                          dataPtr,
                                          sizeof(dataPtr),
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);

    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];
        return [resultData base64EncodedString];
    }
    free(buffer);
    return nil;
}

+(NSString *)processDecodedString:(NSString *)decoded
{
    if( decoded==nil || decoded.length==0 ){
        return nil;
    }
    const char *tmpStr=[decoded UTF8String];
    int i=0;

    while( tmpStr[i]!=‘\0‘ )
    {
        i++;
    }
    NSString *final=[[NSString alloc]initWithBytes:tmpStr length:i encoding:NSUTF8StringEncoding];
    return final;

}

+(NSString *)AES128Decrypt:(NSString *)encryptText withKey:(NSString *)key
{

    if( ![self validKey:key] ){
        return nil;
    }

    char keyPtr[kCCKeySizeAES128 + 1];
    memset(keyPtr, 0, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128 + 1];
    memset(ivPtr, 0, sizeof(ivPtr));
    [key getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];

    NSData *data = [encryptText base64DecodedData];
    NSUInteger dataLength = [data length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesCrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
                                          kCCAlgorithmAES128,
                                          0x0000,
                                          [key UTF8String],
                                          kCCBlockSizeAES128,
                                          [key UTF8String],
                                          [data bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesCrypted);
    if (cryptStatus == kCCSuccess) {
        NSData *resultData = [NSData dataWithBytesNoCopy:buffer length:numBytesCrypted];

        NSString *decoded=[[NSString alloc] initWithData:resultData encoding:NSUTF8StringEncoding];
        return [self processDecodedString:decoded];
    }

    free(buffer);
    return nil;

}

+(BOOL)validKey:(NSString*)key
{
    if( key==nil || key.length !=16 ){
        return NO;
    }
    return YES;
}

-(NSString *)processDecodedString:(NSString *)decoded
{
    if( decoded==nil || decoded.length==0 ){
        return nil;
    }
    const char *tmpStr=[decoded UTF8String];
    int i=0;

    while( tmpStr[i]!=‘\0‘ )
    {
        i++;
    }
    NSString *final=[[NSString alloc]initWithBytes:tmpStr length:i encoding:NSUTF8StringEncoding];
    return final;

}
时间: 2024-10-27 21:36:50

Object-C AES128 Encrypt And Decrypt的相关文章

C# 加密(Encrypt) 解密(Decrypt) 操作类 java与 C# 可以相互加密解密

public sealed class EncryptUtils { #region Base64加密解密 /// <summary> /// Base64加密 /// </summary> /// <param name="input">需要加密的字符串</param> /// <returns></returns> public static string Base64Encrypt(string input)

练习.加密(Encrypt) &amp; 解密(Decrypt)

1.简单加密&解密 1 package com.java7.myencrypt.main; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 9 public class MyEncrypt { 10 public s

如何使用powershell encrypt(加密), decrypt(解密) 账户密码

在SharePoint 2010,2013的项目中,考虑到场解决方案的deploy可以会造成系统的down time, 还有追求一键安装配置所有的服务,越来越多的人用Powershell去创建service application, web application, site collection,在页面配置webpart, 不可避免的,我们需要在创建过程中传递一些账户信息,如果直接把用户密码存放在powershell之中,实在是不安全,任何能接触到source code的人都能够看到这些信息,

Encryp and decrypt a string

1 using System; 2 using System.IO; 3 using System.Security.Cryptography; 4 using System.Text; 5 6 namespace Utility 7 { 8 /// <summary> 9 /// http://stackoverflow.com/questions/202011/encrypt-and-decrypt-a-string 10 /// </summary> 11 public cl

微信破解,解密?How To Decrypt WeChat EnMicroMsg.db Database?

原文地址:http://articles.forensicfocus.com/2014/10/01/decrypt-wechat-enmicromsgdb-database/ WeChat is a smartphone application where users can chat with their friends, share pictures, videos and audio chats. Users can also make free video calls and voice

AES与RSA混合加密完整实例

前言 前段时间看到一篇文章讲如何保证API调用时数据的安全性(传送门:https://blog.csdn.net/ityouknow/article/details/80603617),文中讲到利用RSA来加密传输AES的秘钥,用AES来加密数据,并提供如下思路: 说人话就是前.后端各自生成自己的RSA秘钥对(公钥.私钥),然后交换公钥(后端给前端的是正常的明文公钥,前端给后端的是用后端公钥加密后的密文公钥:PS:其实我觉得直接交换两个明文公钥就行了),后端生成AES的明文key,用明文key进

netty Architectural Overview --reference

reference from:http://docs.jboss.org/netty/3.1/guide/html/architecture.html 2.1. Rich Buffer Data Structure 2.2. Universal Asynchronous I/O API 2.3. Event Model based on the Interceptor Chain Pattern 2.4. Advanced Components for More Rapid Developmen

设计模式实战应用之五:工厂方法模式

工厂方法模式的定义        工厂方法模式的应用相当广泛. 工厂方法模式在 Java API 中的应用比比皆是:java.util.Collection 接口的 iterator 方法就是一个非常著名的工厂方法模式的演示样例:java.net.URLStreamHandlerFactory 的 createURLStreamHandler(String protocol)  也是工厂方法模式的一个非常经典的应用,URLStreamHandlerFactory 定义了一个用来创建 URLStr

openssl之对称加密算法命令详解

1.对称加密算法概述 openssl的加密算法库提供了丰富的对称加密算法,我们可以通过openssl提供的对称加密算法指令的方式使用,也可以通过调用openssl提供的API的方式使用. openssl的对称加密算法指令主要用来对数据进行加密和解密处理,openssl基本上为所有其支持的对称加密算法都提供了指令的方式的应用,这些应用指令的名字基本上都是以对称加密算法本身的名字加上位数.加密模式或者其他属性组合而成.例如DES算法的CBC模式,其对应的指令就是des-cbc.可以通过命令查看当前版