RSA encryption and decryption via iOS

Source: Internet
Author: User
Tags openssl x509

In encryption and decryption, we need to know what is the basic principle of OPENSSL;RSA encryption algorithm, and how to generate the Der and P12 files that we need in the end through OpenSSL.

Nonsense not much to say, direct writing steps:

The first step: OpenSSL to generate public and private key certificates, and finally a public key certificate and a private key certificate are required

This is the certificate shown under the Mac Ox System, and if we open it with a text editor, we will find that it is a string of strings that----begin RSA and End with----end RSA.

Step two: We need to write our encryption and secret method in our code, the encrypted string is encrypted by the public key, and the encrypted string can be decrypted by the private key.

1. Obtain a certificate from the command line via the OpenSSL command

//generate a private key with a length of 1024: Private_key.pem (file name can be customized)OpenSSL Genrsa- outPrivate_key.pem1024x768//Create the required certificate using the private key file: RSACERTREQ.CSR (file name is customizable)OpenSSL req-New-key Private_key.pem- outRSACERTREQ.CSR//Create a certificate with X509: RSACERT.CRT (file name is customizable)OpenSSL x509-req-days3650-inchRsacertreq.csr-signkey Private_key.pem- outRSACERT.CRT//generate the. Der formatted public key: Public_key.der (file name is customizable)OpenSSL X509-outform der-inchRSACERT.CRT- outPublic_key.der//the. p12 file required to generate the decryption: PRIVATE_KEY.P12 (file name can be customized)OpenSSL Pkcs12-export- outPrivate_key.p12-inkey Private_key.pem-inchRsacert.crt

Some of your information may be needed in the command line to generate the public and private keys

Country Name (2 letter code) [AU]:CN//Country code

State or province name (full name) [Some-state]:china//region code

Locality Name (eg, city) []:wuhan//Local code

Organization name (eg, company) [Internet widgits Pty ltd]:airway//Corporate name

Organizational unit Name (eg, section) []:airway//Department

Common name (eg, YOUR name) []:airway//Name

email address []://Email

Note: When generating a key pair, you need to fill in the extraction password of the private key, remember that it is necessary to decrypt it.

2. We need to refine our code to enable RSA encryption and decryption

At the command line, we can finally get the public and private key files we need.

StaticSeckeyref _public_key =Nil; //get the Seckeyref pointer to the public key from the public key certificate file: @ "Public_key" oftype:@ "Der "NSString *publickeypath = [paramsdict stringvalueforkey:@"PublicKey"DefaultValue:@""]; Publickeypath=[self getpathwithuzschemeurl:publickeypath]; if(![[Nsfilemanager Defaultmanager] Fileexistsatpath:publickeypath]) {[Self sendresulteventwithcallbackid:rsacbid datadict:@{@"Status": [NSNumber Numberwithbool:false]} errdict:@{@"Code":@(-1)} Dodelete:no]; return; } NSData*certificatedata =[[NSData Alloc]initwithcontentsoffile:publickeypath]; Seccertificateref mycertificate=Seccertificatecreatewithdata (Kcfallocatordefault, (cfdataref) certificatedata); Secpolicyref MyPolicy=SecPolicyCreateBasicX509 ();        Sectrustref Mytrust; Osstatus Status= Sectrustcreatewithcertificates (mycertificate,mypolicy,&mytrust);        Sectrustresulttype Trustresult; if(Status = =NOERR) {Status= Sectrustevaluate (Mytrust, &Trustresult); } _public_key=Sectrustcopypublickey (Mytrust);        Cfrelease (mycertificate);        Cfrelease (MyPolicy);        Cfrelease (Mytrust); Seckeyref Key=_public_key; size_t cipherbuffersize=seckeygetblocksize (key); uint8_t*cipherbuffer = malloc (Cipherbuffersize *sizeof(uint8_t)); NSData*stringbytes =[instring datausingencoding:nsutf8stringencoding]; size_t blockSize= Cipherbuffersize- One; size_t Blockcount= (size_t) ceil ([Stringbytes length]/(Double) blockSize); Nsmutabledata*encrypteddata =[[Nsmutabledata alloc] init]; NSString*outstring =[[NSString alloc] init];  for(intI=0; i<blockcount; i++) {            intbuffersize = MIN (blocksize,[stringbytes length]-I *blockSize); NSData*buffer = [Stringbytes subdatawithrange:nsmakerange (i *blockSize, buffersize)]; Osstatus 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]; } Else{outstring=@""; }        }        if(Cipherbuffer) {free (cipherbuffer); } outstring=[EncryptedData base64encoding];}returnoutstring;
NSString *password = [paramsdict stringvalueforkey:@"Password"DefaultValue:@""]; NSString*instring = [Paramsdict stringvalueforkey:@"Data"DefaultValue:@""]; NSString*value =@""; if(Instring.length <=0) {        //err:1        returnvalue; } Else {        //get the Seckeyref pointer to the public key from the private key certificate file: @ "Private_key" oftype:@ "Pem"NSString *privatekeypath = [paramsdict stringvalueforkey:@"Privatekey"DefaultValue:@""]; Privatekeypath=[self getpathwithuzschemeurl:privatekeypath]; if(![[Nsfilemanager Defaultmanager] Fileexistsatpath:privatekeypath]) {            returnvalue; } NSData*p12data =[[NSData Alloc]initwithcontentsoffile:privatekeypath]; Seckeyref Privatekeyref=NULL; Nsmutabledictionary*options =[[Nsmutabledictionary alloc] init]; [Options Setobject:password Forkey: (__bridgeID) Ksecimportexportpassphrase]; Cfarrayref Items= Cfarraycreate (NULL,0,0, NULL); Osstatus Securityerror= Secpkcs12import ((__bridge cfdataref) P12data, (__bridge cfdictionaryref) options, &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; }        } Else {            returnvalue;                } cfrelease (items); NSData*cipherdata =[NSData datawithbase64encodedstring:instring]; //nsdata* decryptdata = [self rsadecryptdata:data];size_t Cipherlen =[CipherData length]; void*cipher =malloc (Cipherlen);        [CipherData Getbytes:cipher Length:cipherlen]; size_t Plainlen= Seckeygetblocksize (privatekeyref)- A; void*plain =malloc (Plainlen); Osstatus Status= Seckeydecrypt (Privatekeyref, kSecPaddingPKCS1, cipher, Cipherlen, plain, &Plainlen); if(Status! =NOERR) {            returnvalue; } NSData*decrypteddata = [[NSData alloc] Initwithbytes: (Const void*) plain Length:plainlen]; Value=[[NSString alloc] Initwithdata:decrypteddata encoding:nsutf8stringencoding]; Nsmutablestring*outstring =[[Nsmutablestring alloc] init]; //If encryption is not decrypted directly, outstring will be nil        if(!value && decrypteddata && decrypteddata.length >0) {Byte*datas = (byte*) [Decrypteddata bytes]; Outstring= [nsmutablestring StringWithCapacity:decryptedData.length *2];  for(inti =0; i < decrypteddata.length; i++) {[outstring AppendFormat:@"%02x", Datas[i]]; } Value=[outstring copy]; }        returnvalue; }

RSA encryption and decryption via iOS

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.