├── .gitignore
├── RSAUtil.xcodeproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcshareddata
│ │ └── RSAUtil.xccheckout
└── project.pbxproj
├── RSAUtil
├── ViewController.h
├── AppDelegate.h
├── main.m
├── Images.xcassets
│ └── AppIcon.appiconset
│ │ └── Contents.json
├── Base.lproj
│ ├── Main.storyboard
│ └── LaunchScreen.xib
├── Info.plist
├── AppDelegate.m
└── ViewController.m
├── Demo.m
├── RSA.h
├── LICENSE
├── README.md
├── encrypt.php
└── RSA.m
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | *.swp
3 | *.xcuserstate
4 | RSAUtil.xcodeproj/xcuserdata
5 |
--------------------------------------------------------------------------------
/RSAUtil.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/RSAUtil/ViewController.h:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.h
3 | // RSAUtil
4 | //
5 | // Created by ideawu on 7/14/15.
6 | // Copyright (c) 2015 ideawu. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface ViewController : UIViewController
12 |
13 |
14 | @end
15 |
16 |
--------------------------------------------------------------------------------
/RSAUtil/AppDelegate.h:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.h
3 | // RSAUtil
4 | //
5 | // Created by ideawu on 7/14/15.
6 | // Copyright (c) 2015 ideawu. All rights reserved.
7 | //
8 |
9 | #import
10 |
11 | @interface AppDelegate : UIResponder
12 |
13 | @property (strong, nonatomic) UIWindow *window;
14 |
15 |
16 | @end
17 |
18 |
--------------------------------------------------------------------------------
/RSAUtil/main.m:
--------------------------------------------------------------------------------
1 | //
2 | // main.m
3 | // RSAUtil
4 | //
5 | // Created by ideawu on 7/14/15.
6 | // Copyright (c) 2015 ideawu. All rights reserved.
7 | //
8 |
9 | #import
10 | #import "AppDelegate.h"
11 |
12 | int main(int argc, char * argv[]) {
13 | @autoreleasepool {
14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/Demo.m:
--------------------------------------------------------------------------------
1 | /*
2 | @author: ideawu
3 | @link: https://github.com/ideawu/Objective-C-RSA
4 | */
5 | #import "RSA.h"
6 |
7 | NSString *pubkey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDLuwt30JLYFvKcFOUdjPuDRdqv\nSnDb5TSdA/w0ND/GwLExpT66DeRz9+6//G//Y0y3c/yWT14k/ab1vID4U6W3vOgr\nafC0RyuIgH8ooCTNQpU+LtIoZ6qCejnux7VZ5lwWeT/9DQjWOtf6TopeRdzmOX09\nwa7c5xGGUsmi29QxDQIDAQAB\n-----END PUBLIC KEY-----";
8 | NSString *ret = [RSA encryptString:@"hello world!" publicKey:pubkey];
9 | NSLog(@"encrypted: %@", ret);
10 |
--------------------------------------------------------------------------------
/RSA.h:
--------------------------------------------------------------------------------
1 | /*
2 | @author: ideawu
3 | @link: https://github.com/ideawu/Objective-C-RSA
4 | */
5 |
6 | #import
7 |
8 | @interface RSA : NSObject
9 |
10 | // return base64 encoded string
11 | + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey;
12 | // return raw data
13 | + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey;
14 | // return base64 encoded string
15 | + (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey;
16 | // return raw data
17 | + (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey;
18 |
19 | // decrypt base64 encoded string, convert result to string(not base64 encoded)
20 | + (NSString *)decryptString:(NSString *)str publicKey:(NSString *)pubKey;
21 | + (NSData *)decryptData:(NSData *)data publicKey:(NSString *)pubKey;
22 | + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;
23 | + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey;
24 |
25 | @end
26 |
--------------------------------------------------------------------------------
/RSAUtil/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | },
33 | {
34 | "idiom" : "ipad",
35 | "size" : "29x29",
36 | "scale" : "1x"
37 | },
38 | {
39 | "idiom" : "ipad",
40 | "size" : "29x29",
41 | "scale" : "2x"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "size" : "40x40",
46 | "scale" : "1x"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "size" : "40x40",
51 | "scale" : "2x"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "size" : "76x76",
56 | "scale" : "1x"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "size" : "76x76",
61 | "scale" : "2x"
62 | }
63 | ],
64 | "info" : {
65 | "version" : 1,
66 | "author" : "xcode"
67 | }
68 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2013 Objective-C-RSA(https://github.com/ideawu/Objective-C-RSA) Authors
2 | All rights reserved.
3 |
4 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
5 |
6 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
7 |
8 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
9 |
10 | 3. Neither the name of the Objective-C-RSA(https://github.com/ideawu/Objective-C-RSA) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
11 |
12 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13 |
--------------------------------------------------------------------------------
/RSAUtil/Base.lproj/Main.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/RSAUtil/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | com.ideawu.$(PRODUCT_NAME:rfc1034identifier)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIMainStoryboardFile
28 | Main
29 | UIRequiredDeviceCapabilities
30 |
31 | armv7
32 |
33 | UISupportedInterfaceOrientations
34 |
35 | UIInterfaceOrientationPortrait
36 | UIInterfaceOrientationLandscapeLeft
37 | UIInterfaceOrientationLandscapeRight
38 |
39 | UISupportedInterfaceOrientations~ipad
40 |
41 | UIInterfaceOrientationPortrait
42 | UIInterfaceOrientationPortraitUpsideDown
43 | UIInterfaceOrientationLandscapeLeft
44 | UIInterfaceOrientationLandscapeRight
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/RSAUtil.xcodeproj/project.xcworkspace/xcshareddata/RSAUtil.xccheckout:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | IDESourceControlProjectFavoriteDictionaryKey
6 |
7 | IDESourceControlProjectIdentifier
8 | F8B2757A-71D6-4FD4-BC9D-FA99AC4DD58F
9 | IDESourceControlProjectName
10 | RSAUtil
11 | IDESourceControlProjectOriginsDictionary
12 |
13 | 0FCF057405D50E0F54C86A564EB5510C1EFDE566
14 | https://github.com/ideawu/Objective-C-RSA.git
15 |
16 | IDESourceControlProjectPath
17 | RSAUtil.xcodeproj
18 | IDESourceControlProjectRelativeInstallPathDictionary
19 |
20 | 0FCF057405D50E0F54C86A564EB5510C1EFDE566
21 | ../..
22 |
23 | IDESourceControlProjectURL
24 | https://github.com/ideawu/Objective-C-RSA.git
25 | IDESourceControlProjectVersion
26 | 111
27 | IDESourceControlProjectWCCIdentifier
28 | 0FCF057405D50E0F54C86A564EB5510C1EFDE566
29 | IDESourceControlProjectWCConfigurations
30 |
31 |
32 | IDESourceControlRepositoryExtensionIdentifierKey
33 | public.vcs.git
34 | IDESourceControlWCCIdentifierKey
35 | 0FCF057405D50E0F54C86A564EB5510C1EFDE566
36 | IDESourceControlWCCName
37 | Objective-C-RSA
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/RSAUtil/AppDelegate.m:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.m
3 | // RSAUtil
4 | //
5 | // Created by ideawu on 7/14/15.
6 | // Copyright (c) 2015 ideawu. All rights reserved.
7 | //
8 |
9 | #import "AppDelegate.h"
10 |
11 | @interface AppDelegate ()
12 |
13 | @end
14 |
15 | @implementation AppDelegate
16 |
17 |
18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
19 | // Override point for customization after application launch.
20 | return YES;
21 | }
22 |
23 | - (void)applicationWillResignActive:(UIApplication *)application {
24 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
25 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
26 | }
27 |
28 | - (void)applicationDidEnterBackground:(UIApplication *)application {
29 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
30 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
31 | }
32 |
33 | - (void)applicationWillEnterForeground:(UIApplication *)application {
34 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
35 | }
36 |
37 | - (void)applicationDidBecomeActive:(UIApplication *)application {
38 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
39 | }
40 |
41 | - (void)applicationWillTerminate:(UIApplication *)application {
42 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
43 | }
44 |
45 | @end
46 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Objective-C-RSA
2 | Doing RSA encryption with Objective-C iOS
3 |
4 | ## If you have the same qustion as mine: [iOS Objective-C RSA encrypt with only public key and descrypt with PHP](http://www.ideawu.com/blog/post/132.html)
5 |
6 | ## Usage
7 |
8 | #import "RSA.h"
9 |
10 | NSString *pubkey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI2bvVLVYrb4B0raZgFP60VXY\ncvRmk9q56QiTmEm9HXlSPq1zyhyPQHGti5FokYJMzNcKm0bwL1q6ioJuD4EFI56D\na+70XdRz1CjQPQE3yXrXXVvOsmq9LsdxTFWsVBTehdCmrapKZVVx6PKl7myh0cfX\nQmyveT/eqyZK1gYjvQIDAQAB\n-----END PUBLIC KEY-----";
11 | NSString *privkey = @"-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMMjZu9UtVitvgHS\ntpmAU/rRVdhy9GaT2rnpCJOYSb0deVI+rXPKHI9Aca2LkWiRgkzM1wqbRvAvWrqK\ngm4PgQUjnoNr7vRd1HPUKNA9ATfJetddW86yar0ux3FMVaxUFN6F0KatqkplVXHo\n8qXubKHRx9dCbK95P96rJkrWBiO9AgMBAAECgYBO1UKEdYg9pxMX0XSLVtiWf3Na\n2jX6Ksk2Sfp5BhDkIcAdhcy09nXLOZGzNqsrv30QYcCOPGTQK5FPwx0mMYVBRAdo\nOLYp7NzxW/File//169O3ZFpkZ7MF0I2oQcNGTpMCUpaY6xMmxqN22INgi8SHp3w\nVU+2bRMLDXEc/MOmAQJBAP+Sv6JdkrY+7WGuQN5O5PjsB15lOGcr4vcfz4vAQ/uy\nEGYZh6IO2Eu0lW6sw2x6uRg0c6hMiFEJcO89qlH/B10CQQDDdtGrzXWVG457vA27\nkpduDpM6BQWTX6wYV9zRlcYYMFHwAQkE0BTvIYde2il6DKGyzokgI6zQyhgtRJ1x\nL6fhAkB9NvvW4/uWeLw7CHHVuVersZBmqjb5LWJU62v3L2rfbT1lmIqAVr+YT9CK\n2fAhPPtkpYYo5d4/vd1sCY1iAQ4tAkEAm2yPrJzjMn2G/ry57rzRzKGqUChOFrGs\nlm7HF6CQtAs4HC+2jC0peDyg97th37rLmPLB9txnPl50ewpkZuwOAQJBAM/eJnFw\nF5QAcL4CYDbfBKocx82VX/pFXng50T7FODiWbbL4UnxICE0UBFInNNiWJxNEb6jL\n5xd0pcy9O2DOeso=\n-----END PRIVATE KEY-----";
12 |
13 | NSString *encrypted = [RSA encryptString:@"hello world!" publicKey:pubkey];
14 | NSLog(@"encrypted: %@", encrypted);
15 | NSString *decrypted = [RSA decryptString:encrypted privateKey:privkey];
16 | NSLog(@"decrypted: %@", decrypted);
17 |
18 | __Notice: iOS 10 requires Keychain Entitlements__
19 |
20 | ### Important
21 |
22 | Not thread-safe.
23 |
24 | ## History
25 |
26 | ### 2015-09-26
27 |
28 | - New functions:
29 | - `(NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey;`
30 | - `(NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey;`
31 |
32 |
33 | ## The PHP script for testing
34 |
35 | See `encrypt.php` in the repository.
36 |
37 |
38 | ## Swift version
39 |
40 | - [https://github.com/btnguyen2k/swift-rsautils](https://github.com/btnguyen2k/swift-rsautils)
41 |
42 |
--------------------------------------------------------------------------------
/RSAUtil/ViewController.m:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.m
3 | // RSAUtil
4 | //
5 | // Created by ideawu on 7/14/15.
6 | // Copyright (c) 2015 ideawu. All rights reserved.
7 | //
8 |
9 | #import "ViewController.h"
10 | #import "RSA.h"
11 |
12 | @interface ViewController ()
13 |
14 | @end
15 |
16 | @implementation ViewController
17 |
18 | - (void)viewDidLoad {
19 | [super viewDidLoad];
20 |
21 |
22 | NSString *pubkey = @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI2bvVLVYrb4B0raZgFP60VXY\ncvRmk9q56QiTmEm9HXlSPq1zyhyPQHGti5FokYJMzNcKm0bwL1q6ioJuD4EFI56D\na+70XdRz1CjQPQE3yXrXXVvOsmq9LsdxTFWsVBTehdCmrapKZVVx6PKl7myh0cfX\nQmyveT/eqyZK1gYjvQIDAQAB\n-----END PUBLIC KEY-----";
23 | NSString *privkey = @"-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMMjZu9UtVitvgHS\ntpmAU/rRVdhy9GaT2rnpCJOYSb0deVI+rXPKHI9Aca2LkWiRgkzM1wqbRvAvWrqK\ngm4PgQUjnoNr7vRd1HPUKNA9ATfJetddW86yar0ux3FMVaxUFN6F0KatqkplVXHo\n8qXubKHRx9dCbK95P96rJkrWBiO9AgMBAAECgYBO1UKEdYg9pxMX0XSLVtiWf3Na\n2jX6Ksk2Sfp5BhDkIcAdhcy09nXLOZGzNqsrv30QYcCOPGTQK5FPwx0mMYVBRAdo\nOLYp7NzxW/File//169O3ZFpkZ7MF0I2oQcNGTpMCUpaY6xMmxqN22INgi8SHp3w\nVU+2bRMLDXEc/MOmAQJBAP+Sv6JdkrY+7WGuQN5O5PjsB15lOGcr4vcfz4vAQ/uy\nEGYZh6IO2Eu0lW6sw2x6uRg0c6hMiFEJcO89qlH/B10CQQDDdtGrzXWVG457vA27\nkpduDpM6BQWTX6wYV9zRlcYYMFHwAQkE0BTvIYde2il6DKGyzokgI6zQyhgtRJ1x\nL6fhAkB9NvvW4/uWeLw7CHHVuVersZBmqjb5LWJU62v3L2rfbT1lmIqAVr+YT9CK\n2fAhPPtkpYYo5d4/vd1sCY1iAQ4tAkEAm2yPrJzjMn2G/ry57rzRzKGqUChOFrGs\nlm7HF6CQtAs4HC+2jC0peDyg97th37rLmPLB9txnPl50ewpkZuwOAQJBAM/eJnFw\nF5QAcL4CYDbfBKocx82VX/pFXng50T7FODiWbbL4UnxICE0UBFInNNiWJxNEb6jL\n5xd0pcy9O2DOeso=\n-----END PRIVATE KEY-----";
24 |
25 | NSString *originString = @"hello world!";
26 | for(int i=0; i<4; i++){
27 | originString = [originString stringByAppendingFormat:@" %@", originString];
28 | }
29 | NSString *encWithPubKey;
30 | NSString *decWithPrivKey;
31 | NSString *encWithPrivKey;
32 | NSString *decWithPublicKey;
33 |
34 | NSLog(@"Original string(%d): %@", (int)originString.length, originString);
35 |
36 | // Demo: encrypt with public key
37 | encWithPubKey = [RSA encryptString:originString publicKey:pubkey];
38 | NSLog(@"Enctypted with public key: %@", encWithPubKey);
39 | // Demo: decrypt with private key
40 | decWithPrivKey = [RSA decryptString:encWithPubKey privateKey:privkey];
41 | NSLog(@"Decrypted with private key: %@", decWithPrivKey);
42 |
43 | // by PHP
44 | encWithPubKey = @"CKiZsP8wfKlELNfWNC2G4iLv0RtwmGeHgzHec6aor4HnuOMcYVkxRovNj2r0Iu3ybPxKwiH2EswgBWsi65FOzQJa01uDVcJImU5vLrx1ihJ/PADUVxAMFjVzA3+Clbr2fwyJXW6dbbbymupYpkxRSfF5Gq9KyT+tsAhiSNfU6akgNGh4DENoA2AoKoWhpMEawyIubBSsTdFXtsHK0Ze0Cyde7oI2oh8ePOVHRuce6xYELYzmZY5yhSUoEb4+/44fbVouOCTl66ppUgnR5KjmIvBVEJLBq0SgoZfrGiA3cB08q4hb5EJRW72yPPQNqJxcQTPs8SxXa9js8ZryeSxyrw==";
45 | decWithPrivKey = [RSA decryptString:encWithPubKey privateKey:privkey];
46 | NSLog(@"(PHP enc)Decrypted with private key: %@", decWithPrivKey);
47 |
48 | // Demo: encrypt with private key
49 | encWithPrivKey = [RSA encryptString:originString privateKey:privkey];
50 | NSLog(@"Enctypted with private key: %@", encWithPrivKey);
51 |
52 | // Demo: decrypt with public key
53 | decWithPublicKey = [RSA decryptString:encWithPrivKey publicKey:pubkey];
54 | NSLog(@"(PHP enc)Decrypted with public key: %@", decWithPublicKey);
55 | }
56 |
57 | @end
58 |
--------------------------------------------------------------------------------
/RSAUtil/Base.lproj/LaunchScreen.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
20 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/encrypt.php:
--------------------------------------------------------------------------------
1 | "sha512",
4 | "private_key_bits" => 1024,
5 | "private_key_type" => OPENSSL_KEYTYPE_RSA,
6 | );
7 | $res = openssl_pkey_new($config);
8 | $private_key = '';
9 | openssl_pkey_export($res, $private_key);
10 | $details = openssl_pkey_get_details($res);
11 | $public_key = $details["key"];
12 |
13 | echo "=====================\n";
14 | echo "create private key and public key:\n";
15 | echo "# PRIVATE:\n";
16 | echo str_replace("\n", "\\n", $private_key) . "\n";
17 | echo "# PUBLIC:\n";
18 | echo str_replace("\n", "\\n", $public_key) . "\n";
19 | #var_dump($private_key, $public_key);
20 | echo "=====================\n";
21 | echo "\n\n\n";
22 |
23 | $public_key = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI2bvVLVYrb4B0raZgFP60VXY\ncvRmk9q56QiTmEm9HXlSPq1zyhyPQHGti5FokYJMzNcKm0bwL1q6ioJuD4EFI56D\na+70XdRz1CjQPQE3yXrXXVvOsmq9LsdxTFWsVBTehdCmrapKZVVx6PKl7myh0cfX\nQmyveT/eqyZK1gYjvQIDAQAB\n-----END PUBLIC KEY-----";
24 | $private_key = "-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMMjZu9UtVitvgHS\ntpmAU/rRVdhy9GaT2rnpCJOYSb0deVI+rXPKHI9Aca2LkWiRgkzM1wqbRvAvWrqK\ngm4PgQUjnoNr7vRd1HPUKNA9ATfJetddW86yar0ux3FMVaxUFN6F0KatqkplVXHo\n8qXubKHRx9dCbK95P96rJkrWBiO9AgMBAAECgYBO1UKEdYg9pxMX0XSLVtiWf3Na\n2jX6Ksk2Sfp5BhDkIcAdhcy09nXLOZGzNqsrv30QYcCOPGTQK5FPwx0mMYVBRAdo\nOLYp7NzxW/File//169O3ZFpkZ7MF0I2oQcNGTpMCUpaY6xMmxqN22INgi8SHp3w\nVU+2bRMLDXEc/MOmAQJBAP+Sv6JdkrY+7WGuQN5O5PjsB15lOGcr4vcfz4vAQ/uy\nEGYZh6IO2Eu0lW6sw2x6uRg0c6hMiFEJcO89qlH/B10CQQDDdtGrzXWVG457vA27\nkpduDpM6BQWTX6wYV9zRlcYYMFHwAQkE0BTvIYde2il6DKGyzokgI6zQyhgtRJ1x\nL6fhAkB9NvvW4/uWeLw7CHHVuVersZBmqjb5LWJU62v3L2rfbT1lmIqAVr+YT9CK\n2fAhPPtkpYYo5d4/vd1sCY1iAQ4tAkEAm2yPrJzjMn2G/ry57rzRzKGqUChOFrGs\nlm7HF6CQtAs4HC+2jC0peDyg97th37rLmPLB9txnPl50ewpkZuwOAQJBAM/eJnFw\nF5QAcL4CYDbfBKocx82VX/pFXng50T7FODiWbbL4UnxICE0UBFInNNiWJxNEb6jL\n5xd0pcy9O2DOeso=\n-----END PRIVATE KEY-----";
25 |
26 |
27 | $data = 'hello world';
28 | $data = str_repeat($data, 20);
29 |
30 | $crypted = '';
31 | for($i=0; $i
8 |
9 | @implementation RSA
10 |
11 | /*
12 | static NSString *base64_encode(NSString *str){
13 | NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
14 | if(!data){
15 | return nil;
16 | }
17 | return base64_encode_data(data);
18 | }
19 | */
20 |
21 | static NSString *base64_encode_data(NSData *data){
22 | data = [data base64EncodedDataWithOptions:0];
23 | NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
24 | return ret;
25 | }
26 |
27 | static NSData *base64_decode(NSString *str){
28 | NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
29 | return data;
30 | }
31 |
32 | + (NSData *)stripPublicKeyHeader:(NSData *)d_key{
33 | // Skip ASN.1 public key header
34 | if (d_key == nil) return(nil);
35 |
36 | unsigned long len = [d_key length];
37 | if (!len) return(nil);
38 |
39 | unsigned char *c_key = (unsigned char *)[d_key bytes];
40 | unsigned int idx = 0;
41 |
42 | if (c_key[idx++] != 0x30) return(nil);
43 |
44 | if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
45 | else idx++;
46 |
47 | // PKCS #1 rsaEncryption szOID_RSA_RSA
48 | static unsigned char seqiod[] =
49 | { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
50 | 0x01, 0x05, 0x00 };
51 | if (memcmp(&c_key[idx], seqiod, 15)) return(nil);
52 |
53 | idx += 15;
54 |
55 | if (c_key[idx++] != 0x03) return(nil);
56 |
57 | if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
58 | else idx++;
59 |
60 | if (c_key[idx++] != '\0') return(nil);
61 |
62 | // Now make a new NSData from this buffer
63 | return([NSData dataWithBytes:&c_key[idx] length:len - idx]);
64 | }
65 |
66 | //credit: http://hg.mozilla.org/services/fx-home/file/tip/Sources/NetworkAndStorage/CryptoUtils.m#l1036
67 | + (NSData *)stripPrivateKeyHeader:(NSData *)d_key{
68 | // Skip ASN.1 private key header
69 | if (d_key == nil) return(nil);
70 |
71 | unsigned long len = [d_key length];
72 | if (!len) return(nil);
73 |
74 | unsigned char *c_key = (unsigned char *)[d_key bytes];
75 | unsigned int idx = 22; //magic byte at offset 22
76 |
77 | if (0x04 != c_key[idx++]) return nil;
78 |
79 | //calculate length of the key
80 | unsigned int c_len = c_key[idx++];
81 | int det = c_len & 0x80;
82 | if (!det) {
83 | c_len = c_len & 0x7f;
84 | } else {
85 | int byteCount = c_len & 0x7f;
86 | if (byteCount + idx > len) {
87 | //rsa length field longer than buffer
88 | return nil;
89 | }
90 | unsigned int accum = 0;
91 | unsigned char *ptr = &c_key[idx];
92 | idx += byteCount;
93 | while (byteCount) {
94 | accum = (accum << 8) + *ptr;
95 | ptr++;
96 | byteCount--;
97 | }
98 | c_len = accum;
99 | }
100 |
101 | // Now make a new NSData from this buffer
102 | return [d_key subdataWithRange:NSMakeRange(idx, c_len)];
103 | }
104 |
105 | + (SecKeyRef)addPublicKey:(NSString *)key{
106 | NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
107 | NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
108 | if(spos.location != NSNotFound && epos.location != NSNotFound){
109 | NSUInteger s = spos.location + spos.length;
110 | NSUInteger e = epos.location;
111 | NSRange range = NSMakeRange(s, e-s);
112 | key = [key substringWithRange:range];
113 | }
114 | key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
115 | key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
116 | key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
117 | key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
118 |
119 | // This will be base64 encoded, decode it.
120 | NSData *data = base64_decode(key);
121 | data = [RSA stripPublicKeyHeader:data];
122 | if(!data){
123 | return nil;
124 | }
125 |
126 | //a tag to read/write keychain storage
127 | NSString *tag = @"RSAUtil_PubKey";
128 | NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
129 |
130 | // Delete any old lingering key with the same tag
131 | NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
132 | [publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
133 | [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
134 | [publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
135 | SecItemDelete((__bridge CFDictionaryRef)publicKey);
136 |
137 | // Add persistent version of the key to system keychain
138 | [publicKey setObject:data forKey:(__bridge id)kSecValueData];
139 | [publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
140 | kSecAttrKeyClass];
141 | [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
142 | kSecReturnPersistentRef];
143 |
144 | CFTypeRef persistKey = nil;
145 | OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
146 | if (persistKey != nil){
147 | CFRelease(persistKey);
148 | }
149 | if ((status != noErr) && (status != errSecDuplicateItem)) {
150 | return nil;
151 | }
152 |
153 | [publicKey removeObjectForKey:(__bridge id)kSecValueData];
154 | [publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
155 | [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
156 | [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
157 |
158 | // Now fetch the SecKeyRef version of the key
159 | SecKeyRef keyRef = nil;
160 | status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
161 | if(status != noErr){
162 | return nil;
163 | }
164 | return keyRef;
165 | }
166 |
167 | + (SecKeyRef)addPrivateKey:(NSString *)key{
168 | NSRange spos;
169 | NSRange epos;
170 | spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
171 | if(spos.length > 0){
172 | epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];
173 | }else{
174 | spos = [key rangeOfString:@"-----BEGIN PRIVATE KEY-----"];
175 | epos = [key rangeOfString:@"-----END PRIVATE KEY-----"];
176 | }
177 | if(spos.location != NSNotFound && epos.location != NSNotFound){
178 | NSUInteger s = spos.location + spos.length;
179 | NSUInteger e = epos.location;
180 | NSRange range = NSMakeRange(s, e-s);
181 | key = [key substringWithRange:range];
182 | }
183 | key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
184 | key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
185 | key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
186 | key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
187 |
188 | // This will be base64 encoded, decode it.
189 | NSData *data = base64_decode(key);
190 | data = [RSA stripPrivateKeyHeader:data];
191 | if(!data){
192 | return nil;
193 | }
194 |
195 | //a tag to read/write keychain storage
196 | NSString *tag = @"RSAUtil_PrivKey";
197 | NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
198 |
199 | // Delete any old lingering key with the same tag
200 | NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];
201 | [privateKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
202 | [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
203 | [privateKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
204 | SecItemDelete((__bridge CFDictionaryRef)privateKey);
205 |
206 | // Add persistent version of the key to system keychain
207 | [privateKey setObject:data forKey:(__bridge id)kSecValueData];
208 | [privateKey setObject:(__bridge id) kSecAttrKeyClassPrivate forKey:(__bridge id)
209 | kSecAttrKeyClass];
210 | [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
211 | kSecReturnPersistentRef];
212 |
213 | CFTypeRef persistKey = nil;
214 | OSStatus status = SecItemAdd((__bridge CFDictionaryRef)privateKey, &persistKey);
215 | if (persistKey != nil){
216 | CFRelease(persistKey);
217 | }
218 | if ((status != noErr) && (status != errSecDuplicateItem)) {
219 | return nil;
220 | }
221 |
222 | [privateKey removeObjectForKey:(__bridge id)kSecValueData];
223 | [privateKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
224 | [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
225 | [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
226 |
227 | // Now fetch the SecKeyRef version of the key
228 | SecKeyRef keyRef = nil;
229 | status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);
230 | if(status != noErr){
231 | return nil;
232 | }
233 | return keyRef;
234 | }
235 |
236 | /* START: Encryption & Decryption with RSA private key */
237 |
238 | + (NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef isSign:(BOOL)isSign {
239 | const uint8_t *srcbuf = (const uint8_t *)[data bytes];
240 | size_t srclen = (size_t)data.length;
241 |
242 | size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
243 | void *outbuf = malloc(block_size);
244 | size_t src_block_size = block_size - 11;
245 |
246 | NSMutableData *ret = [[NSMutableData alloc] init];
247 | for(int idx=0; idx src_block_size){
251 | data_len = src_block_size;
252 | }
253 |
254 | size_t outlen = block_size;
255 | OSStatus status = noErr;
256 |
257 | if (isSign) {
258 | status = SecKeyRawSign(keyRef,
259 | kSecPaddingPKCS1,
260 | srcbuf + idx,
261 | data_len,
262 | outbuf,
263 | &outlen
264 | );
265 | } else {
266 | status = SecKeyEncrypt(keyRef,
267 | kSecPaddingPKCS1,
268 | srcbuf + idx,
269 | data_len,
270 | outbuf,
271 | &outlen
272 | );
273 | }
274 | if (status != 0) {
275 | NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
276 | ret = nil;
277 | break;
278 | }else{
279 | [ret appendBytes:outbuf length:outlen];
280 | }
281 | }
282 |
283 | free(outbuf);
284 | CFRelease(keyRef);
285 | return ret;
286 | }
287 |
288 | + (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey{
289 | NSData *data = [RSA encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] privateKey:privKey];
290 | NSString *ret = base64_encode_data(data);
291 | return ret;
292 | }
293 |
294 | + (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey{
295 | if(!data || !privKey){
296 | return nil;
297 | }
298 | SecKeyRef keyRef = [RSA addPrivateKey:privKey];
299 | if(!keyRef){
300 | return nil;
301 | }
302 | return [RSA encryptData:data withKeyRef:keyRef isSign:YES];
303 | }
304 |
305 | + (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
306 | const uint8_t *srcbuf = (const uint8_t *)[data bytes];
307 | size_t srclen = (size_t)data.length;
308 |
309 | size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
310 | UInt8 *outbuf = malloc(block_size);
311 | size_t src_block_size = block_size;
312 |
313 | NSMutableData *ret = [[NSMutableData alloc] init];
314 | for(int idx=0; idx src_block_size){
318 | data_len = src_block_size;
319 | }
320 |
321 | size_t outlen = block_size;
322 | OSStatus status = noErr;
323 | status = SecKeyDecrypt(keyRef,
324 | kSecPaddingNone,
325 | srcbuf + idx,
326 | data_len,
327 | outbuf,
328 | &outlen
329 | );
330 | if (status != 0) {
331 | NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
332 | ret = nil;
333 | break;
334 | }else{
335 | //the actual decrypted data is in the middle, locate it!
336 | int idxFirstZero = -1;
337 | int idxNextZero = (int)outlen;
338 | for ( int i = 0; i < outlen; i++ ) {
339 | if ( outbuf[i] == 0 ) {
340 | if ( idxFirstZero < 0 ) {
341 | idxFirstZero = i;
342 | break;
343 | } else {
344 | // idxNextZero = i;
345 | // break;
346 | }
347 | }
348 | }
349 |
350 | [ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
351 | }
352 | }
353 |
354 | free(outbuf);
355 | CFRelease(keyRef);
356 | return ret;
357 | }
358 |
359 |
360 | + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey{
361 | NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
362 | data = [RSA decryptData:data privateKey:privKey];
363 | NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
364 | return ret;
365 | }
366 |
367 | + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{
368 | if(!data || !privKey){
369 | return nil;
370 | }
371 | SecKeyRef keyRef = [RSA addPrivateKey:privKey];
372 | if(!keyRef){
373 | return nil;
374 | }
375 | return [RSA decryptData:data withKeyRef:keyRef];
376 | }
377 |
378 | /* END: Encryption & Decryption with RSA private key */
379 |
380 | /* START: Encryption & Decryption with RSA public key */
381 |
382 | + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey{
383 | NSData *data = [RSA encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];
384 | NSString *ret = base64_encode_data(data);
385 | return ret;
386 | }
387 |
388 | + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{
389 | if(!data || !pubKey){
390 | return nil;
391 | }
392 | SecKeyRef keyRef = [RSA addPublicKey:pubKey];
393 | if(!keyRef){
394 | return nil;
395 | }
396 | return [RSA encryptData:data withKeyRef:keyRef isSign:NO];
397 | }
398 |
399 | + (NSString *)decryptString:(NSString *)str publicKey:(NSString *)pubKey{
400 | NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
401 | data = [RSA decryptData:data publicKey:pubKey];
402 | NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
403 | return ret;
404 | }
405 |
406 | + (NSData *)decryptData:(NSData *)data publicKey:(NSString *)pubKey{
407 | if(!data || !pubKey){
408 | return nil;
409 | }
410 | SecKeyRef keyRef = [RSA addPublicKey:pubKey];
411 | if(!keyRef){
412 | return nil;
413 | }
414 | return [RSA decryptData:data withKeyRef:keyRef];
415 | }
416 |
417 | /* END: Encryption & Decryption with RSA public key */
418 |
419 | @end
420 |
--------------------------------------------------------------------------------