JAVA, PHP, C#object-c universal des encryption and decryption

Source: Internet
Author: User
JAVA, PHP, C #, Object-c Universal des encryption and decryption

JAVA, Android:

Package Com.example.aric.test;import Javax.crypto.cipher;import Javax.crypto.secretkey;import Javax.crypto.secretkeyfactory;import Javax.crypto.spec.deskeyspec;import Javax.crypto.spec.IvParameterSpec;    Import Android.util.base64;public class DES {public final static String des_key_string = "Absujsuu"; public static string encrypt (String message, String key) throws Exception {Cipher Cipher = cipher.getinstance ("DES        /cbc/pkcs5padding ");        Deskeyspec Deskeyspec = new Deskeyspec (key.getbytes ("UTF-8"));        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");        Secretkey Secretkey = Keyfactory.generatesecret (Deskeyspec);        Ivparameterspec IV = new Ivparameterspec (key.getbytes ("UTF-8"));         Cipher.init (Cipher.encrypt_mode, Secretkey, iv);    Return EncodeBase64 (Cipher.dofinal (Message.getbytes ("UTF-8")); public static string decrypt (string message, String key) throws Exception {byte[] bytesrc = decodeBase64 (mess Age);//converthexstring (message);        Cipher Cipher = cipher.getinstance ("des/cbc/pkcs5padding");        Deskeyspec Deskeyspec = new Deskeyspec (key.getbytes ("UTF-8"));        Secretkeyfactory keyfactory = secretkeyfactory.getinstance ("DES");        Secretkey Secretkey = Keyfactory.generatesecret (Deskeyspec);         Ivparameterspec IV = new Ivparameterspec (key.getbytes ("UTF-8"));        Cipher.init (Cipher.decrypt_mode, Secretkey, iv);        byte[] Retbyte = cipher.dofinal (BYTESRC);    return new String (Retbyte);        } public static byte[] Converthexstring (String ss) {byte digest[] = new Byte[ss.length ()/2];            for (int i = 0; i < digest.length; i++) {String byteString = ss.substring (2 * I, 2 * i + 2);            int bytevalue = Integer.parseint (byteString, 16);        Digest[i] = (byte) bytevalue;    } return digest;        } public static String tohexstring (byte b[]) {StringBuffer hexstring = new StringBuffer (); for (int i = 0;i < b.length;            i++) {String plaintext = integer.tohexstring (0xFF & B[i]);            if (Plaintext.length () < 2) plaintext = "0" + plaintext;        Hexstring.append (plaintext);    } return hexstring.tostring ();    } public static String encodeBase64 (byte[] b) {return base64.encodetostring (b, Base64.default); } public static byte[] DecodeBase64 (String base64string) {return Base64.decode (base64string, Base64.defaul    T); }}

?

Php:

Class Jodes {private static $_instance = NULL; /** * @return Jodes */public static function share () {if (Is_null (self::$_instance)) {Self        :: $_instance = new Jodes ();    } return self::$_instance;    }/** * Encrypt * @param string $STR strings to be processed * @param-string $key encryption key, 8-byte length * @return String * *        Public function encode ($STR, $key) {$size = Mcrypt_get_block_size (Mcrypt_des, MCRYPT_MODE_CBC);        $str = $this->pkcs5pad ($str, $size);        $AAA = MCRYPT_CBC (Mcrypt_des, $key, $str, Mcrypt_encrypt, $key);        $ret = Base64_encode ($AAA);    return $ret;    }/** * Decrypts * @param string $str to be processed * @param strings $key decrypted key, 8 bytes Length * @return String */        Public function decode ($STR, $key) {$strBin = Base64_decode ($STR);        $str = MCRYPT_CBC (Mcrypt_des, $key, $strBin, Mcrypt_decrypt, $key);        $str = $this->pkcs5unpad ($STR);    return $str; } function Hex2bin ($hexData) {$binData = "";        for ($i = 0; $i < strlen ($hexData); $i + = 2) {$binData. = Chr (Hexdec (substr ($hexData, $i, 2)));    } return $binData;        } function Pkcs5pad ($text, $blocksize) {$pad = $blocksize-(strlen ($text)% $blocksize); Return $text.    Str_repeat (Chr ($pad), $pad);        } function Pkcs5unpad ($text) {$pad = Ord ($text {strlen ($text)-1});        if ($pad > strlen ($text)) return false;        if (strspn ($text, Chr ($pad), strlen ($text)-$pad)! = $pad) return false;    Return substr ($text, 0,-1 * $pad); }}

? C#:

public class Mydes {///// des encryption method //////Plaintext///Secret key///Vector///
 
  
   Ciphertext
  
         public static string Encode (string source, String _deskey) {StringBuilder sb = new Stringbuilde            R (); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider ()) {byte[] key = Asciiencodi Ng. Ascii.                GetBytes (_deskey);                Byte[] IV = ASCIIEncoding.ASCII.GetBytes (_deskey);                byte[] Databytearray = Encoding.UTF8.GetBytes (source); Des.                Mode = System.Security.Cryptography.CipherMode.CBC; Des.                key = key;                DES.IV = IV;                String encrypt = ""; using (MemoryStream ms = new MemoryStream ()) using (CryptoStream cs = new CryptoStream (MS, DES). CreateEncryptor (), cryptostreammode.write)) {cs.                    Write (Databytearray, 0, databytearray.length); Cs.                    FlushFinalBlock (); Encrypt = convert.tobase64string (Ms.                ToArray ()); } return encrypt;           }        }        ///  /// for des decryption. /// ///The Base64 string to decrypt///Key, and must be 8 bits.///
 
  
   the decrypted string. 
  
 public static string Decode (string source, String SKey) {byte[] Inputbytearray = System.Convert.FromBas            E64string (source);//encoding.utf8.getbytes (source); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider ()) {des.                Key = ASCIIEncoding.ASCII.GetBytes (SKey);                DES.IV = ASCIIEncoding.ASCII.GetBytes (SKey);                System.IO.MemoryStream ms = new System.IO.MemoryStream (); using (CryptoStream cs = new CryptoStream (MS, Des. CreateDecryptor (), cryptostreammode.write)) {cs.                    Write (Inputbytearray, 0, inputbytearray.length); Cs.                    FlushFinalBlock (); Cs.                Close (); } string str = Encoding.UTF8.GetString (MS.                ToArray ()); Ms.                Close ();            return str; }        }    }

?

Object-c:

/*** JoDes.h ***/#import
 
  #import
  
   #import
   
    
@interface jodes:nsobject+ (NSString *) Encode: (NSString *) str key: (NSString *) key;+ (NSString *) decode: (NSString *) St R key: (NSString *) key; @end/*** jodes.m ***///xlencrythelper.m//newholdgold//Created by Mr.liao on 2016-01-22.//Co Pyright (c) 2016 Nomanland. All rights reserved. #import "JoDes.h" @interface jodes () + (NSString *) encodebase64withstring: (NSString *) strdata;+ ( NSString *) Encodebase64withdata: (NSData *) objdata;+ (NSData *) decodebase64withstring: (NSString *) strBase64;+ ( NSString *) Docipher: (NSString *) stextin key: (NSString *) SKey context: (ccoperation) Encryptordecrypt;     @end @implementation jodes+ (NSString *) Encode: (NSString *) str key: (NSString *) key{//docipher cannot compile Chinese characters, so URL encode    nsmutablestring* str1 = [Jodes urlencode:str];    nsmutablestring* encode = [nsmutablestring stringwithstring:[jodes docipher:str1 Key:key Context:kccencrypt]];    [Jodes Formatspecialcharacters:encode]; return encode;} + (NSString *) decode: (NSString *) Str kEY: (NSString *) key{nsmutablestring *str1 = [nsmutablestring stringwithstring:str];    [Jodes REFORMATSPECIALCHARACTERS:STR1];    NSString *rt = [jodes docipher:str1 key:key Context:kccdecrypt]; return RT;} + (nsmutablestring *) UrlEncode: (nsstring*) str{nsmutablestring* encodestr = [nsmutablestring stringWithString:[str str    Ingbyaddingpercentescapesusingencoding:nsutf8stringencoding]]; [Encodestr replaceoccurrencesofstring:@ "+" withstring:@ "%2b" Options:nswidthinsensitivesearch range:NSMakeRange (0,    [Encodestr length]); [Encodestr replaceoccurrencesofstring:@ "/" withstring:@ "%2f" Options:nswidthinsensitivesearch range:NSMakeRange (0,    [Encodestr length]); return ENCODESTR;} + (void) Formatspecialcharacters: (nsmutablestring *) str{[str replaceoccurrencesofstring:@ "+" withstring:@ "$$"    Options:nswidthinsensitivesearch range:nsmakerange (0, [str length])]; [Str replaceoccurrencesofstring:@ "/" withstring:@ "@@" Options:nswidthinsensitivesearch range:nsmakerange (0, [str lenGTH])];} + (void) Reformatspecialcharacters: (nsmutablestring *) str{[str replaceoccurrencesofstring:@ "$$" withstring:@ "+"    Options:nswidthinsensitivesearch range:nsmakerange (0, [str length])]; [Str replaceoccurrencesofstring:@ "@@" withstring:@ "/" Options:nswidthinsensitivesearch range:nsmakerange (0, [str Length])];} + (NSString *) encodebase64withstring: (NSString *) strdata {return [jodes encodebase64withdata:[strdata DataUsingEncodi Ng:nsutf8stringencoding]];}    + (NSString *) Encodebase64withdata: (NSData *) objdata {nsstring *encoding = nil;    unsigned char *encodingbytes = NULL;        @try {static char encodingtable[64] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/";        Static Nsuinteger paddingtable[] = {0,2,1};        Nsuinteger datalength = [Objdata length];        Nsuinteger encodedblocks = (DATALENGTH * 8)/24;        Nsuinteger padding = paddingtable[datalength% 3];        if (padding > 0) encodedblocks++; Nsuinteger EncodedlengtH = encodedblocks * 4;        Encodingbytes = malloc (encodedlength);            if (encodingbytes! = NULL) {Nsuinteger rawbytestoprocess = datalength;            Nsuinteger rawbaseindex = 0;            Nsuinteger encodingbaseindex = 0;            unsigned char *rawbytes = (unsigned char *) [objdata bytes];            unsigned char rawByte1, rawByte2, RawByte3;                while (rawbytestoprocess >= 3) {rawByte1 = Rawbytes[rawbaseindex];                RawByte2 = rawbytes[rawbaseindex+1];                RawByte3 = rawbytes[rawbaseindex+2];                Encodingbytes[encodingbaseindex] = encodingtable[((rawByte1 >> 2) & 0x3F)]; Encodingbytes[encodingbaseindex+1] = encodingtable[((rawByte1 << 4) & 0x30) |                ((RawByte2 >> 4) & 0x0F)]; ENCODINGBYTES[ENCODINGBASEINDEX+2] = encodingtable[((rawByte2 << 2) & 0x3C) |                ((RawByte3 >> 6) & 0x03)]; Encodingbytes[encodingbasEINDEX+3] = encodingtable[(RawByte3 & 0x3F)];                Rawbaseindex + = 3;                Encodingbaseindex + = 4;            Rawbytestoprocess-= 3;            } rawByte2 = 0;                Switch (datalength-rawbaseindex) {case 2:rawbyte2 = rawbytes[rawbaseindex+1];                    Case 1:rawbyte1 = Rawbytes[rawbaseindex];                    Encodingbytes[encodingbaseindex] = encodingtable[((rawByte1 >> 2) & 0x3F)]; Encodingbytes[encodingbaseindex+1] = encodingtable[((rawByte1 << 4) & 0x30) |                    ((RawByte2 >> 4) & 0x0F)];                    ENCODINGBYTES[ENCODINGBASEINDEX+2] = encodingtable[((rawByte2 << 2) & 0x3C)];            We can skip rawByte3 since we have the a partial block it would always is 0 break; }//Compute location from where to begin inserting padding, it may overwrite some bytes from the partial block encoding//If their value is 0 (cases 1-2).            Encodingbaseindex = encodedlength-padding;            while (padding--> 0) {encodingbytes[encodingbaseindex++] = ' = '; } encoding = [[NSString alloc] initwithbytes:encodingbytes length:encodedlength encoding:nsasciistringencoding]        ;        }} @catch (NSException *exception) {encoding = nil;    NSLog (@ "Warning:error occured while tring to encode base data:%@", exception);        } @finally {if (encodingbytes! = NULL) {free (encodingbytes); }} return encoding;}    + (NSData *) decodebase64withstring: (NSString *) strBase64 {NSData *data = nil;    unsigned char *decodedbytes = NULL; @try {#define __ 255 static char decodingtable[256] = {__,__,__,__, __,__,__,__, __,__,__,__, __,__,__, __,//0x00-0x0f __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,//0x10-0x1F __,__,__,__, __,__,__,__, __,__,__,62, __,__,__,63,//0x20-0x2f 52,53,54,55, 56,57,58,59, 60,            61,__,__, __, 0,__,__,//0x30-0x3f __, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,//0x40-0x4f 15,16,17,18, 19,20,21,22, 23,24,25,__, __,__,__,__,//0x50-0x5f __,26,27,28, 29,30,31,32, 33,34,35,3            6, 37,38,39,40,//0x60-0x6f 41,42,43,44, 45,46,47,48, 49,50,51,__, __,__,__,__,//0x70-0x7f __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,//0x80-0x8f __,__,__,__, __,__,__,__, __,__,__,__, __,_ _,__,__,//0x90-0x9f __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,//0xa0-0xaf __,__,_ _,__, __,__,__,__, __,__,__,__, __,__,__,__,//0XB0-0XBF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__ ,//0XC0-0XCF __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,//0xd0-0xdf __,__,__,__, _ _,__,__,__, __,__,__,__, __,__,__,__,//0xe0-0xef __,__,__,__, __,__,__,__, __,__,__,__, __,__,__,__,//0xf0-0xff};        StrBase64 = [strBase64 stringbyreplacingoccurrencesofstring:@ "=" withstring:@ ""];        NSData *encodeddata = [StrBase64 datausingencoding:nsasciistringencoding];           unsigned char *encodedbytes = (unsigned char *) [encodeddata bytes];        Nsuinteger encodedlength = [Encodeddata length];        Nsuinteger encodedblocks = (encodedlength+3) >> 2;                 Nsuinteger expecteddatalength = encodedblocks * 3;             unsigned char decodingblock[4];        Decodedbytes = malloc (expecteddatalength);            if (decodedbytes! = NULL) {Nsuinteger i = 0;            Nsuinteger j = 0;            Nsuinteger k = 0;            unsigned char c;                while (I < encodedlength) {c = decodingtable[encodedbytes[i]];                i++;  if (c! = __) {DECODINGBLOCK[J] = C;                  j + +; if (j = = 4) {Decodedbytes[k] = (Decodingblock[0] << 2) |                        (Decodingblock[1] >> 4); Decodedbytes[k+1] = (decodingblock[1] << 4) |                        (Decodingblock[2] >> 2); DECODEDBYTES[K+2] = (decodingblock[2] << 6) |                        (Decodingblock[3]);                        j = 0;                    K + = 3;                }}}//Process left through bytes, if any if (j = = 3) { Decodedbytes[k] = (Decodingblock[0] << 2) |                (Decodingblock[1] >> 4); Decodedbytes[k+1] = (decodingblock[1] << 4) |                (Decodingblock[2] >> 2);            K + = 2; } else if (j = = 2) {Decodedbytes[k] = (Decodingblock[0] << 2) |                (Decodingblock[1] >> 4);            K + = 1; } data = [[NSData alloc] Initwithbytes:decodedbytes length:k];        }} @catch (NSException *exception) {data = nil;    NSLog (@ "Warning:error occured while decoding base + string:%@", exception);        } @finally {if (decodedbytes! = NULL) {free (decodedbytes);     }} return data; } + (NSString *) Docipher: (NSString *) stextin key: (NSString *) SKey context: (ccoperation) Encryptordecrypt         {nsstringencoding EnC = nsutf8stringencoding;    Nsmutabledata *dtextin;    if (Encryptordecrypt = = kccdecrypt) {dtextin = [[Jodes decodebase64withstring:stextin] mutablecopy];    } else{dtextin = [[Stextin Datausingencoding:enc] mutablecopy];    } nsmutabledata * Dkey = [[SKey Datausingencoding:enc] mutablecopy];    [Dkey Setlength:kccblocksizedes];    uint8_t *bufferptr1 = NULL;    size_t bufferPtrSize1 = 0;    size_t movedBytes1 = 0;    uint8_t Iv[kccblocksizedes];    memset (void *) IV, 0x0, (size_t) sizeof (iv)); Byte iv[] = {0x12,0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};    BufferPtrSize1 = ([stextin length] + kcckeysizedes) & ~ (KCCKEYSIZEDES-1);    BUFFERPTR1 = malloc (bufferPtrSize1 * sizeof (uint8_t));         memset (void *) BUFFERPTR1, 0x00, bufferPtrSize1); Cccrypt (Encryptordecrypt,//ccoperation op kccalgorithmdes,//Ccalgorithm ALG Kccoptionpkcs7paddin            g,//ccoptions options [dkey bytes],//const void *key [Dkey length],//size_t keylength// [Dkey bytes],//const void *iv [Dtextin bytes],//const void *datain [Dtextin length],//s ize_t datainlength (void *) BUFFERPTR1,//void *dataout bufferPtrSize1,//size_t Dataoutavailab         Le &movedbytes1);    [Dtextin release];         [Dkey release];    NSString * SRESULT; if (Encryptordecrypt = = kccdecrypt) {sresult = [[NSString alloc] Initwithdata:[nsdata datawithbytes:bufferptr1 Leng  TH:MOVEDBYTES1] Encoding:enc];      Free (BUFFERPTR1);        } else {NSData *dresult = [NSData datawithbytes:bufferptr1 length:movedbytes1];        Free (BUFFERPTR1);    Sresult = [Jodes Encodebase64withdata:dresult]; } return sresult;} @end
   
  
 

?

?

?

?

  • Related Article

    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.