sqlite database encrypt

some useful command:

begin transaction;

insert into ..your sql statement

if(some error occors) {

    rollback transaction;

}else {

end transaction; //or commit

}

 

 

#import <Foundation/Foundation.h>
#import <sqlite3.h>

@interface SqliteCrypter : NSObject {
    @private
    NSString* cstrSourceDataBase;
    NSString* cstrDestDataBase;
}

-(BOOL)encryptDatabase: (NSString*)acstrPassword cipher: (NSString*)acstrCipher iteration:(NSString*)acstrIteration;
-(sqlite3*)decryptDatabase: (NSString*)acstrPassword cipher: (NSString*)acstrCipher iteration:(NSString*)acstrIteration;
-(BOOL)changePasswordFrom: (NSString*)acstrOlderPassword: toNewPassword: (NSString*)acstrNewPassword;
@end

#import “SqliteCrypter.h”

@interface SqliteCrypter(Private)
-(BOOL)copyDataTo: (sqlite3*)apSqliteTo;
@end

@implementation SqliteCrypter

– (void) dealloc
{
    [cstrDestDataBase release]; cstrDestDataBase = nil;
    [cstrSourceDataBase release]; cstrSourceDataBase = nil;
    [super dealloc];
}

-(BOOL)encryptDatabase: (NSString*)acstrPassword cipher: (NSString*)acstrCipher iteration:(NSString*)acstrIteration {
    NSString* docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];   
   
    [cstrDestDataBase release], cstrDestDataBase = nil;
    cstrDestDataBase = [[NSString stringWithFormat:@”%@/crypt.sqlite”, docPath] copy];
    BOOL bSuccess = YES;
    sqlite3* psqlite3Crypted = NULL;
       
    if(sqlite3_open_v2([cstrDestDataBase UTF8String], &psqlite3Crypted, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL ) != SQLITE_OK) {
        fprintf(stderr, “encryptDatabase error:%s\n”, sqlite3_errmsg(psqlite3Crypted));
        bSuccess = NO;
        return bSuccess;
    }
    // submit the password
    const char *pzcharKey = [acstrPassword UTF8String];
    int iStatus = -1;
    iStatus = sqlite3_key(psqlite3Crypted, pzcharKey, strlen(pzcharKey));
   if(acstrCipher) {
        iStatus = sqlite3_exec(psqlite3Crypted, (const char*)[[NSString stringWithFormat:@”PRAGMA cipher=’%@’;”, acstrCipher] UTF8String], NULL, NULL, NULL);
    }
   
    if(acstrIteration) {
        iStatus =  sqlite3_exec(psqlite3Crypted, (const char*)[[NSString stringWithFormat:@”PRAGMA kdf_iter=’%@’;”, acstrIteration] UTF8String], NULL, NULL, NULL);
    }
   
    [self copyDataTo: psqlite3Crypted];
   

   
    return bSuccess;
}
-(sqlite3*)decryptDatabase: (NSString*)acstrPassword cipher: (NSString*)acstrCipher iteration:(NSString*)acstrIteration {

    int iStatus = -1;   
    sqlite3* psSqlite3 = NULL;
    iStatus = sqlite3_open_v2([cstrDestDataBase UTF8String], &psSqlite3, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL );
    if (iStatus != SQLITE_OK) {
        fprintf(stderr, “decryptDatabase can’t open database!”);
        return psSqlite3;
    }
   
    const char *pzcharKey = [acstrPassword UTF8String];
    iStatus = sqlite3_key(psSqlite3, pzcharKey, strlen(pzcharKey));
    if (iStatus != SQLITE_OK) {
        fprintf(stderr, “database should be opened firstly.\n”);
        return psSqlite3;
    }
    if(acstrCipher) {
        iStatus = sqlite3_exec(psSqlite3, (const char*)[[NSString stringWithFormat:@”PRAGMA cipher=’%@’;”, acstrCipher] UTF8String], NULL, NULL, NULL);
    }
   
    if(acstrIteration) {
        iStatus =  sqlite3_exec(psSqlite3, (const char*)[[NSString stringWithFormat:@”PRAGMA kdf_iter=’%@’;”, acstrIteration] UTF8String], NULL, NULL, NULL);
    }

    //test
    const char* pcharGetRestaurantSql = “select * from restaurant limit 0,2;”;
    sqlite3_stmt* pstmt = NULL;
    int iStatusCode = sqlite3_prepare(psSqlite3, pcharGetRestaurantSql, -1, &pstmt, NULL);
    if (iStatusCode == SQLITE_OK) {
        iStatusCode = sqlite3_step(pstmt);
        while (iStatusCode == SQLITE_ROW) {
            int iId = sqlite3_column_int(pstmt, 0);
            printf(“id is %d\n”, iId);
            iStatusCode = sqlite3_step(pstmt);
        }
    }
    return psSqlite3;
}

-(BOOL)changePasswordFrom: (NSString*)acstrOlderPassword: toNewPassword: (NSString*)acstrNewPassword {
    BOOL bSuccess = YES;
    int iStatus = -1;   
    sqlite3* psSqlite3 = NULL;
    iStatus = sqlite3_open_v2([cstrDestDataBase UTF8String], &psSqlite3, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL );
    if (iStatus != SQLITE_OK) {
        fprintf(stderr, “decryptDatabase can’t open database!”);
        bSuccess = NO;
    }
   
    const char *pzcharKey = [acstrOlderPassword UTF8String];
    iStatus = sqlite3_key(psSqlite3, pzcharKey, strlen(pzcharKey));
    if (iStatus != SQLITE_OK) {
        fprintf(stderr, “old password is error.\n”);
        bSuccess = NO;
    }
    const char* pzcharNewPassworld = [acstrNewPassword UTF8String];
    iStatus = sqlite3_rekey(psSqlite3, pzcharNewPassworld, strlen(pzcharNewPassworld));
    if (iStatus != SQLITE_OK) {
        fprintf(stderr, “change to new password error.\n”);
        bSuccess = NO;
    }
    sqlite3_close(psSqlite3);
    return bSuccess;
}
-(BOOL)copyDataTo: (sqlite3*)apSqliteTo {
    BOOL bSuccess = YES;
    NSString* cstrSqlDump = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@”c” ofType:@”dump”] encoding:NSUTF8StringEncoding error:nil];
    if (cstrSqlDump != nil) {
        char* pzDumpSql = (char*)[cstrSqlDump UTF8String];
        char* pcError = NULL;
        int iStatus = sqlite3_exec(apSqliteTo, pzDumpSql, NULL, NULL, &pcError);
        if (iStatus != SQLITE_OK) {
            fprintf(stderr, “error copyDataFrom %s”, sqlite3_errmsg(apSqliteTo));
            bSuccess = NO;
        }else {
            NSLog(@”encrypt database successfully!”);
        }

        sqlite3_close(apSqliteTo);
       
    }
    return bSuccess;
}

@end
here is the source code: before your run the project, you must do download the openssl and the sqlite cipher source

https://skydrive.live.com/?cid=0fd1e8e318234b14&sc=documents&uc=1&id=FD1E8E318234B14%21251#

 

Posted in Uncategorized | Leave a comment

md5 create a string md5

+(NSString*)md5String: (NSString*)acstrSouceString {
    const char* cpStrSrc = [acstrSouceString UTF8String];
    unsigned char pucMd5Buffer[CC_MD5_DIGEST_LENGTH];
    CC_MD5(cpStrSrc, strlen(cpStrSrc), pucMd5Buffer);
    NSMutableString* cmuttrMd5 = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [cmuttrMd5 appendFormat:@”%02x”, pucMd5Buffer[i]];
    }
    return cmuttrMd5;
}

Posted in iphone | Leave a comment

memory warning

all the view initiating process should be created in the init or the loadview or the viewWillappear or the viewDidLoad function, or else the when the memorying waring occours, the system will release all the views relating to the controls and when you come back the system will recreate the views release by the system, so you can recreate your views in the viewDidload or loadView or viewWillAppear.

Posted in Uncategorized | Leave a comment

iphone request url encode

//using the following statement can escape the chinsese characters in the url address string.

    NSString* escapedUrlString =[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

 

Posted in iphone | Leave a comment

dynamic bar iphone implementation.

I have implented an dynamic iphone bar view.

(1)the bars will increase one by one to the orgin specified value.

(2)when you clicke the bar, the “+1” and the description will popout and place on to the top of the bar view.

(3)you can also click the lable button to increase the bar value.

(4)when the bar value increased up to a specified value the bar color will change to red.

(5)here the pictures.

 

Posted in Uncategorized | Leave a comment

Getting google map data using objective c and drawing it on the map

(1)you can get the google map route informaiton from the google map api but this api set an bottle effect that limit up to 2,500 times perday, but if you are using iphone or ipad device, i think 2,500 time one day for you viewing the google information is enough.

(2)here’s some effect that I have implemented.

 

(3)you can reference the octomapkit in the git hub

(4)you can also reference my api because the octomapkit has some error and the releationship between class is complicated.

//
//  WgGoogleMapModel.h
//  WidgetApp
//
//  Created by JoeMhamMertef on 5/17/11.
//  Copyright 2011 http://www.cqtimtes.com. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface WgMapCorindate : NSObject
{
    CLLocationCoordinate2D coordinate;
    MKMapPoint mapPoint;
}
@property(nonatomic, assign) CLLocationCoordinate2D coordinate;
@property(nonatomic, assign, getter=getMapPoint) MKMapPoint mapPoint;

+(NSString*)coordinateToString: (CLLocationCoordinate2D)aLocationCoordiante2d;
+(CLLocationCoordinate2D)coorindateStringToCoordinate2d: (NSString*)astrCoordiante2d;
@end

@class WgGoogleMapModel;
@protocol WgGoogleMapProtocol
-(void)didRequestFinished: (WgGoogleMapModel*)accGoogleModel;
@end

@class SBJsonParser;
@interface WgGoogleMapModel : NSObject{
   
@protected
    WgMapCorindate* from;
    WgMapCorindate* to;
    WgMapCorindate* topLeft;
    WgMapCorindate* bottomRight;
    //just for one leg, for support all the leg this should be an array to store all the legs information
    NSString* cstrStartAddress;
    NSString* cstrEndAddress;
    NSString* cstrAllDistance;
    NSString* cstrAllDuration;
    NSString* cstrStartLocation;
    NSString* cstrEndLocation;
@private
    NSString*      cstrMapServerAddress;
    NSString*      cstrServiceType;
    NSMutableDictionary* cmutdicRequestHeaders;
    NSMutableData* cmutdataReceived;
    NSMutableString* cmutstrRequestGetURL;

   
    NSArray* carrRoutes;
   
    NSURLConnection* curlconnJsonConnection;
   
    SBJsonParser*  cjsonParser;
   
    BOOL isErrorOccored;
    NSDictionary* cdicJsonRoot;
@public
    id<WgGoogleMapProtocol> delegator;
   
}
@property(nonatomic, assign) id<WgGoogleMapProtocol> delegator;
@property(nonatomic, retain) WgMapCorindate* from, *to, *topLeft, *bottomRight;
@property(nonatomic, copy) NSString* mapServerAddress, *cmutstrRequestGetURL, *cstrServiceType;
@property(nonatomic, copy) NSString* cstrStartAddress,* cstrEndAddress,*cstrStartLocation,*cstrEndLocation,  *cstrAllDistance, *cstrAllDuration;
/*!
 @method initWithStart: endLocation:andWayPoints
 @abstract initiate the google map model

 @param astrStartLocation the start location
 @param astrEndLocation the end location
 @param astrWayPoints the middle waypoint the route must contains
 @discussion the start and the end location must be an cooridate string, and the waypint should be separeate by the | separator.
 */
-(id)initWithStart: (NSString*)astrStartLocation endLocation: (NSString*)astrEndLocation andWayPoints: (NSString*)astrWayPoints;
/*!
 @method changeLocationFrom: toLocation:wayPoints
 @abstract changeing the from location and the destination
 
 @param astrFromLocation the start location
 @param astrToLocation the end location
 @param astrWayPoints the middle waypoint the route must contains
 @discussion the start and the end location must be an cooridate string, and the waypint should be separeate by the | separator.
 */
-(void)changeLocationFrom: (NSString*)astrFromLocation toLocation: (NSString*)astrToLocation wayPoints: (NSString*)asWayPoints;
/*!
 @method setHttpGetURLParameter: value:
 @abstract reset the http get request url’s request parameter, the parameter should be the follow’s or else do nothing.
      origin, destination, mode, waypoints, alternatives, avoid, units, region, language, sensor
 @param acstrParemter the get url’s key
 @param acstrValue the get url’s value
 */
-(void)setHttpGetURLParameter: (NSString*)acstrParameter value: (NSString*)acstrValue;
/*!
 @method sendRequest
 @abstract when you have reset the http get requeset url ,  you should send the request explicitly, or else you can’t update the data
 
 */
-(void)sendRequest;
/*!
 @method getRoutesNumber
 @abstract get how many  route the returned json result
 @result the number the routes
 */
-(CFIndex)getRoutesNumber;
/*!
 @method getRouteStepsDescription:
 @abstract get steps description corresponding to the specific route numnber index
 @param aiRoute the route array index number
 @result an array contains all the steps information of this route
 @discussion the array element is an NSDictionary the keys are: description, duration, distance, type
 */
-(NSMutableArray*)getRouteStepsDescription:(CFIndex)aiRoute;
/*!
 @method getRouteMappointsSummary:
 @abstract get steps all the map points  summary corresponding to the specific route numnber index
 @para aiRoute the route array index number
 @result an array contains all the steps map point information of this route
 @discussion the array element is a WgMapCoorindate class type
 */
-(NSMutableArray*)getRouteMappointsSummary:(CFIndex)aiRoute;
/*!
 @method getRouteStepsPolylineMapoints:
 @abstract get steps  polyline mappint  corresponding to the specific route numnber index
 @param aiRoute the route array index number
 @result an array contains all the steps point information of this route
 @discussion the array element is is a WgMapCoorindate class type
 */
-(NSMutableArray*)getRouteStepsPolylineMapoints:(CFIndex)aiRoute;

@end
(5)for detail information you can email me.

Posted in iphone | Leave a comment

opengl bounding-box

bounding-box: is  a rectangle area which your object inside in 2d; or an cubic volume where your object in side. so if you want to see if the running object runs out of the boundaries you should test if the coordinates which your object are ruing is withing the x, y limit of the the rect in 2d and x, y, z boundary limit in 3d area.

here’s the code segments from : http://www.morrowland.com/apron/article/gl/boundingbox/index.php

bounding box: struct tBoundingBox{
tVector3 max;
tVector3 min;
};
tBoundingBox boxArray[1];
boxArray[1].min.x = 2;
boxArray[1].max.x = 10;
boxArray[1].min.z = -10;
boxArray[1].max.z = -2;
if(pos.x < boxArray[1].max.x &&
pos.x > boxArray[1].min.z&&
pos.z < boxyArray[1].max.z &&
pos.z > boxArray[1].min.z) {
}

Posted in iphone | Leave a comment

code block set up opengl environment

referenced from http://www.levelbylevel.com/tutorials/opengl-c-and-glut-using-codeblocks-and-mingw-updated/

(1)first in the code blocks with minigw package.

(2)download the glut.zip

(3)install the glut.dll into your system folder system32, adding glut.h into the include folder of the minigw and add the libglut32.a into the lib folder of the minigw.

(4)adding opengl32 glu32 glut32 into the liker liberary in your project settings under the codeblocks.

(5)all works fine

Posted in Uncategorized | Leave a comment

core-plot useful

Pay attention the the definitions of the chart:

here’s the demo project which uses core-plot to draw the chart.

here’s the code segments:

the x, y axis’s scale is different.

the x axis which is the data axis: the staring coordinate is from the reference point:

e.g.

for ( NSUInteger i = 0; i < [dataSoureData count]; i++ ) {
NetTrafficDataObj*  obj = [dataSoureData objectAtIndex:i];
NSTimeInterval xValue = [[obj datelog] timeIntervalSince1970] – xOffset; //paying attention to the xOffset.
id xRelative = [NSDecimalNumber numberWithDouble: xValue]; //axis’s relative value
id yRelative = [NSDecimalNumber numberWithFloat:[obj datavalue] / 100.0f]; //axis’s relative value

NSDictionary* dataItem = [NSDictionary dictionaryWithObjectsAndKeys: xRelative,@”x”, yRelative, @”y”, nil];
[plotData addObject: dataItem];
}

(2) add annotation into the plot-chart:

you should calculate the realized value based on the relative value:

e.g

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTimeFormatter *timeFormatter = [[[CPTimeFormatter alloc] initWithDateFormatter:dateFormatter] autorelease];
timeFormatter.referenceDate = [NSDate dateWithTimeIntervalSince1970: xOffset]; //you must set this value, or else the wrong value will be calculated.
NSString* description = [NSString stringWithFormat:@”%@\n%@”, yString, [timeFormatter stringFromNumber:x]];

(3)

CPXYPlotSpace: is the visible area in the view which is showed on the plot-chart, but you can drag it.

eg.

NSTimeInterval xLow = – CONST_ONE_DAY * 1;
plotSpace.xRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(xLow) length:CPDecimalFromFloat(CONST_ONE_DAY*9)];
plotSpace.yRange = [CPPlotRange plotRangeWithLocation:CPDecimalFromFloat(-0.5f) length:CPDecimalFromFloat(2.0f)];
plotSpace.allowsUserInteraction = YES;
plotSpace.delegate = self;

the above code setting and move the origin of the coordinate left and right.

CPXYAxisSet *axisSet = (CPXYAxisSet *)graph.axisSet;
CPXYAxis *x = axisSet.xAxis;
x.majorIntervalLength = CPDecimalFromFloat(CONST_ONE_DAY); // it’s important the CONST_ONE_DAY is the interval which should be the same when you generating the data

x.orthogonalCoordinateDecimal = CPDecimalFromFloat(0.0f); //the zero point corresponding to the y axis.

CPXYAxis *y = axisSet.yAxis;
y.majorIntervalLength = CPDecimalFromString(@”.2f”);
y.minorTicksPerInterval = 2;
y.orthogonalCoordinateDecimal = CPDecimalFromDouble(0); //the x corresponding value according to the origin, you can what value, the changes only effect the coordinate origin.

//you can format the x axis or y axis the label value according the the axis’s relative value
XLableFormmater* numberFormatter = [[XLableFormmater shareXLableFormatter] initWithScaleFactor:100.0f];
y.labelFormatter = numberFormatter;
[numberFormatter release];

 

 

Posted in iphone | Leave a comment

Pay attention to the small iPHone configurations

Some time if you ignore the other linker flags:
for example: -load_all you can’t load the class extensions if you use the static library. -ObjC

Posted in Uncategorized | Tagged | Leave a comment