php、java、android、ios通用的3des方法(推荐)
php服务器,java服务器,android,ios开发兼容的3des加密解密,
php
<?php classDES3{ var$key="my.oschina.net/penngo?#@"; var$iv="01234567"; functionencrypt($input){ $size=mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_CBC); $input=$this->pkcs5_pad($input,$size); $key=str_pad($this->key,24,'0'); $td=mcrypt_module_open(MCRYPT_3DES,'',MCRYPT_MODE_CBC,''); if($this->iv=='') { $iv=@mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND); } else { $iv=$this->iv; } @mcrypt_generic_init($td,$key,$iv); $data=mcrypt_generic($td,$input); mcrypt_generic_deinit($td); mcrypt_module_close($td); $data=base64_encode($data); return$data; } functiondecrypt($encrypted){ $encrypted=base64_decode($encrypted); $key=str_pad($this->key,24,'0'); $td=mcrypt_module_open(MCRYPT_3DES,'',MCRYPT_MODE_CBC,''); if($this->iv=='') { $iv=@mcrypt_create_iv(mcrypt_enc_get_iv_size($td),MCRYPT_RAND); } else { $iv=$this->iv; } $ks=mcrypt_enc_get_key_size($td); @mcrypt_generic_init($td,$key,$iv); $decrypted=mdecrypt_generic($td,$encrypted); mcrypt_generic_deinit($td); mcrypt_module_close($td); $y=$this->pkcs5_unpad($decrypted); return$y; } functionpkcs5_pad($text,$blocksize){ $pad=$blocksize-(strlen($text)%$blocksize); return$text.str_repeat(chr($pad),$pad); } functionpkcs5_unpad($text){ $pad=ord($text{strlen($text)-1}); if($pad>strlen($text)){ returnfalse; } if(strspn($text,chr($pad),strlen($text)-$pad)!=$pad){ returnfalse; } returnsubstr($text,0,-1*$pad); } functionPaddingPKCS7($data){ $block_size=mcrypt_get_block_size(MCRYPT_3DES,MCRYPT_MODE_CBC); $padding_char=$block_size-(strlen($data)%$block_size); $data.=str_repeat(chr($padding_char),$padding_char); return$data; } } $des=newDES3(); echo$ret=$des->encrypt("来自http://jb51.net的博客")."\n"; echo$des->decrypt($ret)."\n";
java(android)
importjava.io.ByteArrayOutputStream; importjava.io.IOException; importjava.io.OutputStream; importjava.io.UnsupportedEncodingException; importjava.security.Key; importjavax.crypto.Cipher; importjavax.crypto.SecretKeyFactory; importjavax.crypto.spec.DESedeKeySpec; importjavax.crypto.spec.IvParameterSpec; /** *3DES加密工具类 */ publicclassDES3{ //密钥 privatefinalstaticStringsecretKey="my.oschina.net/penngo?#@"; //向量 privatefinalstaticStringiv="01234567"; //加解密统一使用的编码方式 privatefinalstaticStringencoding="utf-8"; /** *3DES加密 * *@paramplainText普通文本 *@return *@throwsException */ publicstaticStringencode(StringplainText)throwsException{ Keydeskey=null; DESedeKeySpecspec=newDESedeKeySpec(secretKey.getBytes()); SecretKeyFactorykeyfactory=SecretKeyFactory.getInstance("desede"); deskey=keyfactory.generateSecret(spec); Ciphercipher=Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpecips=newIvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE,deskey,ips); byte[]encryptData=cipher.doFinal(plainText.getBytes(encoding)); returnBase64.encode(encryptData); } /** *3DES解密 * *@paramencryptText加密文本 *@return *@throwsException */ publicstaticStringdecode(StringencryptText)throwsException{ Keydeskey=null; DESedeKeySpecspec=newDESedeKeySpec(secretKey.getBytes()); SecretKeyFactorykeyfactory=SecretKeyFactory.getInstance("desede"); deskey=keyfactory.generateSecret(spec); Ciphercipher=Cipher.getInstance("desede/CBC/PKCS5Padding"); IvParameterSpecips=newIvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE,deskey,ips); byte[]decryptData=cipher.doFinal(Base64.decode(encryptText)); returnnewString(decryptData,encoding); } publicstaticStringpadding(Stringstr){ byte[]oldByteArray; try{ oldByteArray=str.getBytes("UTF8"); intnumberToPad=8-oldByteArray.length%8; byte[]newByteArray=newbyte[oldByteArray.length+numberToPad]; System.arraycopy(oldByteArray,0,newByteArray,0, oldByteArray.length); for(inti=oldByteArray.length;i<newByteArray.length;++i){ newByteArray[i]=0; } returnnewString(newByteArray,"UTF8"); }catch(UnsupportedEncodingExceptione){ System.out.println("Crypter.paddingUnsupportedEncodingException"); } returnnull; } /** *Base64编码工具类 * */ publicstaticclassBase64{ privatestaticfinalchar[]legalChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); publicstaticStringencode(byte[]data){ intstart=0; intlen=data.length; StringBufferbuf=newStringBuffer(data.length*3/2); intend=len-3; inti=start; intn=0; while(i<=end){ intd=((((int)data[i])&0x0ff)<<16)|((((int)data[i+1])&0x0ff)<<8)|(((int)data[i+2])&0x0ff); buf.append(legalChars[(d>>18)&63]); buf.append(legalChars[(d>>12)&63]); buf.append(legalChars[(d>>6)&63]); buf.append(legalChars[d&63]); i+=3; if(n++>=14){ n=0; buf.append(""); } } if(i==start+len-2){ intd=((((int)data[i])&0x0ff)<<16)|((((int)data[i+1])&255)<<8); buf.append(legalChars[(d>>18)&63]); buf.append(legalChars[(d>>12)&63]); buf.append(legalChars[(d>>6)&63]); buf.append("="); }elseif(i==start+len-1){ intd=(((int)data[i])&0x0ff)<<16; buf.append(legalChars[(d>>18)&63]); buf.append(legalChars[(d>>12)&63]); buf.append("=="); } returnbuf.toString(); } privatestaticintdecode(charc){ if(c>='A'&&c<='Z') return((int)c)-65; elseif(c>='a'&&c<='z') return((int)c)-97+26; elseif(c>='0'&&c<='9') return((int)c)-48+26+26; else switch(c){ case'+': return62; case'/': return63; case'=': return0; default: thrownewRuntimeException("unexpectedcode:"+c); } } /** *DecodesthegivenBase64encodedStringtoanewbytearray.Thebytearrayholdingthedecodeddataisreturned. */ publicstaticbyte[]decode(Strings){ ByteArrayOutputStreambos=newByteArrayOutputStream(); try{ decode(s,bos); }catch(IOExceptione){ thrownewRuntimeException(); } byte[]decodedBytes=bos.toByteArray(); try{ bos.close(); bos=null; }catch(IOExceptionex){ System.err.println("ErrorwhiledecodingBASE64:"+ex.toString()); } returndecodedBytes; } privatestaticvoiddecode(Strings,OutputStreamos)throwsIOException{ inti=0; intlen=s.length(); while(true){ while(i<len&&s.charAt(i)<='') i++; if(i==len) break; inttri=(decode(s.charAt(i))<<18)+(decode(s.charAt(i+1))<<12)+(decode(s.charAt(i+2))<<6)+(decode(s.charAt(i+3))); os.write((tri>>16)&255); if(s.charAt(i+2)=='=') break; os.write((tri>>8)&255); if(s.charAt(i+3)=='=') break; os.write(tri&255); i+=4; } } } publicstaticvoidmain(String[]args)throwsException{ StringplainText="来自http://jb51.net的博客"; StringencryptText=DES3.encode(plainText); System.out.println(encryptText); System.out.println(DES3.decode(encryptText)); } }
Ojbective-C(ios)
// //DES3Util.h // #import<Foundation/Foundation.h> @interfaceDES3Util:NSObject{ } //加密方法 +(NSString*)encrypt:(NSString*)plainText; //解密方法 +(NSString*)decrypt:(NSString*)encryptText; @end // //DES3Util.m // #import"DES3Util.h" #import<CommonCrypto/CommonCryptor.h> #import"GTMBase64.h" #definegkey@"my.oschina.net/penngo?#@" #definegIv@"01234567" @implementationDES3Util //加密方法 +(NSString*)encrypt:(NSString*)plainText{ NSData*data=[plainTextdataUsingEncoding:NSUTF8StringEncoding]; size_tplainTextBufferSize=[datalength]; constvoid*vplainText=(constvoid*)[databytes]; CCCryptorStatusccStatus; uint8_t*bufferPtr=NULL; size_tbufferPtrSize=0; size_tmovedBytes=0; bufferPtrSize=(plainTextBufferSize+kCCBlockSize3DES)&~(kCCBlockSize3DES-1); bufferPtr=malloc(bufferPtrSize*sizeof(uint8_t)); memset((void*)bufferPtr,0x0,bufferPtrSize); constvoid*vkey=(constvoid*)[gkeyUTF8String]; constvoid*vinitVec=(constvoid*)[gIvUTF8String]; ccStatus=CCCrypt(kCCEncrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding, vkey, kCCKeySize3DES, vinitVec, vplainText, plainTextBufferSize, (void*)bufferPtr, bufferPtrSize, &movedBytes); NSData*myData=[NSDatadataWithBytes:(constvoid*)bufferPtrlength:(NSUInteger)movedBytes]; NSString*result=[GTMBase64stringByEncodingData:myData]; returnresult; } //解密方法 +(NSString*)decrypt:(NSString*)encryptText{ NSData*encryptData=[GTMBase64decodeData:[encryptTextdataUsingEncoding:NSUTF8StringEncoding]]; size_tplainTextBufferSize=[encryptDatalength]; constvoid*vplainText=[encryptDatabytes]; CCCryptorStatusccStatus; uint8_t*bufferPtr=NULL; size_tbufferPtrSize=0; size_tmovedBytes=0; bufferPtrSize=(plainTextBufferSize+kCCBlockSize3DES)&~(kCCBlockSize3DES-1); bufferPtr=malloc(bufferPtrSize*sizeof(uint8_t)); memset((void*)bufferPtr,0x0,bufferPtrSize); constvoid*vkey=(constvoid*)[gkeyUTF8String]; constvoid*vinitVec=(constvoid*)[gIvUTF8String]; ccStatus=CCCrypt(kCCDecrypt, kCCAlgorithm3DES, kCCOptionPKCS7Padding, vkey, kCCKeySize3DES, vinitVec, vplainText, plainTextBufferSize, (void*)bufferPtr, bufferPtrSize, &movedBytes); NSString*result=[[[NSStringalloc]initWithData:[NSDatadataWithBytes:(constvoid*)bufferPtr length:(NSUInteger)movedBytes]encoding:NSUTF8StringEncoding]autorelease]; returnresult; } @end // //GTMBase64.h // //Copyright2006-2008GoogleInc. // //LicensedundertheApacheLicense,Version2.0(the"License");youmaynot //usethisfileexceptincompliancewiththeLicense.Youmayobtainacopy //oftheLicenseat // //http://www.apache.org/licenses/LICENSE-2.0 // //Unlessrequiredbyapplicablelaworagreedtoinwriting,software //distributedundertheLicenseisdistributedonan"ASIS"BASIS,WITHOUT //WARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.Seethe //Licenseforthespecificlanguagegoverningpermissionsandlimitationsunder //theLicense. //DavidLeemakechanges: //RemovedependencyonGTMDefines.h //addsomestringtostringfunction #import<Foundation/Foundation.h> //GTMBase64 // ///HelperforhandlingBase64andWebSafeBase64encodings // ///ThewebSafemethodsusedifferentcharactersetandalsotheresultsaren't ///alwayspaddedtoamultipleof4characters.Thisisdonesotheresulting ///datacanbeusedinurlsandurlqueryargumentswithoutneedingany ///encoding.YoumustusethewebSafe*methodstogether,thedatadoesnot ///interopwiththeRFCmethods. // @interfaceGTMBase64:NSObject // //StandardBase64(RFC)handling // //encodeData: // ///Base64encodescontentsoftheNSDataobject. // ///Returns: ///AnewautoreleasedNSDatawiththeencodedpayload.nilforanyerror. // +(NSData*)encodeData:(NSData*)data; //decodeData: // ///Base64decodescontentsoftheNSDataobject. // ///Returns: ///AnewautoreleasedNSDatawiththedecodedpayload.nilforanyerror. // +(NSData*)decodeData:(NSData*)data; //encodeBytes:length: // ///Base64encodesthedatapointedatby|bytes|. // ///Returns: ///AnewautoreleasedNSDatawiththeencodedpayload.nilforanyerror. // +(NSData*)encodeBytes:(constvoid*)byteslength:(NSUInteger)length; //decodeBytes:length: // ///Base64decodesthedatapointedatby|bytes|. // ///Returns: ///AnewautoreleasedNSDatawiththeencodedpayload.nilforanyerror. // +(NSData*)decodeBytes:(constvoid*)byteslength:(NSUInteger)length; //stringByEncodingData: // ///Base64encodescontentsoftheNSDataobject. // ///Returns: ///AnewautoreleasedNSStringwiththeencodedpayload.nilforanyerror. // +(NSString*)stringByEncodingData:(NSData*)data; //stringByEncodingBytes:length: // ///Base64encodesthedatapointedatby|bytes|. // ///Returns: ///AnewautoreleasedNSStringwiththeencodedpayload.nilforanyerror. // +(NSString*)stringByEncodingBytes:(constvoid*)byteslength:(NSUInteger)length; //decodeString: // ///Base64decodescontentsoftheNSString. // ///Returns: ///AnewautoreleasedNSDatawiththedecodedpayload.nilforanyerror. // +(NSData*)decodeString:(NSString*)string; // //ModifiedBase64encodingsotheresultscangoontourls. // //Thechangesareinthecharactersgeneratedandalsoallowstheresultto //notbepaddedtoamultipleof4. //Mustusethematchingcalltoencode/decode,won'tinteropwiththe //RFCversions. // //webSafeEncodeData:padded: // ///WebSafeBase64encodescontentsoftheNSDataobject.If|padded|isYES ///thenpaddingcharactersareaddedsotheresultlengthisamultipleof4. // ///Returns: ///AnewautoreleasedNSDatawiththeencodedpayload.nilforanyerror. // +(NSData*)webSafeEncodeData:(NSData*)data padded:(BOOL)padded; //webSafeDecodeData: // ///WebSafeBase64decodescontentsoftheNSDataobject. // ///Returns: ///AnewautoreleasedNSDatawiththedecodedpayload.nilforanyerror. // +(NSData*)webSafeDecodeData:(NSData*)data; //webSafeEncodeBytes:length:padded: // ///WebSafeBase64encodesthedatapointedatby|bytes|.If|padded|isYES ///thenpaddingcharactersareaddedsotheresultlengthisamultipleof4. // ///Returns: ///AnewautoreleasedNSDatawiththeencodedpayload.nilforanyerror. // +(NSData*)webSafeEncodeBytes:(constvoid*)bytes length:(NSUInteger)length padded:(BOOL)padded; //webSafeDecodeBytes:length: // ///WebSafeBase64decodesthedatapointedatby|bytes|. // ///Returns: ///AnewautoreleasedNSDatawiththeencodedpayload.nilforanyerror. // +(NSData*)webSafeDecodeBytes:(constvoid*)byteslength:(NSUInteger)length; //stringByWebSafeEncodingData:padded: // ///WebSafeBase64encodescontentsoftheNSDataobject.If|padded|isYES ///thenpaddingcharactersareaddedsotheresultlengthisamultipleof4. // ///Returns: ///AnewautoreleasedNSStringwiththeencodedpayload.nilforanyerror. // +(NSString*)stringByWebSafeEncodingData:(NSData*)data padded:(BOOL)padded; //stringByWebSafeEncodingBytes:length:padded: // ///WebSafeBase64encodesthedatapointedatby|bytes|.If|padded|isYES ///thenpaddingcharactersareaddedsotheresultlengthisamultipleof4. // ///Returns: ///AnewautoreleasedNSStringwiththeencodedpayload.nilforanyerror. // +(NSString*)stringByWebSafeEncodingBytes:(constvoid*)bytes length:(NSUInteger)length padded:(BOOL)padded; //webSafeDecodeString: // ///WebSafeBase64decodescontentsoftheNSString. // ///Returns: ///AnewautoreleasedNSDatawiththedecodedpayload.nilforanyerror. // +(NSData*)webSafeDecodeString:(NSString*)string; //DavidLeenewaddedfunction ///Returns: //AnewautoreleasedNSStringwithBase64encodedNSString +(NSString*)stringByBase64String:(NSString*)base64String; //DavidLeenewaddedfunction ///Returns: //AnewautoreleasedBase64encodedNSStringwithNSString +(NSString*)base64StringBystring:(NSString*)string; @end // //GTMBase64.m // //Copyright2006-2008GoogleInc. // //LicensedundertheApacheLicense,Version2.0(the"License");youmaynot //usethisfileexceptincompliancewiththeLicense.Youmayobtainacopy //oftheLicenseat // //http://www.apache.org/licenses/LICENSE-2.0 // //Unlessrequiredbyapplicablelaworagreedtoinwriting,software //distributedundertheLicenseisdistributedonan"ASIS"BASIS,WITHOUT //WARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.Seethe //Licenseforthespecificlanguagegoverningpermissionsandlimitationsunder //theLicense. //DavidLeemakechanges: //RemovedependencyonGTMDefines.h //addsomestringtostringfunction #import"GTMBase64.h" staticconstchar*kBase64EncodeChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; staticconstchar*kWebSafeBase64EncodeChars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; staticconstcharkBase64PaddingChar='='; staticconstcharkBase64InvalidChar=99; staticconstcharkBase64DecodeChars[]={ //Thisarraywasgeneratedbythefollowingcode: //#include<sys/time.h> //#include<stdlib.h> //#include<string.h> //main() //{ //staticconstcharBase64[]= //"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //char*pos; //intidx,i,j; //printf(""); //for(i=0;i<255;i+=8){ //for(j=i;j<i+8;j++){ //pos=strchr(Base64,j); //if((pos==NULL)||(j==0)) //idx=99; //else //idx=pos-Base64; //if(idx==99) //printf("%2d,",idx); //else //printf("%2d/*%c*/,",idx,j); //} //printf("\n"); //} //} 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,62/*+*/,99,99,99,63/*/*/, 52/*0*/,53/*1*/,54/*2*/,55/*3*/,56/*4*/,57/*5*/,58/*6*/,59/*7*/, 60/*8*/,61/*9*/,99,99,99,99,99,99, 99,0/*A*/,1/*B*/,2/*C*/,3/*D*/,4/*E*/,5/*F*/,6/*G*/, 7/*H*/,8/*I*/,9/*J*/,10/*K*/,11/*L*/,12/*M*/,13/*N*/,14/*O*/, 15/*P*/,16/*Q*/,17/*R*/,18/*S*/,19/*T*/,20/*U*/,21/*V*/,22/*W*/, 23/*X*/,24/*Y*/,25/*Z*/,99,99,99,99,99, 99,26/*a*/,27/*b*/,28/*c*/,29/*d*/,30/*e*/,31/*f*/,32/*g*/, 33/*h*/,34/*i*/,35/*j*/,36/*k*/,37/*l*/,38/*m*/,39/*n*/,40/*o*/, 41/*p*/,42/*q*/,43/*r*/,44/*s*/,45/*t*/,46/*u*/,47/*v*/,48/*w*/, 49/*x*/,50/*y*/,51/*z*/,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99 }; staticconstcharkWebSafeBase64DecodeChars[]={ //Thisarraywasgeneratedbythefollowingcode: //#include<sys/time.h> //#include<stdlib.h> //#include<string.h> //main() //{ //staticconstcharBase64[]= //"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; //char*pos; //intidx,i,j; //printf(""); //for(i=0;i<255;i+=8){ //for(j=i;j<i+8;j++){ //pos=strchr(Base64,j); //if((pos==NULL)||(j==0)) //idx=99; //else //idx=pos-Base64; //if(idx==99) //printf("%2d,",idx); //else //printf("%2d/*%c*/,",idx,j); //} //printf("\n"); //} //} 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,62/*-*/,99,99, 52/*0*/,53/*1*/,54/*2*/,55/*3*/,56/*4*/,57/*5*/,58/*6*/,59/*7*/, 60/*8*/,61/*9*/,99,99,99,99,99,99, 99,0/*A*/,1/*B*/,2/*C*/,3/*D*/,4/*E*/,5/*F*/,6/*G*/, 7/*H*/,8/*I*/,9/*J*/,10/*K*/,11/*L*/,12/*M*/,13/*N*/,14/*O*/, 15/*P*/,16/*Q*/,17/*R*/,18/*S*/,19/*T*/,20/*U*/,21/*V*/,22/*W*/, 23/*X*/,24/*Y*/,25/*Z*/,99,99,99,99,63/*_*/, 99,26/*a*/,27/*b*/,28/*c*/,29/*d*/,30/*e*/,31/*f*/,32/*g*/, 33/*h*/,34/*i*/,35/*j*/,36/*k*/,37/*l*/,38/*m*/,39/*n*/,40/*o*/, 41/*p*/,42/*q*/,43/*r*/,44/*s*/,45/*t*/,46/*u*/,47/*v*/,48/*w*/, 49/*x*/,50/*y*/,51/*z*/,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99, 99,99,99,99,99,99,99,99 }; //Testsacharactertoseeifit'sawhitespacecharacter. // //Returns: //YESifthecharacterisawhitespacecharacter. //NOifthecharacterisnotawhitespacecharacter. // BOOLIsSpace(unsignedcharc){ //weuseourownmappingherebecausewedon'twantanythingw/locale //support. staticBOOLkSpaces[256]={ 0,0,0,0,0,0,0,0,0,1,//0-9 1,1,1,1,0,0,0,0,0,0,//10-19 0,0,0,0,0,0,0,0,0,0,//20-29 0,0,1,0,0,0,0,0,0,0,//30-39 0,0,0,0,0,0,0,0,0,0,//40-49 0,0,0,0,0,0,0,0,0,0,//50-59 0,0,0,0,0,0,0,0,0,0,//60-69 0,0,0,0,0,0,0,0,0,0,//70-79 0,0,0,0,0,0,0,0,0,0,//80-89 0,0,0,0,0,0,0,0,0,0,//90-99 0,0,0,0,0,0,0,0,0,0,//100-109 0,0,0,0,0,0,0,0,0,0,//110-119 0,0,0,0,0,0,0,0,0,0,//120-129 0,0,0,0,0,0,0,0,0,0,//130-139 0,0,0,0,0,0,0,0,0,0,//140-149 0,0,0,0,0,0,0,0,0,0,//150-159 1,0,0,0,0,0,0,0,0,0,//160-169 0,0,0,0,0,0,0,0,0,0,//170-179 0,0,0,0,0,0,0,0,0,0,//180-189 0,0,0,0,0,0,0,0,0,0,//190-199 0,0,0,0,0,0,0,0,0,0,//200-209 0,0,0,0,0,0,0,0,0,0,//210-219 0,0,0,0,0,0,0,0,0,0,//220-229 0,0,0,0,0,0,0,0,0,0,//230-239 0,0,0,0,0,0,0,0,0,0,//240-249 0,0,0,0,0,1,//250-255 }; returnkSpaces[c]; } //Calculatehowlongthedatawillbeonceit'sbase64encoded. // //Returns: //Theguessedencodedlengthforasourcelength // NSUIntegerCalcEncodedLength(NSUIntegersrcLen,BOOLpadded){ NSUIntegerintermediate_result=8*srcLen+5; NSUIntegerlen=intermediate_result/6; if(padded){ len=((len+3)/4)*4; } returnlen; } //Triestocalculatehowlongthedatawillbeonceit'sbase64decoded. //Unliketheabove,thisisalwaysanupperbound,sincethesourcedata //couldhavespacesandmightendwiththepaddingcharactersonthem. // //Returns: //Theguesseddecodedlengthforasourcelength // NSUIntegerGuessDecodedLength(NSUIntegersrcLen){ return(srcLen+3)/4*3; } @interfaceGTMBase64(PrivateMethods) +(NSData*)baseEncode:(constvoid*)bytes length:(NSUInteger)length charset:(constchar*)charset padded:(BOOL)padded; +(NSData*)baseDecode:(constvoid*)bytes length:(NSUInteger)length charset:(constchar*)charset requirePadding:(BOOL)requirePadding; +(NSUInteger)baseEncode:(constchar*)srcBytes srcLen:(NSUInteger)srcLen destBytes:(char*)destBytes destLen:(NSUInteger)destLen charset:(constchar*)charset padded:(BOOL)padded; +(NSUInteger)baseDecode:(constchar*)srcBytes srcLen:(NSUInteger)srcLen destBytes:(char*)destBytes destLen:(NSUInteger)destLen charset:(constchar*)charset requirePadding:(BOOL)requirePadding; @end @implementationGTMBase64 // //StandardBase64(RFC)handling // +(NSData*)encodeData:(NSData*)data{ return[selfbaseEncode:[databytes] length:[datalength] charset:kBase64EncodeChars padded:YES]; } +(NSData*)decodeData:(NSData*)data{ return[selfbaseDecode:[databytes] length:[datalength] charset:kBase64DecodeChars requirePadding:YES]; } +(NSData*)encodeBytes:(constvoid*)byteslength:(NSUInteger)length{ return[selfbaseEncode:bytes length:length charset:kBase64EncodeChars padded:YES]; } +(NSData*)decodeBytes:(constvoid*)byteslength:(NSUInteger)length{ return[selfbaseDecode:bytes length:length charset:kBase64DecodeChars requirePadding:YES]; } +(NSString*)stringByEncodingData:(NSData*)data{ NSString*result=nil; NSData*converted=[selfbaseEncode:[databytes] length:[datalength] charset:kBase64EncodeChars padded:YES]; if(converted){ result=[[[NSStringalloc]initWithData:converted encoding:NSASCIIStringEncoding]autorelease]; } returnresult; } +(NSString*)stringByEncodingBytes:(constvoid*)byteslength:(NSUInteger)length{ NSString*result=nil; NSData*converted=[selfbaseEncode:bytes length:length charset:kBase64EncodeChars padded:YES]; if(converted){ result=[[[NSStringalloc]initWithData:converted encoding:NSASCIIStringEncoding]autorelease]; } returnresult; } +(NSData*)decodeString:(NSString*)string{ NSData*result=nil; NSData*data=[stringdataUsingEncoding:NSASCIIStringEncoding]; if(data){ result=[selfbaseDecode:[databytes] length:[datalength] charset:kBase64DecodeChars requirePadding:YES]; } returnresult; } // //ModifiedBase64encodingsotheresultscangoontourls. // //Thechangesareinthecharactersgeneratedandalsotheresultisn't //paddedtoamultipleof4. //Mustusethematchingcalltoencode/decode,won'tinteropwiththe //RFCversions. // +(NSData*)webSafeEncodeData:(NSData*)data padded:(BOOL)padded{ return[selfbaseEncode:[databytes] length:[datalength] charset:kWebSafeBase64EncodeChars padded:padded]; } +(NSData*)webSafeDecodeData:(NSData*)data{ return[selfbaseDecode:[databytes] length:[datalength] charset:kWebSafeBase64DecodeChars requirePadding:NO]; } +(NSData*)webSafeEncodeBytes:(constvoid*)bytes length:(NSUInteger)length padded:(BOOL)padded{ return[selfbaseEncode:bytes length:length charset:kWebSafeBase64EncodeChars padded:padded]; } +(NSData*)webSafeDecodeBytes:(constvoid*)byteslength:(NSUInteger)length{ return[selfbaseDecode:bytes length:length charset:kWebSafeBase64DecodeChars requirePadding:NO]; } +(NSString*)stringByWebSafeEncodingData:(NSData*)data padded:(BOOL)padded{ NSString*result=nil; NSData*converted=[selfbaseEncode:[databytes] length:[datalength] charset:kWebSafeBase64EncodeChars padded:padded]; if(converted){ result=[[[NSStringalloc]initWithData:converted encoding:NSASCIIStringEncoding]autorelease]; } returnresult; } +(NSString*)stringByWebSafeEncodingBytes:(constvoid*)bytes length:(NSUInteger)length padded:(BOOL)padded{ NSString*result=nil; NSData*converted=[selfbaseEncode:bytes length:length charset:kWebSafeBase64EncodeChars padded:padded]; if(converted){ result=[[[NSStringalloc]initWithData:converted encoding:NSASCIIStringEncoding]autorelease]; } returnresult; } +(NSData*)webSafeDecodeString:(NSString*)string{ NSData*result=nil; NSData*data=[stringdataUsingEncoding:NSASCIIStringEncoding]; if(data){ result=[selfbaseDecode:[databytes] length:[datalength] charset:kWebSafeBase64DecodeChars requirePadding:NO]; } returnresult; } //DavidLeenewaddedfunction ///Returns: //AnewautoreleasedNSStringwithBase64encodedNSString +(NSString*)stringByBase64String:(NSString*)base64String { NSString*sourceString=[[[NSStringalloc]initWithData:[GTMBase64decodeData:[base64StringdataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:NO]]encoding:NSUTF8StringEncoding]autorelease]; returnsourceString; } //DavidLeenewaddedfunction ///Returns: //AnewautoreleasedBase64encodedNSStringwithNSString +(NSString*)base64StringBystring:(NSString*)string { NSString*base64String=[[[NSStringalloc]initWithData:[GTMBase64encodeData:[stringdataUsingEncoding:NSUTF8StringEncodingallowLossyConversion:NO]]encoding:NSUTF8StringEncoding]autorelease]; returnbase64String; } @end @implementationGTMBase64(PrivateMethods) // //baseEncode:length:charset:padded: // //DoesthecommonliftingofcreatingthedestNSData.itcreates&sizesthe //datafortheresults.|charset|isthecharacterstousefortheencoding //ofthedata.|padding|controlsiftheencodeddatashouldbepaddedtoa //multipleof4. // //Returns: //anautoreleaseNSDatawiththeencodeddata,nilifanyerror. // +(NSData*)baseEncode:(constvoid*)bytes length:(NSUInteger)length charset:(constchar*)charset padded:(BOOL)padded{ //howbigcoulditbe? NSUIntegermaxLength=CalcEncodedLength(length,padded); //makespace NSMutableData*result=[NSMutableDatadata]; [resultsetLength:maxLength]; //doit NSUIntegerfinalLength=[selfbaseEncode:bytes srcLen:length destBytes:[resultmutableBytes] destLen:[resultlength] charset:charset padded:padded]; if(finalLength){ NSAssert(finalLength==maxLength,@"howdidwecalcthelengthwrong?"); }else{ //shouldn'thappen,thismeansweranoutofspace result=nil; } returnresult; } // //baseDecode:length:charset:requirePadding: // //DoesthecommonliftingofcreatingthedestNSData.itcreates&sizesthe //datafortheresults.|charset|isthecharacterstouseforthedecoding //ofthedata. // //Returns: //anautoreleaseNSDatawiththedecodeddata,nilifanyerror. // // +(NSData*)baseDecode:(constvoid*)bytes length:(NSUInteger)length charset:(constchar*)charset requirePadding:(BOOL)requirePadding{ //couldtrytocalculatewhatitwillendupas NSUIntegermaxLength=GuessDecodedLength(length); //makespace NSMutableData*result=[NSMutableDatadata]; [resultsetLength:maxLength]; //doit NSUIntegerfinalLength=[selfbaseDecode:bytes srcLen:length destBytes:[resultmutableBytes] destLen:[resultlength] charset:charset requirePadding:requirePadding]; if(finalLength){ if(finalLength!=maxLength){ //resizedowntohowbigitwas [resultsetLength:finalLength]; } }else{ //eitheranerrorintheargs,orweranoutofspace result=nil; } returnresult; } // //baseEncode:srcLen:destBytes:destLen:charset:padded: // //Encodesthebufferintothelarger.returnsthelengthoftheencoded //data,orzeroforanerror. //|charset|isthecharacterstousefortheencoding //|padded|tellsiftheresultshouldbepaddedtoamultipleof4. // //Returns: //thelengthoftheencodeddata.zeroifanyerror. // +(NSUInteger)baseEncode:(constchar*)srcBytes srcLen:(NSUInteger)srcLen destBytes:(char*)destBytes destLen:(NSUInteger)destLen charset:(constchar*)charset padded:(BOOL)padded{ if(!srcLen||!destLen||!srcBytes||!destBytes){ return0; } char*curDest=destBytes; constunsignedchar*curSrc=(constunsignedchar*)(srcBytes); //Threebytesofdataencodestofourcharactersofcyphertext. //Sowecanpumpthroughthree-bytechunksatomically. while(srcLen>2){ //space? NSAssert(destLen>=4,@"ourcalcforencodedlengthwaswrong"); curDest[0]=charset[curSrc[0]>>2]; curDest[1]=charset[((curSrc[0]&0x03)<<4)+(curSrc[1]>>4)]; curDest[2]=charset[((curSrc[1]&0x0f)<<2)+(curSrc[2]>>6)]; curDest[3]=charset[curSrc[2]&0x3f]; curDest+=4; curSrc+=3; srcLen-=3; destLen-=4; } //nowdealwiththetail(<=2bytes) switch(srcLen){ case0: //Nothingleft;nothingmoretodo. break; case1: //Onebyteleft:thisencodestotwocharacters,and(optionally) //twopadcharacterstoroundoutthefour-charactercypherblock. NSAssert(destLen>=2,@"ourcalcforencodedlengthwaswrong"); curDest[0]=charset[curSrc[0]>>2]; curDest[1]=charset[(curSrc[0]&0x03)<<4]; curDest+=2; destLen-=2; if(padded){ NSAssert(destLen>=2,@"ourcalcforencodedlengthwaswrong"); curDest[0]=kBase64PaddingChar; curDest[1]=kBase64PaddingChar; curDest+=2; } break; case2: //Twobytesleft:thisencodestothreecharacters,and(optionally) //onepadcharactertoroundoutthefour-charactercypherblock. NSAssert(destLen>=3,@"ourcalcforencodedlengthwaswrong"); curDest[0]=charset[curSrc[0]>>2]; curDest[1]=charset[((curSrc[0]&0x03)<<4)+(curSrc[1]>>4)]; curDest[2]=charset[(curSrc[1]&0x0f)<<2]; curDest+=3; destLen-=3; if(padded){ NSAssert(destLen>=1,@"ourcalcforencodedlengthwaswrong"); curDest[0]=kBase64PaddingChar; curDest+=1; } break; } //returnthelength return(curDest-destBytes); } // //baseDecode:srcLen:destBytes:destLen:charset:requirePadding: // //Decodesthebufferintothelarger.returnsthelengthofthedecoded //data,orzeroforanerror. //|charset|isthecharacterdecodingbuffertouse // //Returns: //thelengthoftheencodeddata.zeroifanyerror. // +(NSUInteger)baseDecode:(constchar*)srcBytes srcLen:(NSUInteger)srcLen destBytes:(char*)destBytes destLen:(NSUInteger)destLen charset:(constchar*)charset requirePadding:(BOOL)requirePadding{ if(!srcLen||!destLen||!srcBytes||!destBytes){ return0; } intdecode; NSUIntegerdestIndex=0; intstate=0; charch=0; while(srcLen--&&(ch=*srcBytes++)!=0){ if(IsSpace(ch))//Skipwhitespace continue; if(ch==kBase64PaddingChar) break; decode=charset[(unsignedint)ch]; if(decode==kBase64InvalidChar) return0; //Fourcyphertextcharactersdecodetothreebytes. //Thereforewecanbeinoneoffourstates. switch(state){ case0: //We'reatthebeginningofafour-charactercyphertextblock. //Thissetsthehighsixbitsofthefirstbyteofthe //plaintextblock. NSAssert(destIndex<destLen,@"ourcalcfordecodedlengthwaswrong"); destBytes[destIndex]=decode<<2; state=1; break; case1: //We'reonecharacterintoafour-charactercyphertextblock. //Thissetsthelowtwobitsofthefirstplaintextbyte, //andthehighfourbitsofthesecondplaintextbyte. NSAssert((destIndex+1)<destLen,@"ourcalcfordecodedlengthwaswrong"); destBytes[destIndex]|=decode>>4; destBytes[destIndex+1]=(decode&0x0f)<<4; destIndex++; state=2; break; case2: //We'retwocharactersintoafour-charactercyphertextblock. //Thissetsthelowfourbitsofthesecondplaintext //byte,andthehightwobitsofthethirdplaintextbyte. //However,ifthisistheendofdata,andthosetwo //bitsarezero,itcouldbethatthosetwobitsare //leftoversfromtheencodingofdatathathadalength //oftwomodthree. NSAssert((destIndex+1)<destLen,@"ourcalcfordecodedlengthwaswrong"); destBytes[destIndex]|=decode>>2; destBytes[destIndex+1]=(decode&0x03)<<6; destIndex++; state=3; break; case3: //We'reatthelastcharacterofafour-charactercyphertextblock. //Thissetsthelowsixbitsofthethirdplaintextbyte. NSAssert(destIndex<destLen,@"ourcalcfordecodedlengthwaswrong"); destBytes[destIndex]|=decode; destIndex++; state=0; break; } } //WearedonedecodingBase-64chars.Let'sseeifweended //onabyteboundary,and/orwitherroneoustrailingcharacters. if(ch==kBase64PaddingChar){//Wegotapadchar if((state==0)||(state==1)){ return0;//Invalid'='infirstorsecondposition } if(srcLen==0){ if(state==2){//Werunoutofinputbutwestillneedanother'=' return0; } //Otherwise,weareinstate3andonlyneedthis'=' }else{ if(state==2){//needanother'=' while((ch=*srcBytes++)&&(srcLen-->0)){ if(!IsSpace(ch)) break; } if(ch!=kBase64PaddingChar){ return0; } } //state=1or2,checkifallremainpaddingisspace while((ch=*srcBytes++)&&(srcLen-->0)){ if(!IsSpace(ch)){ return0; } } } }else{ //Weendedbyseeingtheendofthestring. if(requirePadding){ //Ifwerequirepadding,thenanythingbutstate0isanerror. if(state!=0){ return0; } }else{ //Makesurewehavenopartialbyteslyingaround.Notethatwedonot //requiretrailing'=',sostates2and3areokaytoo. if(state==1){ return0; } } } //Ifthennextpieceofoutputwasvalidandgotwrittentoitmeanswegota //verycarefullycraftedinputthatappearedvalidbutcontainssometrailing //bitspastthereallength,sojusttossthething. if((destIndex<destLen)&& (destBytes[destIndex]!=0)){ return0; } returndestIndex; }
以上这篇php、java、android、ios通用的3des方法(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。