Using Bbrsacryptor to realize RSA encryption and decryption on iOS side

Source: Internet
Author: User

Background

RSA This asymmetric encryption is widely used in the transmission of network data, but it is difficult to implement directly on iOS, Bbrsacryptor framework through the migration of OpenSSL implementation of iOS RSA, this article will show how to use Bbrsacryptor to generate certificates, load the public key, And the backend how to read the certificate with PHP and load the private key.

iOS encryption new project and integrated Bbrsacryptor

This frame comes with a demo that puts the project file and the framework in the same directory, so when the header search paths is not included in the project folder, it is important to note that the following new project puts the framework in the project folder, so the header file search path needs to include the project directory. The detailed steps are as follows.
1. Create a new iOS project, drag Bbrsacryptor, GTMBase64, OpenSSL three folders into the project, the directory structure is as follows.

2. Configure the header Search pathes in build settings.

Note The first folder name is the same as your project name

3. Open the Bbrsacryptor.m file, modify the directory and file path where the certificate is stored, the default is to hide the directory (the front dot), in order to facilitate viewing and replication of the certificate, it is recommended to remove the front of the path, for example:

#define OpenSSLRSAKeyDir [DocumentsDir stringByAppendingPathComponent:@"openssl_rsa"]#define OpenSSLRSAPublicKeyFile [OpenSSLRSAKeyDir stringByAppendingPathComponent:@"publicKey.pem"]#define OpenSSLRSAPrivateKeyFile [OpenSSLRSAKeyDir stringByAppendingPathComponent:@"privateKey.pem"]
    • 1
    • 2
    • 3

4. Open viewcontroller.m, import BBRSACryptor.h and GTMBase64.h, and use the following code to generate the certificate.

BBRSACryptor *rsaCryptor = [[BBRSACryptor alloc] init];[rsaCryptor generateRSAKeyPairWithKeySize:1024];
    • 1
    • 2

After running, the certificate path is printed in the console, and when you enter the path, you can see the public and private key certificates.

5. Use TextEdit to open the public key certificate, copy the portion of the-–begin. key-– and the-–end public key-–, and then create a new macro in the project to save it for subsequent reads.

#define PublicKey @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDjYyZoASYgT+MIc/5YkSJngRbNYEQEI3UF7RVijF0STcMs93pH0qhjLJIQnsvUn2ghEVM4X+S+tQ0XhS+7tmL1UMEFgDgYwG/xr/ZjUozgQyvqeUejA08pbun0E0/Yx9WuBQfCpCc5vNka/ENDZEy/2PbEO5KD3hgsnH1JyNqNnwIDAQAB"
    • 1
    • 2

The client only saves the public key, and the private key is placed on the server. The certificate can be read directly using PHP.

6. Load the public key on the client and encrypt it
The macro was created earlier and the public key can be loaded later with a macro. As follows:

[[BBRSACryptor alloc] init];// PublicKey是从公钥证书中复制的内容创建的宏,见上文。[rsaCryptor importRSAPublicKeyBase64:PublicKey];NSData *data = [rsaCryptor encryptWithPublicKeyUsingPadding:RSA_PADDING_TYPE_PKCS1 plainData:[@"客户端加密的内容" dataUsingEncoding:NSUTF8StringEncoding]];NSString *baseStr = [GTMBase64 stringByEncodingData:data];NSLog(@"%@",baseStr);
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

The public key is loaded first, then the content to be encrypted is converted to NSData, and the encrypted content is Base64 encoded before transmission. In order to verify the decryption, the Base64 encoded encrypted content was printed, the content was copied to the Clipboard, and then pasted in PHP for decryption.

PHP decryption

For convenience, copy the private key certificate generated by the preceding method to a directory on the server, create a PHP file under this directory, and add the following code:

<?php Header ("Content-type:text/html; Charset=utf-8 ");/** * Path to key file */$privateKeyFilePath =' Privatekey.pem ';/** * Path to public key file */$publicKeyFilePath =' Publickey.pem '; Extension_loaded (' OpenSSL ')OrDie' PHP requires OpenSSL extended support '); (File_exists ($privateKeyFilePath) && file_exists ($publicKeyFilePath))OrDie' The file path of the key or public key is incorrect ');/** * Generates a resource type key, and if the key file contents are corrupted, the Openssl_pkey_get_private function returns false */$privateKey = Openssl_pkey_get_private (file_get_contents ($privateKeyFilePath));/** * Generates resource type of public key, Openssl_pkey_get_public function returns False if public key file contents are corrupted */$publicKey = Openssl_pkey_get_public (file_get_contents ($publicKeyFilePath)); ($privateKey &&$publicKey)OrDie' Key or public key is not available ');This piece of content is from the base64 encoding of the encrypted content printed on the iOS side above $encryptData =  ' j0otqbcnbsjauvwrz+ 380y519ssa7ficuo1nvrkimgkugjf0pomou20fhqc77nmskle9/ L4dyynr3xdgda4spo0in39ra9eyxzmx3rlyi1c8ipjakq6xpwzk7bsthicfb/6qmktw5pmio4b0axrv/4lq1rqx/ytuisgkxqtnnti= ';  $ee = Base64_decode ( $encryptData);  $decryptData = "; if (Openssl_private_decrypt ( $ee,  $decryptData,  $privateKey)) {echo  ' decryption succeeded, decrypted data: ', $ Decryptdata, Php_eol; } else {die ( ' decryption succeeded ');} ?>             
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

To access this script, if the previous do not have a problem, you will get the result of decryption:

PHP encryption

With the private key encrypted, the public key can be decrypted on the client. Use the following code to encrypt.

<?php Header ("Content-type:text/html; Charset=utf-8 ");/** * Path to key file */$privateKeyFilePath =' Privatekey.pem ';/** * Path to public key file */$publicKeyFilePath =' Publickey.pem '; Extension_loaded (' OpenSSL ') or Die (' PHP requires OpenSSL extended support '); (File_exists ($privateKeyFilePath) && file_exists ($publicKeyFilePath)) or Die (' The file path of the key or public key is incorrect ');/** * Generates a resource type key, and if the contents of the key file are corrupted, the Openssl_pkey_get_private function returns false */$privateKey = Openssl_pkey_get_private (file_ Get_contents ($privateKeyFilePath));/** * generates the public key of the resource type, if the contents of the public key file are corrupted, the Openssl_pkey_get_public function returns false */$publicKey = Openssl_pkey_get_public (file_get_contents ($publicKeyFilePath)); ($privateKey && $publicKey) or Die ( ' server encrypted content '; /** * encrypted data for transmission on the network */$encryptData = " The original data is: ', $originalData, Php_eol; ///////////////////////////////with private key encryption//////////////////////// if (Openssl_private_encrypt ($originalData, $encryptData, $privateKey)) {echo  ' encryption succeeded, encrypted data ( Base64_encode) for: ', Base64_encode ($encryptData), Php_eol; } else {die ( ' encryption failed ');}?           
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21st
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

When the script is accessed, the encrypted base64 encoding is printed and the encoding is copied to the client for decryption to verify availability.

iOS decryption

To decrypt on the iOS side, like encryption, first load the public key, and then decode the Base64 encoded encrypted content, decrypted and converted to NSString.

[[BBRSACryptor alloc] init];[rsaCryptor importRSAPublicKeyBase64:PublicKey];NSData *enCryptorDataBase64 = [@"aWdbPQHiQzU5CUOAIGQT3OD/MPqcqoXHXDFtYQPVRo9/Mb1S/aVcKQVHDjBpLgfzw+0mWxgHN6SuOfH8z9WobgQrTZh+pxhau3DnfukLmENGPWVMqquWMxTkEU7yCkx/RI7XEwv3jk9d4UgFOv35eqNUgYyWDq2gGatEpfnUg6U=" dataUsingEncoding:NSUTF8StringEncoding];NSData *deCryptorData = [rsaCryptor decryptWithPublicKeyUsingPadding:RSA_PADDING_TYPE_PKCS1 cipherData:[GTMBase64 decodeData:enCryptorDataBase64]];NSLog(@"%@",[[NSString alloc] initWithData:deCryptorData encoding:NSUTF8StringEncoding]);
    • 1
    • 2
    • 3
    • 4
    • 5

Without an accident, the console will print out the decrypted content.

Original

Using Bbrsacryptor to implement RSA encryption on iOS side

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.