Generate RSA keys under Mac

Source: Internet
Author: User
Tags base64 base64 encode openssl x509

MAC OS comes with OpenSSL, which you can use with OpenSSL directly on the command line.

Open the command-line tool and enter OpenSSL to open OpenSSL, and then just three commands to get it done.

The first sentence command generates a 1024-bit private key;

openssl> genrsa-out Rsa_private_key.pem 1024x768

The second sentence command to convert the RSA private key to PKCS8 format, the password is empty on the line;

Pkcs8-topk8-inform pem-in Rsa_private_key.pem-outform Pem–nocrypt

The third sentence generates the public key.

Rsa-in Rsa_private_key.pem-pubout-out Rsa_public_key.pem

There is no direct RSA encryption API on iOS. But iOS provides X509 APIs, while X509 supports RSA encryption. Therefore, we can create a self-signed X509 certificate (because the security requirements are not high, we do not need to use a CA-certified certificate), and then call the X509 related API to encrypt.

1) Create a certificate request (enter information as prompted)

OpenSSL req-new-out Cert.csr-key Private_key.pem

2) Self-signed root certificate

OpenSSL x509-req-in cert.csr-out public_key.der-outform der-signkey private_key.pem-days 3650

2. Verify the certificate. Drag the Public_key.der to Xcode, and if the file is not a problem, you can open it directly in Xcode and see the various information about the certificate.

can also be done in one line!

The simplest and quickest way to turn on terminal is to generate a private key and self-signed X509 certificate using OpenSSL (Mac OS x comes with it).

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

Just follow the command-line prompts to enter the content.

Several instructions:

Public_key.der is the output of the self-signed X509 certificate, which we want to use.

PRIVATE_KEY.PEM is the output of the private key, used to decrypt, please keep it properly.

rsa:1024 here 1024 is the key length, 1024 is relatively safe, if needed more secure, can use 2048, but the cost of encryption and decryption will increase.

-days: Certificate expires, be sure to add this parameter, the default certificate expiration time is 30 days, generally we do not want the certificate to expire so short, so write a more appropriate number of days, such as here 3650 (10).

The second step is to use Public_key.der to encrypt.

1. Import Security.framework.

2. Put the Public_key.der in the mainbundle (usually just drag to Xcode).

3. Read the public key from the Public_key.der.

4. Encryption.

The following is a reference code that can only be used to encrypt content that is less than or equal to 116 bytes, and is appropriate for encrypting the password. ARC is used, but it's important to note that some of the resources need to be freed using Cfrealse.

+ (SECKEYREF) getpublickey{//get the Seckeyref pointer to the public key from the public key certificate file    /*Open and parse the cert*/NSString*path = [[NSBundle mainbundle] Pathforresource:@"Public_key"OfType:@"der"]; NSData*certdata =[NSData Datawithcontentsoffile:path]; Seccertificateref cert=Seccertificatecreatewithdata (Kcfallocatordefault, (cfdataref) certdata); Secpolicyref Policy=SecPolicyCreateBasicX509 ();        Sectrustref Trust; Osstatus Status=sectrustcreatewithcertificates (cert, policy,&Trust); /*You can ignore the sectrustresulttype and you have to run Sectrustevaluate * Before you can get the public key*/Sectrustresulttype Trustresult; if(Status = =NOERR) {Status=sectrustevaluate (trust,&Trustresult); }        /*Now grab the public key from the cert*/seckeyref PublicKey=Sectrustcopypublickey (trust); /*Free the Security framework!*/cfrelease (CERT);    Cfrelease (Policy);    Cfrelease (trust); returnPublicKey;}+ (nsmutabledata*) rsaencryptstring: (nsstring*)string{seckeyref key=[self getpublickey]; size_t cipherbuffersize=seckeygetblocksize (key); uint8_t*cipherbuffer = malloc (Cipherbuffersize *sizeof(uint8_t)); NSData*stringbytes = [stringdatausingencoding:nsutf8stringencoding]; size_t blockSize= Cipherbuffersize- One; size_t Blockcount= (size_t) ceil ([Stringbytes length]/(Double) blockSize); Nsmutabledata*encrypteddata =[[[ Nsmutabledata alloc] init] autorelease];  for(intI=0; i<blockcount; i++) {        intbuffersize = MIN (blocksize,[stringbytes length]-I *blockSize); NSData*buffer = [Stringbytes subdatawithrange:nsmakerange (i *blockSize, buffersize)]; Osstatus Status= Seckeyencrypt (Key, KSecPaddingPKCS1, (Constuint8_t *) [Buffer bytes], [buffer length], Cipherbuffer,&cipherbuffersize); if(Status = =NOERR) {NSData*encryptedbytes = [[NSData alloc] Initwithbytes: (Const void*) Cipherbuffer Length:cipherbuffersize];            [EncryptedData appenddata:encryptedbytes];        [Encryptedbytes release]; }Else{            if(Cipherbuffer) free (cipherbuffer); returnNil; }    }    if(Cipherbuffer) free (cipherbuffer); //Release Keycfrelease (key); //NSLog (@ "Encrypted text (%d bytes):%@", [EncryptedData length], [EncryptedData description]);//NSLog (@ "Encrypted text base64:%@", [Base64 Encode:encrypteddata]);    returnEncryptedData;}

Generate RSA keys under Mac

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.