Svudid realization of device unique indication

Source: Internet
Author: User

svudidtools:https://github.com/smileevday/svudid//saves the generated udid to the keychain, and the user uninstalls the app and then re-installs the udid without changing./* Usage 1: (How to use online) Create a new Keychainaccessgroups.plist file in the project directory, the topmost node in the structure of the file must be an array named "Keychain-access-groups", And each item in the array is a nsstring that describes the grouping. YourAppID.com.yourCompany.whatever is the name of the public area you want, except the whatever field can be arbitrarily set, the others must be truthfully filled out. The path of this file is to be configured in Project->build Setting->code Signing entitlements, otherwise the public area is invalid, after the configuration, must use your official certificate signature compiles only then can pass, Otherwise Xcode will frame the box to tell you that code signing has a problem. So, Apple restricts you to share keychain data with your company's products, and other companies won't be able to access your company's products keychain. If copy: Copy the keychainaccessgroups.plist below the UID folder to the same class as the project directory, and drag to the Xcode Project window to modify the response yourAppID.com.yourCompany.whatever append build phases->compile sources below the svudidtools.m file configuration information string " -fno-objc-arc "Modify build Setting->code Signing->code Signing entitlements Property for keychainaccessgroups.plist*//* usage 2: The actual operation of the project, capabilities, Keychain sharing, on, will pop up the prompt box request fetching list of teams from the Developer Portal ..., select the Development Account, confirm.    To generate the entitlements file, the network is not good when you can manually add keychainaccessgroups.plist usage similar to usage 1. The auto-generated entitlements has the KEychain Access Groups is complementary and does not need to be changed, the Keychain Access Groups group appears in the $ (appidentifierprefix) Com.moule.utils-ios ($ ( Appidentifierprefix), Build phases->compile sources The following SVUDIDTOOLS.M file configuration information string "-fno-objc-arc"//Get the Development Account Appi d+ (NSString *) Bundleseedid {nsdictionary *query = [Nsdictionary dictionarywithobjectsandkeys:ksecclassgenericpasswor    D, ksecclass,@ "Bundleseedid", ksecattraccount,@ "", Ksecattrservice, (ID) kcfbooleantrue, ksecreturnattributes,nil];    Cfdictionaryref result = nil;    Osstatus status = Secitemcopymatching ((cfdictionaryref) query, (CFTYPEREF *) &result);            if (status = = Errsecitemnotfound) status = Secitemadd ((cfdictionaryref) query, (CFTYPEREF *) &result);        if (Status! = errsecsuccess) return nil;        NSString *accessgroup = [(__bridge nsdictionary *) result Objectforkey:ksecattraccessgroup];        Nsarray *components = [Accessgroup componentsseparatedbystring:@ ".]; NSString *bundleseedid = [[Components objecteNumerator] nextobject];    Cfrelease (result); return bundleseedid;} Kkeychainudidaccessgroup is the bundle id*/of the application

. h file #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface svudidtools:nsobject/* * @brief Obtain Unique Device Identity */+ (nsstring*) UDID; @end

. m file////svudidtools.m//svudid////Created by maple on 8/18/13.//Copyright (c) Maple. All rights reserved.//#import "SvUDIDTools.h" #import <Security/Security.h> #include <sys/socket.h># Include <sys/sysctl.h> #include <net/if.h> #include <net/if_dl.h>//replace the identity with your Company ' s domainstatic const char kkeychainudiditemidentifier[] = "UUID"; static NSString * Kkeychainudidaccessgroup = @ "C Om.moule.utils-ios "; @implementation svudidtools+ (NSString *) Bundleseedid {nsdictionary *query = [Nsdictionary diction Arywithobjectsandkeys:ksecclassgenericpassword, Ksecclass, @ "Bundlese EdID ", Ksecattraccount, @" ", Ksecattrservice, (ID) kcfbooleantrue, ksec    Returnattributes, nil];    Cfdictionaryref result = nil;    Osstatus status = Secitemcopymatching ((cfdictionaryref) query, (CFTYPEREF *) &result); if (status= = Errsecitemnotfound) status = Secitemadd ((cfdictionaryref) query, (CFTYPEREF *) &result);    if (Status! = errsecsuccess) return nil;    NSString *accessgroup = [(__bridge nsdictionary *) result Objectforkey:ksecattraccessgroup];    Nsarray *components = [Accessgroup componentsseparatedbystring:@ ".];    NSString *bundleseedid = [[Components objectenumerator] nextobject];    Cfrelease (result); return bundleseedid;}    + (nsstring*) udid{nsstring *udid = [Svudidtools getudidfromkeychain];        if (!udid) {nsstring *sysversion = [Uidevice currentdevice].systemversion;            CGFloat Version = [Sysversion Floatvalue];        if (version >= 7.0) {udid = [svudidtools _udid_ios7];        } else if (version >= 2.0) {udid = [svudidtools _UDID_IOS6];    } [Svudidtools Settudidtokeychain:udid]; } return Udid;} /* * IOS 6.0 * Use WiFi ' s MAC address */+ (nsstring*) _udid_ios6{return [Svudidtools geTmacaddress];} /* * iOS 7.0 * Starting from iOS 7, the system always returns the value 02:00:00:00:00:00 * If you ask for the MAC addr ESS on any device. * Use Identifierforvendor + keyChain * Make sure UDID consistency atfer app Delete and reinstall */+ (nsstring*) _udid_ios7 {return [[Uidevice Currentdevice].identifierforvendor uuidstring];} #pragma mark-#pragma mark Helper Method for Get Mac address//from Http://stackoverflow.com/questions/677530/how-can-i-p    Rogrammatically-get-the-mac-address-of-an-iphone+ (NSString *) getmacaddress{int mgmtinfobase[6];    char *msgbuffer = NULL;    size_t length;    unsigned char macaddress[6];    struct IF_MSGHDR *interfacemsgstruct;    struct SOCKADDR_DL *socketstruct;        NSString *errorflag = nil;        Setup The Management Information Base (MIB) mgmtinfobase[0] = ctl_net;       Request network subsystem mgmtinfobase[1] = Af_route;  Routing Table Info  MGMTINFOBASE[2] = 0;        MGMTINFOBASE[3] = Af_link;  Request link layer information mgmtinfobase[4] = net_rt_iflist; Request all configured interfaces//with all configured interfaces requested, get handle index if ((Mgmtinfo    BASE[5] = If_nametoindex ("En0")) = = 0) Errorflag = @ "If_nametoindex failure"; else {//Get the size of the data available (store in Len) if (Sysctl (Mgmtinfobase, 6, NULL, &length        , NULL, 0) < 0) Errorflag = @ "Sysctl mgmtinfobase failure";                else {//Alloc memory based on above call if ((Msgbuffer = malloc (length)) = = NULL)            Errorflag = @ "Buffer allocation failure"; else {//Get system information, store in buffer if (Sysctl (mgmtinfobase, 6, MSG            Buffer, &length, NULL, 0) < 0) Errorflag = @ "Sysctl msgbuffer failure"; }}}//Befor going any FUrther ... if (errorflag! = NULL) {NSLog (@ "Error:%@", Errorflag);        if (Msgbuffer) {free (msgbuffer);    } return Errorflag;        }//Map Msgbuffer to Interface message structure interfacemsgstruct = (struct IF_MSGHDR *) Msgbuffer;        Map to LINK-LEVEL socket structure socketstruct = (struct SOCKADDR_DL *) (interfacemsgstruct + 1); Copy link Layer address data in socket structure to an array memcpy (&macaddress, Socketstruct->sdl_data + Soc        Ketstruct->sdl_nlen, 6); Read from char array to a string object, into traditional MAC address format nsstring *macaddressstring = [Nsstrin G stringwithformat:@ "%02x:%02x:%02x:%02x:%02x:%02x", Macaddress[0], macaddress[1], Macadd    RESS[2], macaddress[3], macaddress[4], macaddress[5]];        NSLog (@ "Mac Address:%@", macaddressstring); Release the buffer Memory free (msgbuffer); return macaddressstring;} #pragma mark-#pragma mark Helper Method for Make Identityforvendor consistency+ (nsstring*) getudidfromkeychain{Nsmuta    Bledictionary *dictforquery = [[Nsmutabledictionary alloc] init];        [Dictforquery SetValue: (ID) Ksecclassgenericpassword Forkey: (ID) ksecclass];                    Set Attr Description for query [Dictforquery setvalue:[nsstring Stringwithutf8string:kkeychainudiditemidentifier]        Forkey:ksecattrdescription];                                            Set Attr Identity for query NSData *keychainitemid = [NSData datawithbytes:kkeychainudiditemidentifier    Length:strlen (Kkeychainudiditemidentifier)];        [Dictforquery setobject:keychainitemid Forkey: (ID) ksecattrgeneric]; The Keychain Access group attribute determines if this item can be shared//amongst multiple apps whose code signin    g entitlements contain the same Keychain Access group. NSString *accessgroup =[nsstring stringwithformat:@ "%@.%@", [SvUDidtools Bundleseedid],kkeychainudidaccessgroup]; if (accessgroup! = nil) {#if target_iphone_simulator//Ignore The Access group if running on the IPHONE Simulat        Or. Apps that is built for the simulator aren ' t signed, so there ' s no Keychain Access group//For the SI Mulator to check.        This means, all apps can see all keychain items if run//on the simulator.  If A Secitem contains an Access group attribute, Secitemadd and secitemupdate on the//simulator would return-25243 (Errsecnoaccessforitem). #else [Dictforquery setobject:accessgroup forkey: (ID) ksecattraccessgroup]; #e    NDIF} [Dictforquery SetValue: (ID) kcfbooleantrue Forkey: (ID) ksecmatchcaseinsensitive];    [Dictforquery SetValue: (ID) ksecmatchlimitone Forkey: (ID) ksecmatchlimit];        [Dictforquery SetValue: (ID) kcfbooleantrue Forkey: (ID) ksecreturndata];    Osstatus queryerr = NOERR;    NSData *udidvalue = nil;     NSString *udid = nil;        Queryerr = secitemcopymatching ((cfdictionaryref) Dictforquery, (cftyperef*) &udidvalue);    Nsmutabledictionary *dict = nil;    [Dictforquery SetValue: (ID) kcfbooleantrue Forkey: (ID) ksecreturnattributes];        Queryerr = secitemcopymatching ((cfdictionaryref) Dictforquery, (cftyperef*) &dict); if (Queryerr = = Errsecitemnotfound) {NSLog (@ "KeyChain Item:%@ not Found!!!", [NSString STRINGWITHUTF8STRING:KKEYC    Hainudiditemidentifier]); } else if (queryerr! = errsecsuccess) {NSLog (@ "KeyChain Item query Error!!!    Error code:%d ", (int) queryerr);                } if (Queryerr = = errsecsuccess) {NSLog (@ "KeyChain Item:%@", udidvalue);            if (udidvalue) {udid = [nsstring stringWithUTF8String:udidValue.bytes];        [Udidvalue release];    } [Dict release];    } [Dictforquery release]; return udid;} + (BOOL) Settudidtokeychain: (nsstring*) udid{nsmutabledictionary *dictforadd = [[Nsmutabledictionary alloc]INIT];    [Dictforadd SetValue: (ID) Ksecclassgenericpassword Forkey: (ID) ksecclass];        [Dictforadd setvalue:[nsstring Stringwithutf8string:kkeychainudiditemidentifier] forKey:kSecAttrDescription];        [Dictforadd setvalue:@ "UUID" Forkey: (ID) ksecattrgeneric];    Default attributes for keychain item.    [Dictforadd setobject:@ "" Forkey: (ID) ksecattraccount];            [Dictforadd setobject:@ "" Forkey: (ID) Ksecattrlabel]; The Keychain Access group attribute determines if this item can be shared//amongst multiple apps whose code signin    g entitlements contain the same Keychain Access group.    NSString *accessgroup = [NSString stringwithformat:@ "%@.%@", [Svudidtools Bundleseedid],kkeychainudidaccessgroup]; if (accessgroup! = nil) {#if target_iphone_simulator//Ignore The Access group if running on the IPHONE Simulat        Or. Apps that is built for the simulator aren ' t signed, so there ' s no Keychain Access group//For the SI Mulator to Check.        This means, all apps can see all keychain items if run//on the simulator.  If A Secitem contains an Access group attribute, Secitemadd and secitemupdate on the//simulator would return-25243 (Errsecnoaccessforitem). #else [Dictforadd setobject:accessgroup forkey: (ID) ksecattraccessgroup]; #end    if} const char *udidstr = [Udid utf8string];    NSData *keychainitemvalue = [NSData datawithbytes:udidstr Length:strlen (UDIDSTR)];        [Dictforadd setvalue:keychainitemvalue Forkey: (ID) ksecvaluedata];    Osstatus writeerr = NOERR; if ([Svudidtools Getudidfromkeychain]) {//There is item in keychain [Svudidtools Updateudidinkeychain:udid        ];        [Dictforadd release];    return YES;        } else {//Add item to Keychain Writeerr = Secitemadd ((cfdictionaryref) Dictforadd, NULL); if (writeerr! = errsecsuccess) {NSLog (@ "ADD KeyChain Item Error!!!         Error code:%ld ", Writeerr);               [Dictforadd release];        return NO;            } else {NSLog (@ "ADD KeyChain Item Success!!!");            [Dictforadd release];        return YES;    }} [Dictforadd release]; return NO;}        + (BOOL) removeudidfromkeychain{nsmutabledictionary *dicttodelete = [[Nsmutabledictionary alloc] init];        [Dicttodelete SetValue: (ID) Ksecclassgenericpassword Forkey: (ID) ksecclass]; NSData *keychainitemid = [NSData datawithbytes:kkeychainudiditemidentifier Length:strlen (    Kkeychainudiditemidentifier)];        [Dicttodelete setvalue:keychainitemid Forkey: (ID) ksecattrgeneric];    Osstatus deleteerr = NOERR;    Deleteerr = Secitemdelete ((cfdictionaryref) dicttodelete); if (deleteerr! = errsecsuccess) {NSLog (@ "Delete UUID from KeyChain Error!!!        Error code:%ld ", Deleteerr);        [Dicttodelete release];    return NO;        } else {NSLog (@ "DELETE success!!!");}    [Dicttodelete release]; return YES;} + (BOOL) Updateudidinkeychain: (nsstring*) newudid{nsmutabledictionary *dictforquery = [[Nsmutabledictionary alloc] init];       [Dictforquery SetValue: (ID) Ksecclassgenericpassword Forkey: (ID) ksecclass]; NSData *keychainitemid = [NSData datawithbytes:kkeychainudiditemidentifier Leng    Th:strlen (Kkeychainudiditemidentifier)];    [Dictforquery setvalue:keychainitemid Forkey: (ID) ksecattrgeneric];    [Dictforquery SetValue: (ID) kcfbooleantrue Forkey: (ID) ksecmatchcaseinsensitive];    [Dictforquery SetValue: (ID) ksecmatchlimitone Forkey: (ID) ksecmatchlimit];        [Dictforquery SetValue: (ID) kcfbooleantrue Forkey: (ID) ksecreturnattributes];    Nsdictionary *queryresult = nil;    Secitemcopymatching ((Cfdictionaryref) Dictforquery, (cftyperef*) &queryresult);        if (queryresult) {nsmutabledictionary *dictforupdate = [[Nsmutabledictionary alloc] init]; [Dictforupdate setvalue:[nsstring Stringwithutf8string:kkeychainudiditemidenTifier] forkey:ksecattrdescription];                [Dictforupdate setvalue:keychainitemid Forkey: (ID) ksecattrgeneric];        const char *UDIDSTR = [Newudid utf8string];        NSData *keychainitemvalue = [NSData datawithbytes:udidstr Length:strlen (UDIDSTR)];                [Dictforupdate setvalue:keychainitemvalue Forkey: (ID) ksecvaluedata];                Osstatus updateerr = NOERR;        First we need the attributes from the Keychain.        Nsmutabledictionary *updateitem = [Nsmutabledictionary Dictionarywithdictionary:queryresult];                [QueryResult release];        Second we need to add the appropriate search key/values.                Set Ksecclass is Very important [UpdateItem SetObject: (ID) Ksecclassgenericpassword Forkey: (ID) ksecclass];        Updateerr = Secitemupdate ((cfdictionaryref) UpdateItem, (cfdictionaryref) dictforupdate); if (updateerr! = errsecsuccess) {NSLog (@ "Update KeyChain Item Error!!!    Error code:%ld ", Updateerr);                    [Dictforquery release];            [Dictforupdate release];        return NO;            } else {NSLog (@ "Update KeyChain Item Success!!!");            [Dictforquery release];            [Dictforupdate release];        return YES;    }} [Dictforquery release]; return NO;} @end

Svudid realization of device unique indication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.