Using JSPatch in PHP and iOS is basically encrypted with RSA and AES.

Source: Internet
Author: User
PHP and iOS use JSPatch and RSA. AES encryption when JSPatch is used, JS scripts can theoretically call any OC method, and the permission is very high. if it is transmitted over HTTP, tampering with js code by man-in-the-middle attacks can cause great harm.

In view of this situation

1. try to use https for transmission on the server. 2. encrypt and verify the transmitted code.

Next, use php on the server side and iOS on the mobile side to process the second method.

RSA algorithm

RSA is currently the most influential public key encryption algorithm. it can resist the vast majority of known password attacks so far and has been recommended as the public key data encryption standard by ISO.

RSA is an asymmetric encryption algorithm that is often used to encrypt data transmission. if it is used together with the digest algorithm, it can also be used for file signature.

The RSA algorithm is an asymmetric algorithm. it requires a pair of keys and one of them is used for encryption. The other is used for decryption. During RSA encrypted communication, we put the public key on the client and the private key on the server.

Generally
1. public key encryption, private key decryption 2. private key is used to sign the file, and the public key is used to verify the signature
Public key and private key generation
  1. Use openSSL commands to generate keys

openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem

Enter the password of the private key (which will be used later) as Prompted. after signing the certificate's organization name, email, and other information, the certificate file public_key.der and private key file private_key.pem are generated.

The public_key.der file is used for distribution to the ios client for public key encryption and decryption, while the private_key.pem file is left on the server side for php to use.

openssl rsa -in private_key.pem -pubout -out public_key.pem

This command generates a public key file in pem format based on the entered private key file, which is also the reason for putting private_key on the server.

Server php code (ThinkPHP framework, encryption and decryption code has no direct relationship with the framework)
    
    
 
 

If the resourceID is not obtained, first check whether openssl extension is enabled, and then check whether the private_key has been indented without authorization.

==================

Use JSPatch for iOS

The JSPatch script has a high execution permission. if it is tampered with by a man in the middle during the transmission process, it will bring a lot of security issues. to prevent this situation, the RSA signature is encrypted for the JS file during transmission. The process is as follows:

Server:
  1. Calculate the MD5 value of the JS content.
  2. Use the RSA private key to encrypt the MD5 value and send it to the client together with the JS content.
Client:
  1. Obtain the encrypted data and use the RSA public key to decrypt the MD5 value.
  2. Locally calculate the MD5 value of the returned JS content.
  3. Compare the two MD5 values above. if they are equal, the verification is passed and the JS file is saved to the local device. Because RSA is non-symmetric encryption, a third party cannot encrypt the corresponding MD5 value without a private key, and thus cannot forge JS files, eliminating the possibility of tampering during the transmission of JS files.
Server php code
/** Encrypt a string and return the RSA encrypted content * aString * return encrypted rsa encrypted string */public function enjscode ($ aString) {$ pi_key = openssl_pkey_get_private (self: PRIVATE_KEY); // This function can be used to determine whether the private key is available. the Resource id openssl_private_encrypt ($ aString, $ encrypted, $ pi_key); // private key encryption $ encrypted = base64_encode ($ encrypted); // The encrypted content usually contains special characters and requires encoding and conversion, during url transmission between networks, pay attention to whether base64 encoding is url-safe return $ encrypted;} // JS public Function jscode () {// $ headers = $ this-> verifyHeaders (); // verify the header // $ this-> verifyHeadersWithHeaders ($ headers ); $ data ['con '] = "defineClass ('findviewcontroller', {viewDidLoad: function () {self. super (). viewDidLoad (); self. setTitle ('Haha found '); _ selectedIndex = 0; self. initView () ;}}) "; $ data ['isupdate'] = 'true'; // calculate the md5 value of the js content first, then encrypt the md5 value in RSA $ data ["ver"] = self: enjscode (md5 ($ data ['con ']); $ data1 ['con'] = "Require ('uialertview'); defineClass ('circlehotpageviewcontroller', {tableView_didSelectRowAtIndexPath: function (tableView, indexPath) {tableView. deselectRowAtIndexPath_animated (indexPath, YES); var alert = UIAlertView. alloc (). initWithTitle_message_delegate_cancelButtonTitle_otherButtonTitles ('just a prompt ', 'Test JSPath! ', Null,' Knows ', null, null); alert. show () ;}}) "; $ data1 ['isupdate'] = 'true'; $ data1 [" ver "] = self :: enjscode (md5 ($ data1 ['con ']); $ this-> json_out ('20170', '0', '', $ da );}
IOS code

Because native encryption and decryption on iOS is not very easy to use, use the RSA encryption and decryption method encapsulated on github here. For Download, click RSA encryption and decryption.

  1. Import Security. framework
  2. Retrieve public_key from public_key.pem
#define rsa_public_key @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDdg086h7CIhMPG0EdzE/RacFc3rfpBkKYSQhX2OgObuICugbolSqiaUa6CZc4Ock988ubc6MKUqiLjGfNdOJ3Iod7ryqDb7z4cI08uphhyR6CmhgZZyu6DFzpoudMFQPKr3/vpGZ8Z/Vu7TGJwnuhkpEAUuSoMrYaSKj2qnGmNXQIDAQAB"

3. make a network request in the didFinishLaunchingWithOptions method to get the content data from the network disconnection

/** Obtain the content as * con js content * isUpdate or not (useless) * ver verification content, with con computing md5, then perform rsa encryption-> decrypt the client homepage to obtain the md5 value of con, and compare the md5 value with the md5 value of the obtained js content ** if the value is equal, otherwise, it indicates that the bucket is not tampered with. the bucket */-(void) upJSHandle :( NSDictionary *) response {NSMutableString * jsString = [NSMutableString string]; for (NSDictionary * di in (NSArray *) response) {NSString * js = di [@ "con"]; // calculate the md5 value of the obtained js content NSString * jsMd5 = [MiscTool md5: js]; // decrypt the md5 NSS of the obtained js content Tring * cdMd5 = [RSA decryptString: di [@ "ver"] publicKey: rsa_public_key]; NSLog (@ "cd bicode = % @", cdMd5); // verify if (! [JsMd5 isEqualToString: cdMd5]) {// after verification, the content is not equal. if the content is tampered with, the NSLog (@ "zz content is tampered !!! "); Return;} [jsString appendString: js]; // download the code locally and save it as a Document/up file. js. use the ***** separator [jsString appendString: @ "******"];} // Obtain and save the js file content NSString * jsPath = [self jsFilePath]; NSLog (@ "js xx = write % @", jsString ); // perform aes symmetric encryption on jsString // jsString = [self aes: jsString]. mutableCopy; // NSLog (@ "xx encrypted ==%@", jsString); NSData * jsData = [jsString dataUsingEncoding :( NSUTF8StringEncoding)]; // write the file [jsData writeToFile: jsPath atomically: YES]; // execute [self execUpJsWithJsArray: [self readJs];}

4. in the applicationDidBecomeActive method, read the js file and execute

# Pragma mark -- js read-(NSArray *) readJs {NSString * file = [self jsFilePath]; NSFileManager * fileManager = [NSFileManager defaultManager]; if (! [FileManager fileExistsAtPath: file]) {// if no return @ [];} NSString * jsString = [NSString stringWithContentsOfFile: file encoding: NSUTF8StringEncoding error: nil]; // after retrieval, decrypt jsString // jsString = [self cdAes: jsString]; // NSLog (@ "xx after decryption =%@", jsString); NSArray * jsArray = [jsString componentsSeparatedByString: @ "*****"]; return jsArray;}-(void) execUpJsWithJsArray :( NSArray *) jsArray {if (jsArray. count = 0) {return;} [JPEngine startEngine]; for (NSString * js in jsArray) {if ([js isEqualToString: @ ""] | js = nil) {continue;} NSLog (@ "read js =%@", js); [JPEngine evaluateScript: js] ;}}-(void) applicationDidBecomeActive :( UIApplication *) application {// Restart any tasks that were paused (or not yet started) while the application was inactive. if the application was previusly in the background, optionally refresh the user interface. // execute js [self execUpJsWithJsArray: [self readJs] every time you enter;}
Local Storage

The chance of tampering with locally stored scripts is much lower, but it is only risky on the jailbreaking machine. you can perform symmetric encryption after the script is downloaded and saved locally, and decrypt it each time you read the script.

Aes encryption and decryption
/** Perform aes symmetric encryption */-(NSString *) aes :( NSString *) aString {NSString * biCode = [SecurityUtil encryptAESData: aString app_key: aesKey]; // NSLog (@ "xx encryption: % @", st); return biCode;}/** perform aes decryption on the string */-(NSString *) cdAes :( NSString *) aString {// NSData * EncryptData1 = [GTMBase64 decodeString: [SecurityUtil encoding: string app_key: aesKey]; // perform GTMBase64 encoding NSData * EncryptData = [GTMBase64 decodeString: aString]; NSString * unCode = [SecurityUtil decryptAESData: EncryptData app_key: aesKey]; // NSLog (@ "xx decryption: % @", string1); return unCode ;}

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.