RSA algorithm and its use in iOS

Source: Internet
Author: User
Tags asymmetric encryption

Because the project needs to transfer the user password, in order to secure the need to use RSA encryption, so learn the next RSA encryption in iOS application. About the history and principles of RSA, the following two articles are very clear: http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html/http Www.ruanyifeng.com/blog/2013/07/rsa_algorithm_part_two.html Simply put, RSA is based on a mathematical puzzle, that is, the decomposition of large numbers: it is easy to multiply two large primes, But it is extremely difficult to factorization the product. As for why it's hard, it's a mathematician's business ... Understanding this will give you a general idea of how RSA works: Asymmetric encryption (1) Party B generates two keys (public and private). The public key is public and can be obtained by anyone, and the private key is confidential. (2) Party A obtains the public key of party B, then uses it to encrypt the information. (3) Party B obtains the encrypted information, decrypts with the private key. It is like a special lock and key, the lock is public, anyone can take this lock to lock his things, only the person with the key can open. So the question is, since the lock is public, can't the shape of the key be rolled out by the structure of the lock? The answer is: No! Because this lock is special, it is particularly difficult to push backwards. (This is not absolute, perhaps one day in the future, the mathematical problem of large number decomposition solved, this algorithm is not safe, see the beginning of the link) I encountered the application scenario is that the client has the server's public key, the client to the user's password encrypted with the public key after uploading to the server, the server can be decrypted with the private key. So the client has to do is to encrypt the content that needs to be encrypted with the public key of the server. There is no direct RSA encryption API on iOS, so it takes a bit of tossing and taking. The code on GitHub is a similar one, mostly three methods (copied from Https://github.com/ideawu/Objective-C-RSA) Note that there is a kSecPaddingPKCS1 in the code that was written by the author, And we need to pass Ksecpaddingnone in the project!!!
+ (NSData *) Strippublickeyheader: (NSData *) d_key{//Skip ASN.1 Public key Headerif(D_key = = nil)return(nil); unsignedLongLen =[D_key length];if(!len)return(nil); unsignedChar*c_key = (unsignedChar*) [D_key bytes];unsignedintIDX =0;if(c_key[idx++]! =0x30)return(nil);if(C_key[idx] >0x80) idx + = C_key[idx]-0x80+1;Elseidx++;//PKCS #1 rsaencryption szoid_rsa_rsaStaticUnsignedCharSeqiod[] ={ 0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x01,0x05,0x00 };if(MEMCMP (&c_key[idx], Seqiod, the))return(nil); IDX+= the;if(c_key[idx++]! =0x03)return(nil);if(C_key[idx] >0x80) idx + = C_key[idx]-0x80+1;Elseidx++;if(c_key[idx++]! =' /')return(nil);//Now make a new NSData from this bufferreturn([NSData Datawithbytes:&c_key[idx] Length:len-idx]);}

+ (Seckeyref) Addpublickey: (NSString *) Key{nsrange Spos= [Key rangeofstring:@"-----BEGIN Public KEY-----"]; Nsrange Epos= [Key rangeofstring:@"-----END Public KEY-----"];if(spos.location! = Nsnotfound && epos.location! =nsnotfound) {Nsuinteger s= Spos.location +spos.length; Nsuinteger e=epos.location; Nsrange Range= Nsmakerange (S, e-s); key=[key Substringwithrange:range];} Key= [Key stringbyreplacingoccurrencesofstring:@"\ r"Withstring:@""];key= [Key stringbyreplacingoccurrencesofstring:@"\ n"Withstring:@""];key= [Key stringbyreplacingoccurrencesofstring:@"\ t"Withstring:@""];key= [Key stringbyreplacingoccurrencesofstring:@" "Withstring:@""];//This'll be base64 encoded, decode it.NSData *data =Base64_decode (key);d ATA=[RSA Strippublickeyheader:data];if(!data) {returnNil;} NSString*tag =@"What_the_fuck_is_this"; NSData*d_tag =[NSData datawithbytes:[tag utf8string] length:[tag length]];//Delete any old lingering key with the same tagNsmutabledictionary *publickey =[[Nsmutabledictionary alloc] init]; [PublicKey setobject: (__bridgeID) Ksecclasskey Forkey: (__bridgeID) Ksecclass]; [PublicKey setobject: (__bridgeID) Ksecattrkeytypersa Forkey: (__bridgeID) Ksecattrkeytype]; [PublicKey setobject:d_tag Forkey: (__bridgeID) Ksecattrapplicationtag]; Secitemdelete ((__bridge cfdictionaryref) publickey);//ADD Persistent version of the key to system keychain[PublicKey setobject:data Forkey: (__bridgeID) Ksecvaluedata]; [PublicKey setobject: (__bridgeID) ksecattrkeyclasspublic Forkey: (__bridgeID) Ksecattrkeyclass]; [PublicKey setobject:[nsnumber Numberwithbool:yes] Forkey: (__bridgeID) Ksecreturnpersistentref]; Cftyperef Persistkey=nil;osstatus Status= Secitemadd (__bridge cfdictionaryref) PublicKey, &persistkey);if(Persistkey! =Nil) {cfrelease (Persistkey);}if(Status! = NOERR) && (Status! =Errsecduplicateitem)) {returnNil;} [PublicKey Removeobjectforkey: (__bridgeID) Ksecvaluedata]; [PublicKey Removeobjectforkey: (__bridgeID) Ksecreturnpersistentref]; [PublicKey setobject:[nsnumber Numberwithbool:yes] Forkey: (__bridgeID) Ksecreturnref]; [PublicKey setobject: (__bridgeID) Ksecattrkeytypersa Forkey: (__bridgeID) Ksecattrkeytype];//Now fetch the SECKEYREF version of the keySeckeyref KeyRef =Nil;status= Secitemcopymatching ((__bridge cfdictionaryref) PublicKey, (Cftyperef *) &keyRef);if(Status! =NOERR) {returnNil;}returnKeyRef;}

1+ (NSString *) EncryptData: (NSData *) data publickey: (NSString *) pubkey{2 if(!data | |!PubKey) {3 returnNil;4 }5Seckeyref KeyRef =[RSA Addpublickey:pubkey];6 if(!keyRef) {7 returnNil;8 }9 Ten Constuint8_t *srcbuf = (Constuint8_t *) [data bytes]; Onesize_t Srclen =(size_t) data.length; A  -size_t Outlen = seckeygetblocksize (KEYREF) *sizeof(uint8_t); - if(Srclen > Outlen- One){ the cfrelease (KEYREF); - returnNil; - } - void*outbuf =malloc (Outlen); +  -Osstatus status =NOERR; +Status =Seckeyencrypt (KeyRef, AKsecpaddingnone,//The original author is written by KSecPaddingPKCS1, through the spring Brother study here written Ksecpaddingnone only in line with our use at Srcbuf, - Srclen, - Outbuf, -&Outlen -   ); -NSString *ret =Nil; in if(Status! =0) { - //NSLog (@ "Seckeyencrypt fail. Error Code:%ld ", status); to}Else{ +NSData *data =[NSData datawithbytes:outbuf Length:outlen]; -RET =base64_encode_data (data); the } * Free (OUTBUF); $ cfrelease (KEYREF);Panax Notoginseng returnret; -}

There is also an article to refer to:HTTP://BLOG.IAMZSX.ME/SHOW.HTML?ID=155002 signature mechanism is not enough to encrypt only one parameter, but also to ensure that the request has not been tampered with, so the signature mechanism is necessary. Relatively simple and commonly used is MD5 signature: Get to sign the string a (such as a URL), and the server contract with the key to the new string B, the B MD5 algorithm to get the signature C,c is then sent to the server as a signature of a. After the server receives the request, the same algorithm for a with the client-agreed key to get C ', if c==c ', that means that the change request has not been tampered with, otherwise the validation can also do RSA signature This is a little more troublesome than MD5 signature, because the client needs to generate a public key pair, The basic process is also the same as the MD5 signature of the string A to be signed a (such as a URL), it is encrypted with the private key to the string B, and then the B and the original data A and its own public key sent to the server, the server received the request, with the public key decryption to get B ', if B==b ', Indicates that the original data has not been tampered with, otherwise the validation does not pass. Also said here to get B, need to re-use the server's public key encryption to get C, the C and the original data and their public key sent to the server, the server received, now need to use their own private key to decrypt the C ', and then use the client's public key decryption to get B ', and then ibid ...  RSA signature and verification I still do not use, so the specific how to achieve the need for research, to be supplemented!!! Httpshttps is a typical application of RSA encryption, but this server's public key private key is not produced by itself, but by the CA issued. Specific principles on the web a lot, one of them: http://jingyan.baidu.com/article/2fb0ba4048e15500f3ec5f7e.html

RSA algorithm and its use in 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.