RSA encryption decryption of common iOS encryption

Source: Internet
Author: User
Tags openssl x509

Objective:

There are many kinds of encryption commonly used in iOS, the first two days in the work encountered RSA encryption, now the generation share out.

RSA Fundamentals

RSA encrypts the data using the "key pair". Before encrypting and decrypting data, you need to be a public key and private key.

    • Public key: Used to encrypt data. Used for public, typically stored in data providers, such as iOS clients.
    • Private key: Used to decrypt data. Must be kept secret, private key leaks can cause security problems
First step: The generation of public and private keys

iOS developers can be generated directly from the Mac terminal, the command is as follows, when generating the public key der file needs to fill in the national area and other basic information, you can also directly ignore the blank. When you generate a private P12 file, you need to fill in the password, this must be filled in and remember that it will be useful later.

Generate a 1024-bit private key
OpenSSL genrsa-out Private_key.pem 1024
Generate a CSR file based on the private key
OpenSSL Req-new-key private_key.pem-out RSACERTREQ.CSR
Generate CRT files based on private key and CSR files
OpenSSL x509-req-days 3650-in rsacertreq.csr-signkey private_key.pem-out rsacert.crt

Generate a public key der file for the iOS side
OpenSSL x509-outform der-in rsacert.crt-out Public_key.der

Export the private key to this P12 file
OpenSSL pkcs12-export-out Private_key.p12-inkey private_key.pem-in rsacert.crt

Step two: Encrypt the relevant code

The public variable public and private keys need to be defined when encrypting encryption

    Seckeyref _publickey;    Seckeyref _privatekey;
Encryption-related code
1 #pragmaMark-Encryption-related2 //To load the public key with a local certificate3- (void) Loadpublickeywithpath: (NSString *) Derfilepath4 {5NSData *derdata =[[NSData alloc] initwithcontentsoffile:derfilepath];6     if(Derdata.length >0)7     {8 [self loadpublickeywithdata:derdata];9     }Ten     Else One     { ANSLog (@"load public key fail with path:%@", Derfilepath); -     } - } the //load Public Key method -- (void) Loadpublickeywithdata: (NSData *) Derdata - { -Seccertificateref mycertificate =Seccertificatecreatewithdata (Kcfallocatordefault, (__bridge cfdataref) derdata); +Secpolicyref MyPolicy =SecPolicyCreateBasicX509 (); - sectrustref Mytrust; +Osstatus status = Sectrustcreatewithcertificates (mycertificate,mypolicy,&mytrust); A Sectrustresulttype Trustresult; at     if(Status = =NOERR) { -Status = Sectrustevaluate (Mytrust, &trustresult); -     } -      -Seckeyref SecurityKey =Sectrustcopypublickey (Mytrust);  Cfrelease (mycertificate);  Cfrelease (MyPolicy); Cfrelease (mytrust); -      in_publickey =SecurityKey; - } to  +  - //Encrypt the text content the-(NSString *) Rsaencrypttext: (NSString *) Text * { $NSData *encrypteddata =[self rsaencryptdata:[text datausingencoding:nsutf8stringencoding]];Panax NotoginsengNSString *base64encryptedstring = [EncryptedData base64encodedstringwithoptions:0]; -     returnbase64encryptedstring; the } +  A  the //segment re-encrypt data +-(NSData *) Rsaencryptdata: (NSData *) Data - { $Seckeyref key =_publickey; $      -size_t cipherbuffersize =seckeygetblocksize (key); -uint8_t *cipherbuffer = malloc (Cipherbuffersize *sizeof(uint8_t)); thesize_t blockSize = cipherbuffersize- One; -size_t Blockcount = (size_t) ceil ([Data length]/(Double) blockSize);WuyiNsmutabledata *encrypteddata =[[Nsmutabledata alloc] init]; the      for(inti =0; i < Blockcount; i++) -     { Wusize_t buffersize = MIN (blocksize,[data length]-I *blockSize); -NSData *buffer = [Data Subdatawithrange:nsmakerange (i *blockSize, buffersize)]; AboutOsstatus status = Seckeyencrypt (Key, KSecPaddingPKCS1, (Constuint8_t *) [Buffer Bytes],[buffer length],cipherbuffer,&cipherbuffersize); $         if(Status = =NOERR) -         { -NSData *encryptedbytes = [[NSData alloc] Initwithbytes: (Const void*) Cipherbuffer length:cipherbuffersize]; - [EncryptedData appenddata:encryptedbytes]; A         } +         Else the         { -             if(cipherbuffer) { $ Free (cipherbuffer); the}returnNil; the         } the          the     } -     if(Cipherbuffer) in     { the Free (cipherbuffer); the          About     } the     returnEncryptedData; the}
Step three: Decrypt the relevant code
#pragmaMark-Decryption related-(void) Loadprivatekeywithpath: (NSString *) p12filepath Password: (NSString *) p12password{NSData*data =[NSData Datawithcontentsoffile:p12filepath]; if(Data.length >0) {[self loadprivatekeywithdata:data password:p12password];} Else{NSLog (@"load private key fail with path:%@", P12filepath);}}//Generate private key- (void) Loadprivatekeywithdata: (NSData *) p12data Password: (NSString *) p12password{seckeyref privatekeyref=NULL; Nsmutabledictionary* Options =[[Nsmutabledictionary alloc] init]; [Options Setobject:p12password Forkey: (__bridgeID) Ksecimportexportpassphrase]; Cfarrayref items = cfarraycreate (NULL,0,0, NULL); Osstatus Securityerror=Secpkcs12import ((__bridge cfdataref) P12data, (__bridge cfdictionaryref) op tions,&items);if(Securityerror = = NoErr && cfarraygetcount (items) >0) {Cfdictionaryref identitydict = cfarraygetvalueatindex (items,0); Secidentityref Identityapp=(secidentityref) cfdictionarygetvalue (Identitydict,        ksecimportitemidentity); Securityerror= Secidentitycopyprivatekey (Identityapp, &privatekeyref);if(Securityerror! =NOERR) {Privatekeyref=NULL; }} _privatekey=Privatekeyref; Cfrelease (items);}//call the following method to decrypt, and finally return a string-(NSString *) Rsadecrypttext: (NSString *) text{NSData*data = [[NSData alloc] initwithbase64encodedstring:text options:0]; NSData*decryptdata =[self rsadecryptdata:data]; NSString*result =[[NSString alloc] Initwithdata:decryptdata encoding:nsutf8stringencoding]; returnresult;}//the method that is decrypted with the private key is called by the method above-(NSData *) Rsadecryptdata: (NSData *) data{seckeyref key=_privatekey; size_t Cipherlen=[data length]; void*cipher =malloc (Cipherlen);    [Data Getbytes:cipher Length:cipherlen]; size_t Plainlen= Seckeygetblocksize (Key)- A; void*plain =malloc (Plainlen); Osstatus Status= Seckeydecrypt (key, kSecPaddingPKCS1, cipher, Cipherlen, plain, &Plainlen); if(Status! =NOERR) {        returnNil; } NSData*decrypteddata = [[NSData alloc] Initwithbytes: (Const void*) plain Length:plainlen]; returnDecrypteddata;}
Fourth step: RSA Encryption and decryption application

Be sure to load the certificate before encrypting live decryption, and then call the encryption method directly on the code

1-(Ibaction) Decryptionbtnclick: (ID) Sender {2     3NSString *path = [[NSBundle mainbundle] Pathforresource:@"Public_key"OfType:@"der"];4 [self loadpublickeywithpath:path];5Path = [[NSBundle mainbundle] Pathforresource:@"Private_key"OfType:@"P12"];6[Self loadprivatekeywithpath:path password:@"bestnet"];7     8NSString *encryptstr =Self.encryptTextFeild.text;9     if(Encryptstr.length >0)Ten     { OneNSString *miwen =[self rsaencrypttext:encryptstr]; ASelf.miWenLabel.text = [NSString stringWithFormat:@"encryption Result:%@", Miwen]; -         if(Miwen.length >0) -         { theSelf.decryptionTextFeild.text =[self Rsadecrypttext:miwen]; -         } -     } -}

RSA encryption decryption of common iOS encryption

Related Article

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.