Basic knowledge
-
What is RSA?
A: RSA is an asymmetric encryption algorithm, often used to encrypt the transmitted data, with the Digital Digest algorithm, you can also be text signature.
-
RSA encryption in padding?
A: Padding is the Fill method, because the RSA encryption algorithm to encrypt the clear text is smaller than the modulus, padding is through some fill way to limit the length of the plaintext. Several modes of padding and segmented encryption are described in detail later.
-
What is the difference between encryption and signing?
A: The public key is placed on the client, and the data is encrypted with the public key, and the server is decrypted with the private key after it gets the data;
Add-on: The private key is placed on the client, and the data is signed with the private key, the service side to get the data with the public key for verification.
The former is purely for encryption, the latter is mainly for the purpose of preventing malicious attacks, to prevent others from impersonating our client to attack our server, causing the server to crash.
Basic principle
RSA encrypts the data using a key pair, which needs to survive the public key and the private key before encryption and decryption.
public key: used to encrypt data. Used for public, typically stored in data providers, such as iOS clients.
private key: used to decrypt data. Must be kept secret and private key leaks can create security issues.
The Security.framework in iOS provides support for the RSA algorithm, which requires processing the key pair, generating a certificate from public key, and generating a key in the P12 format with private key. Think of the Jave directly with string encryption and decryption is much simpler. (⊙o⊙) ...
Actual combat
Certificate generation
RSA encrypts this public key, the private key is necessary. Apple does not support encrypting and decrypting directly using strings, it is recommended to use the P12 file . Here to teach you to generate all the files used in the encryption, and provided to Java use, think of this public key private key for half a day. %>_<%
- Generate a private key with a modulus length of 1024bit
OpenSSL genrsa-out Private_key.pem 1024
- Generate certification Require file
OpenSSL Req-new-key private_key.pem-out RSACERTREQ.CSR
- Generate certification and specify expiration time
OpenSSL x509-req-days3650-in Rsacertreq.csr-signkey private_key.pem-out rsacert.crt
- Generate a public key for use with iOS
OpenSSL x509-outform der-in rsacert.crt-out Public_key.der
- Generate a private key for iOS use this way you will be prompted for a password, which will be used later when generating seckeyref.
OpenSSL pkcs12-export-out Private_key.p12-inkey private_key.pem-in rsacert.crt
- Generate the public key at the end of the PEM for use in Java
OpenSSL rsa-in private_key.pem-out rsa_public_key.pem-pubout
- Generate the private key at the end of the PEM for Java to use OpenSSL pkcs8-topk8-in private_key.pem-out pkcs8_private_key.pem-nocrypt
All of the above steps are done under the terminal Oh (^__^)
Generate Seckeyref for public and private keys
//generate the private key according to your p12 file the corresponding seckeyref this side returns if nil please check your P12 file generation steps-(Seckeyref) Getprivatekeyrefrencefromdata: (nsdata*) p12data Password: (nsstring*) Password {seckeyref privatekeyref=NULL; Nsmutabledictionary* Options =[[Nsmutabledictionary alloc] init]; [Options Setobject:password Forkey: (__bridgeID) Ksecimportexportpassphrase]; Cfarrayref Items= Cfarraycreate (NULL,0,0, NULL); Osstatus securityerror= Secpkcs12import ((__bridge cfdataref) P12data, (__bridge cfdictionaryref) options, &items);if(Securityerror = = NoErr && cfarraygetcount (items) >0) {cfdictionaryref identitydict= Cfarraygetvalueatindex (items,0); Secidentityref Identityapp=(secidentityref) cfdictionarygetvalue (identitydict, ksecimportitemidentity); Securityerror= Secidentitycopyprivatekey (Identityapp, &privatekeyref); if(Securityerror! =NOERR) {Privatekeyref=NULL; }}cfrelease (items);returnPrivatekeyref;}
-
//based on the seckeyref of your der file's public key-(Seckeyref) Getpublickeyrefrencefromedata: (nsdata*) derdata {seccertificateref mycertificate=Seccertificatecreatewithdata (Kcfallocatordefault, (__bridge cfdataref) derdata); Secpolicyref MyPolicy=SecPolicyCreateBasicX509 (); Sectrustref mytrust;osstatus Status= Sectrustcreatewithcertificates (mycertificate,mypolicy,&mytrust); Sectrustresulttype Trustresult;if(Status = =NOERR) {Status= Sectrustevaluate (Mytrust, &trustresult);} Seckeyref SecurityKey=Sectrustcopypublickey (Mytrust); Cfrelease (mycertificate); Cfrelease (MyPolicy); Cfrelease (mytrust);returnSecurityKey;}
Encryption and decryption
-(nsdata*) Rsaencryptdata: (nsdata*) Data {seckeyref key=[self getpublickey]; size_t cipherbuffersize=seckeygetblocksize (key); uint8_t*cipherbuffer = malloc (Cipherbuffersize *sizeof(uint8_t)); size_t blockSize= Cipherbuffersize- One; size_t Blockcount= (size_t) ceil ([Data length]/(Double) blockSize); Nsmutabledata*encrypteddata =[[Nsmutabledata alloc] init]; for(intI=0; i<blockcount; i++) {unsignedLongbuffersize = MIN (blockSize, [data length]-I *blockSize); NSData*buffer = [Data Subdatawithrange:nsmakerange (i *blockSize, buffersize)]; Osstatus Status= Seckeyencrypt (Key, KSecPaddingPKCS1, (Constuint8_t *) [buffer bytes], [buffer length], Cipherbuffer, &cipherbuffersize); if(Status! =NOERR) { returnNil; } NSData*encryptedbytes = [[NSData alloc] Initwithbytes: (Const void*) Cipherbuffer Length:cipherbuffersize]; [EncryptedData appenddata:encryptedbytes]; } if(Cipherbuffer) {free (cipherbuffer); } returnEncryptedData; }
-
-(nsdata*) Rsadecryptdata: (nsdata*) Data {seckeyref key=[self getprivatkey];size_t cipherbuffersize=seckeygetblocksize (key); size_t BlockSize=cipherbuffersize;size_t Blockcount= (size_t) ceil ([Data length]/(Double) blockSize); Nsmutabledata*decrypteddata =[[Nsmutabledata alloc] init]; for(inti =0; i < Blockcount; i++) {unsignedLongbuffersize = MIN (blockSize, [data length]-I *blockSize); NSData*buffer = [Data Subdatawithrange:nsmakerange (i *blockSize, buffersize)]; size_t Cipherlen=[buffer length]; void*cipher =malloc (Cipherlen); [Buffer getbytes:cipher Length:cipherlen]; size_t Plainlen=seckeygetblocksize (key); void*plain =malloc (Plainlen); Osstatus Status= Seckeydecrypt (key, kSecPaddingPKCS1, cipher, Cipherlen, plain, &Plainlen); if(Status! =NOERR) { returnNil; } NSData*decryptedbytes = [[NSData alloc] Initwithbytes: (Const void*) plain Length:plainlen]; [Decrypteddata appenddata:decryptedbytes];}returnDecrypteddata;}
Padding in RSA encryption
-
Rsa_pkcs1_padding fill mode, the most commonly used mode
Requirements: Input: must be shorter than RSA key modulo length (modulus) at least 11 bytes, that is, Rsa_size (RSA) –11 If the input clear text is too long, you must cut and then fill.
Output: As long as modulus
According to this requirement, for a 1024bit key, block length = 1024/8–11 = 117 bytes
-
Rsa_pkcs1_oaep_padding
Input: Rsa_size (RSA) –41
Output: As long as modulus
-
Rsa_no_padding not populated
Input: Can be as long as the RSA key modulus, if the input clear text is too long, you must cut, and then fill
Output: As long as modulus
Signature and verification
//sha256 signature of data-(NSData *) Rsasha256signdata: (NSData *) plaindata {seckeyref key=[self getprivatkey]; size_t signedhashbytessize=seckeygetblocksize (key); uint8_t* Signedhashbytes =malloc (signedhashbytessize); memset (Signedhashbytes,0x0, signedhashbytessize); size_t hashbytessize=cc_sha256_digest_length; uint8_t* Hashbytes =malloc (hashbytessize); if(!cc_sha256 ([plaindata bytes], (cc_long) [Plaindata length], hashbytes)) { returnNil;} Seckeyrawsign (Key, ksecpaddingpkcs1sha256, Hashbytes, Hashbytessize, S Ignedhashbytes,&signedhashbytessize); NSData* Signedhash =[NSData datawithbytes:signedhashbytes Length: (Nsuinteger) signedhashbytessize]; if(hashbytes) free (hashbytes); if(signedhashbytes) free (signedhashbytes); returnSignedhash; }
-
//this way, verify that the signed data is successful, then return Yes-(BOOL) Rsasha256verifydata: (NSData *) plaindata withsignature: (NSData *) Signature {seckeyref key=[self getpublickey]; size_t signedhashbytessize=seckeygetblocksize (key); Const void* Signedhashbytes =[Signature bytes]; size_t hashbytessize=cc_sha256_digest_length; uint8_t* Hashbytes =malloc (hashbytessize); if(!cc_sha256 ([plaindata bytes], (cc_long) [Plaindata length], hashbytes)) { returnNO; } osstatus Status=seckeyrawverify (Key, ksecpaddingpkcs1sha256, Hashby TES, Hashbytessize, Signedhashbytes, Signedhashbytessize); returnStatus = =errsecsuccess; }
This is the end of the article, I hope this article is helpful to everyone. To see the demo, click here: Xyrsacryptor
RELATED links: An article on RSA encryption and SHA Signature | fully synchronized with Java
An article on RSA encryption and SHA Signature | fully synchronized with Java