The first step is to make a self-signed certificate.
The easiest and quickest way is to open the terminal and use openssl(Mac OS X comes with it) to generate a private key and a self-signed x509 certificate.
OpenSSL req-x509-out public _ key . der-out form der-new-new key RSA: 1024-keyut private _ key . PEM-days 3650
Just follow the prompts on the command line to enter the content.
Some precautions:
Public_key.der is the x509 certificate output from self-signature, which is what we want to use.
Private_key.pem is the output private key used for decryption. Please take good care of it.
Rsa: 1024 Here 1024 is the key length, and 1024 is relatively safe. If it is safer, 2048 can be used, but the cost of encryption and decryption will also increase.
-days: certificate expiration time, and this parameter must be added. The default certificate expiration time is 30 days. Generally, we don't want the certificate to expire so soon, so write a more suitable number of days, such as 3650( 10 year) here.
In fact, this line of command contains several steps (I studied the following steps because I have a private key of private_key.pem, and I want to use it to generate x509 certificate directly, that is, use the following 2-3).
1) to create a private key.
OpenSSL gen RSA-out private _ key . PEM 1024
2) Create a certificate request (enter information as prompted)
OpenSSL req-new-out cert . CSR-key private _ key . PEM
3) Self-signed root certificate
OpenSSL x509-req-in cert . CSR-out public _ key . der-out form der-sign key private _ key . PEM-days 3650
2. Verify the certificate. Drag public_key.der to xcode. If there is nothing wrong with the file, you can open it directly in xcode and see all kinds of information about the certificate.
The second step is to use public_key.der for encryption.
Import security. framework
2. put public_key.der in the mainBundle (generally just drag it to Xcode).
3. Read the public key from public_key.der
4. encryption.
The following is the reference code (it can only be used for the content with encryption length less than or equal to 1 16 bytes, and it is applicable to encryption passwords. ARC is used, but it should be noted that some resources need to be released using CFRealse)
RSA.h
//
// ? RSA.h
//
# Import & lt foundation/foundation.h >;
@interface RSA : NSObject {
SecKeyRef publicKey
SecCertificateRef certificate;
SecPolicyRef policy;
SecTrustRef trust;
size _ t maxPlainLen
}
-(nsdata *) encryptwithdata: (nsdata *) content;
-(nsdata *) encryptwithstring: (nsstring *) content;
@end
RSA.m
//
// ? RSA.m
//
# Import "RSA.h"
@ Implement RSA
-(id) initialization {
self =[super init];
ns string * public key path =[[ns bundle main bundle]path for resource:@ " public _ key "
of type:@ " der "];
if (publicKeyPath == nil) {
NSLog(@ "pub.der not found");
Return to nil
}
ns date * public key file content =[ns data datawithcontentsofile:public key path];
if (publicKeyFileContent == nil) {
NSLog(@ "Cannot read from pub.der");
Return to nil
}
certificate = SecCertificateCreateWithData(kCFAllocatorDefault,(_ _ bridge CFDataRef)publicKeyFileContent);
if (certificate == nil) {
NSLog(@ "Unable to read certificate from publisher");
Return to nil
}
policy = SecPolicyCreateBasicX509();
Osstatus return code = sectrustcreatewithcertificates (certificate, policy, trust);
if (returnCode! = 0) {
Nslog (@ "sectrustcreatewithcertificates failed. Error code: %ld ",return code);
Return to nil
}
SecTrustResultType trust resulttype;
return code = SecTrustEvaluate(trust,trust resulttype);
if (returnCode! = 0) {
NSLog(@"SecTrustEvaluate failed. Error code: %ld ",return code);
Return to nil
}
public key = SecTrustCopyPublicKey(trust);
if (publicKey == nil) {
NSLog(@ " SecTrustCopyPublicKey fail ");
Return to nil
}
maxPlainLen = SecKeyGetBlockSize(public key)- 12;
Return to self;
}
-(ns data *)encryptWithData:(ns data *)content {
Size _ t plain len =[ content length];
if(plain len & gt; maxPlainLen) {
NSLog(@ "content (%ld) is too long, and must be <% ld", plainLen, max plain len);
Return to nil
}
void * plain = malloc(plain len);
[content getBytes:plain?
Length: plain len];
size _ t cipher len = 128; //The current RSA key length is 128 bytes.
void * cipher = malloc(cipher len);
OS status return code = sec key encrypt(public key,kSecPaddingPKCS 1,plain,?
plainLen,cipher,cipher len);
NSData * result = nil
if (returnCode! = 0) {
NSLog(@"SecKeyEncrypt failed. Error code: %ld ",return code);
}
Otherwise {
result =[ns data dataWithBytes:cipher?
Length: cipher len];
}
Free (plain color);
Free (password);
Return the result;
}
-(ns data *)encrypt with string:(ns string *)content {
return[self encryptWithData:[content data using encoding:nsu TF 8 string encoding]];
}
- (void)dealloc{
CFRelease (certificate);
CFRelease (trust);
CFRelease (strategy);
cf release(public key);
}
@end
How to use:
RSA * RSA =[[RSA alloc]init];
If (rsa! = zero) {
NSLog(@“% @”,[RSA encryptWithString:@“test”]);
}
Otherwise {
NSLog(@ " init RSA error ");
}