iOS common encryption algorithms

Source: Internet
Author: User


First of all, let's talk about our game design security considerations (lazy typing, directly from the design documents copied, but also forgive me ....) Own independent game, so 100% of the copyright ha)
5.1 Prevent data plaintext transmission with simple UrlEncode + BASE64 encoding
5.2 For normal request, return data, generate MD5 checksum (add dynamic key in MD5), data integrity (simple anti-tamper, low security, Advantage: fast) check.
5.3 For important data, the use of RSA digital signature, play a tamper-proof role.
5.4 For more sensitive data, such as user information (login, registration, etc.), the client sends using RSA encryption, and the server returns using DES (AES) encryption.
Cause: The client sends the RSA encryption because RSA decryption needs to know the server private key, and the server private key is generally difficult to steal, if you use DES, you can crack the client to obtain the key, security is low. While the server returned to use DES, because regardless of whether the use of DES or RSA, the key (or the private key) are stored in the client, there is a risk of being cracked, therefore, the need to adopt a dynamic key, RSA key generation is more complex, not suitable for dynamic keys, and RSA speed is relatively slow, So choose des)



The code of the relevant algorithm is also affixed to it (in fact, the use of some mature third party libraries may come more simple, but write, free point). Note that most of the cryptographic algorithms here refer to some of the existing algorithms, or use them directly.
1, MD5
Because the category is used, the parameters of the wood are passed in.

-(NSString*) StringFromMD5 {
if( Self==Nil|| [ Selflength] ==0) {
returnNil;
}
ConstChar*value = [ Selfutf8string];
unsignedCharoutputbuffer[Cc_md5_digest_length];
CC_MD5(Value,strlen(value), OutputBuffer);
nsmutablestring*outputstring = [[nsmutablestringAlloc]initwithcapacity:Cc_md5_digest_length*2];
for(NsintegerCount =0; Count <Cc_md5_digest_length; count++) {
[outputstringAppendFormat:@ "%02x", Outputbuffer[count]];
}
return[outputstringautorelease];
}


2, Base64

+ (NSString*) Base64encodedata: (NSData*) Objdata {
ConstunsignedChar* Objrawdata = [objdatabytes];
Char* ObjPointer;
Char* STRRESULT;

Get the Raw data length and ensure we actually have data
intIntlength = [Objdatalength];
if(Intlength = =0)returnNil;

Setup the string-based Result placeholder and pointer within that placeholder
Strresult = (Char*)calloc((Intlength +2) /3) *4,sizeof(Char));
ObjPointer = Strresult;

Iterate through everything
while(Intlength >2) { Keep going until we have less than bits
*objpointer++ =_base64encodingtable[objrawdata[0] >>2];
*objpointer++ =_base64encodingtable[((objrawdata[0] &0x03) <<4) + (objrawdata[1] >>4)];
*objpointer++ =_base64encodingtable[((objrawdata[1] &0x0f) <<2) + (objrawdata[2] >>6)];
*objpointer++ =_base64encodingtable[objrawdata[2] &0x3f];

We just handled 3 octets (bits) of data
Objrawdata + =3;
Intlength-=3;
}

Now deal with the tail end of things
if(Intlength! =0) {
*objpointer++ =_base64encodingtable[objrawdata[0] >>2];
if(Intlength >1) {
*objpointer++ =_base64encodingtable[((objrawdata[0] &0x03) <<4) + (objrawdata[1] >>4)];
*objpointer++ =_base64encodingtable[(objrawdata[1] &0x0f) <<2];
*objpointer++ =' = ';
}Else{
*objpointer++ =_base64encodingtable[(objrawdata[0] &0x03) <<4];
*objpointer++ =' = ';
*objpointer++ =' = ';
}
}

Terminate the string-based result
*objpointer =' + ';

    NSString*rststr = [NSStringStringwithcstring: StrresultEncoding:Nsasciistringencoding];
Free(ObjPointer);
returnRSTSTR;
}




3. AES
-(NSData*) Encryptaes: (NSString*) Key {
    Charkeyptr[kCCKeySizeAES256+1];
bzero(Keyptr,sizeof(keyptr));

[KeyGetcstring: KeyptrMaxLength:sizeof(keyptr)Encoding:Nsutf8stringencoding];

NsuintegerDatalength = [ Selflength];

size_tbuffersize = Datalength +kCCBlockSizeAES128;
void*buffer =malloc(buffersize);

size_tnumbytesencrypted =0;
    CccryptorstatusCryptstatus =Cccrypt(Kccencrypt, kCCAlgorithmAES128,
kccoptionpkcs7padding|Kccoptionecbmode,
Keyptr,kCCBlockSizeAES128,
NULL,
[ Selfbytes], datalength,
Buffer, buffersize,
&numbytesencrypted);
if(Cryptstatus = =kccsuccess) {
return[NSDatadatawithbytesnocopy: Bufferlength: numbytesencrypted];
}

Free(buffer);
    Return Nil;
}


4. RSA

- (NSData*) Encryptwithdata: (NSData*) Content {
size_tPlainlen = [Contentlength];
if(Plainlen >Maxplainlen) {
        NSLog(@ "Content (%LD) is too long, must <%LD", Plainlen,Maxplainlen);
returnNil;
}

void*plain =malloc(Plainlen);
[ContentgetBytes:p Lain
length:p Lainlen];

    size_tCipherlen = -; Currently RSA key length is set to bytes
void*cipher =malloc(Cipherlen);

OsstatusReturnCode =Seckeyencrypt(PublicKey,kSecPaddingPKCS1, Plain,
Plainlen, cipher, &cipherlen);

NSData*result =Nil;
if(ReturnCode! =0) {
        NSLog(@ "Seckeyencrypt fail. Error Code:%ld ", ReturnCode);
}
Else{
result = [NSDatadatawithbytes: Cipher
length: Cipherlen];
}

Free(plain);
Free(cipher);

returnResult
}

iOS common encryption algorithms

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.