about how objective-c and Java are consistent in DES encryption

Source: Internet
Author: User
Tags base64



Reprinted from: http://www.cnblogs.com/janken/archive/2012/04/05/2432930.html






Recently made a mobile project, there is a server and client type of project, the client is to log in, the password to use DES encryption, the server is developed in Java, the client to support multi-platform (Android, iOS), while processing the IOS DES encryption encountered some problems , the original tune will not be the same as the android generated ciphertext. Finally a sudden idea let me find the problem, and now the code to summarize, in case I look later.



First, the Java side of DES encryption implementation, the code is as follows:


Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code


The code above uses a BASE64 encoding class whose code is implemented in the following way:


Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code


The above is the Java side of the DES encryption method of all the implementation process.



I also wrote a method of converting byte binary to 16, so that when debugging, the contents of a byte array that is encrypted with a printout are used, and this method is not an encrypted part, but is used for debugging purposes only:


1     
2      
3      * @return  String
4 */  
5 public     static String parsebyte2hexstr (byte buf[]) {  
6             StringBuffer sb = new StringBuffer ();  
7 for             (int i = 0; i < buf.length; i++) {  
8                     String hex = integer.tohexstring (Buf[i] & 0xFF);  
9                     if (hex.length () = = 1) {  
Ten                             hex = ' 0 ' + hex;  
One                     }  
                     Sb.append (Hex.touppercase ());  
-             }  
             return sb.tostring ();  
     }


The following is the DES encryption algorithm implemented by OBJECTIVE-C on iOS:


Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code


The following is also a binary conversion of objective-c to 16 binary method, but also for the purpose of testing easy to read write:


1 + (NSString *) parsebyte2hexstring: (Byte *) bytes
2 {
3 nsmutablestring *hexstr = [[nsmutablestring alloc]init];
4 int i = 0;
5 if (bytes)
6 {
7 while (bytes[i]! = ' + ')
8 {
9 NSString *hexbyte = [NSString stringwithformat:@ "%x", Bytes[i] & 0xff];///16 binary number
if ([HexByte length]==1)
One by one [hexstr appendformat:@ "0%@", HexByte];
Else
[Hexstr appendformat:@ "%@", HexByte];
14
i++;
16}
17}
NSLog (@ "bytes 16 binary number is:%@", hexstr);
return hexstr;
20}
21st
+ (NSString *) parsebytearray2hexstring: (byte[]) bytes
23 {
nsmutablestring *hexstr = [[nsmutablestring alloc]init];
int i = 0;
if (bytes)
27 {
while (bytes[i]! = ' + ')
29 {
NSString *hexbyte = [NSString stringwithformat:@ "%x", Bytes[i] & 0xff];///16 binary number
if ([HexByte length]==1)
[Hexstr appendformat:@ "0%@", HexByte];
+ Else
[Hexstr appendformat:@ "%@", HexByte];
35
i++;
37}
38}
NSLog (@ "bytes 16 binary number is:%@", hexstr);
HEXSTR return;
41}


The package that contains the above encryption method is commoncrypto/commoncryptor.h.

The above implementation of OBJECTIVE-C and Java under the same plaintext and key in the case of generating the same plaintext algorithm.



The BASE64 algorithm can be written in your own, not necessarily using the one I provide. When decrypting, we also use BASE64 to convert the ciphertext.



The BASE64 algorithm under iOS is behind.



The decryption algorithm under Java is as follows:


Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code


The Decode method for Base64 is as follows:


Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code


Des decryption algorithm under OBJECTIVE-C:


1 +(NSString *)decryptUseDES:(NSString *)cipherText key:(NSString *)key
 2 {
 3     NSString *plaintext = nil;
 4     NSData *cipherdata = [Base64 decode:cipherText];
 5     unsigned char buffer[1024];
 6     memset(buffer, 0, sizeof(char));
 7     size_t numBytesDecrypted = 0;
 8     CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES,
 9                                           kCCOptionPKCS7Padding,
10                                           [key UTF8String], kCCKeySizeDES,
11                                           iv,
12                                           [cipherdata bytes], [cipherdata length],
13                                           buffer, 1024,
14                                           &numBytesDecrypted);
15     if(cryptStatus == kCCSuccess) {
16         NSData *plaindata = [NSData dataWithBytes:buffer length:(NSUInteger)numBytesDecrypted];
17         plaintext = [[NSString alloc]initWithData:plaindata encoding:NSUTF8StringEncoding];
18     }
19     return plaintext;
20 }


The following is the objective-c implementation of the Base64 tool object, of course you can also choose to use Google's Base64 class--gtmbase64 (very powerful), the initial test using GTMBASE64 and use I wrote this Base64 effect is the same.


 1 static const char encodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2 
  3 @interface Base64()
  4 +(int)char2Int:(char)c;
  5 @end
  6 
  7 @implementation Base64
  8 
  9 +(NSString *)encode:(NSData *)data
 10 {
 11     if (data.length == 0)
 12         return nil;
 13     
 14     char *characters = malloc(data.length * 3 / 2);
 15     
 16     if (characters == NULL)
 17         return nil;
 18     
 19     int end = data.length - 3;
 20     int index = 0;
 21     int charCount = 0;
 22     int n = 0;
 23     
 24     while (index <= end) {
 25         int d = (((int)(((char *)[data bytes])[index]) & 0x0ff) << 16)
 26         | (((int)(((char *)[data bytes])[index + 1]) & 0x0ff) << 8)
 27         | ((int)(((char *)[data bytes])[index + 2]) & 0x0ff);
 28         
 29         characters[charCount++] = encodingTable[(d >> 18) & 63];
 30         characters[charCount++] = encodingTable[(d >> 12) & 63];
 31         characters[charCount++] = encodingTable[(d >> 6) & 63];
 32         characters[charCount++] = encodingTable[d & 63];
 33         
 34         index += 3;
 35         
 36         if(n++ >= 14)
 37         {
 38             n = 0;
 39             characters[charCount++] = ‘ ‘;
 40         }
 41     }
 42     
 43     if(index == data.length - 2)
 44     {
 45         int d = (((int)(((char *)[data bytes])[index]) & 0x0ff) << 16)
 46         | (((int)(((char *)[data bytes])[index + 1]) & 255) << 8);
 47         characters[charCount++] = encodingTable[(d >> 18) & 63];
 48         characters[charCount++] = encodingTable[(d >> 12) & 63];
 49         characters[charCount++] = encodingTable[(d >> 6) & 63];
 50         characters[charCount++] = ‘=‘;
 51     }
 52     else if(index == data.length - 1)
 53     {
 54         int d = ((int)(((char *)[data bytes])[index]) & 0x0ff) << 16;
 55         characters[charCount++] = encodingTable[(d >> 18) & 63];
 56         characters[charCount++] = encodingTable[(d >> 12) & 63];
 57         characters[charCount++] = ‘=‘;
 58         characters[charCount++] = ‘=‘;
 59     }
 60     NSString * rtnStr = [[NSString alloc] initWithBytesNoCopy:characters length:charCount encoding:NSUTF8StringEncoding freeWhenDone:YES];
 61     return rtnStr;
 62 
 63 }
 64 
 65 +(NSData *)decode:(NSString *)data
 66 {
 67     if(data == nil || data.length <= 0) {
 68         return nil;
 69     }
 70     NSMutableData *rtnData = [[NSMutableData alloc]init];
 71     int slen = data.length;
 72     int index = 0;
 73     while (true) {
 74         while (index < slen && [data characterAtIndex:index] <= ‘ ‘) {
 75             index++;
 76         }
 77         if (index >= slen || index  + 3 >= slen) {
 78             break;
 79         }
 80 
 81         int byte = ([self char2Int:[data characterAtIndex:index]] << 18) + ([self char2Int:[data characterAtIndex:index + 1]] << 12) + ([self char2Int:[data characterAtIndex:index + 2]] << 6) + [self char2Int:[data characterAtIndex:index + 3]];
 82         Byte temp1 = (byte >> 16) & 255;
 83         [rtnData appendBytes:&temp1 length:1];
 84         if([data characterAtIndex:index + 2] == ‘=‘) {
 85             break;
 86         }
 87         Byte temp2 = (byte >> 8) & 255;
 88         [rtnData appendBytes:&temp2 length:1];
 89         if([data characterAtIndex:index + 3] == ‘=‘) {
 90             break;
 91         }
 92         Byte temp3 = byte & 255;
 93         [rtnData appendBytes:&temp3 length:1];
 94         index += 4;
 95 
 96     }
 97     return rtnData;
 98 }
 99 
100 +(int)char2Int:(char)c
101 {
102     if (c >= ‘A‘ && c <= ‘Z‘) {
103         return c - 65;
104     } else if (c >= ‘a‘ && c <= ‘z‘) {
105         return c - 97 + 26;
106     } else if (c >= ‘0‘ && c <= ‘9‘) {
107         return c - 48 + 26 + 26;
108     } else {
109         switch(c) {
110             case ‘+‘:
111                 return 62;
112             case ‘/‘:
113                 return 63;
114             case ‘=‘:
115                 return 0;
116             default:
117                 return -1;
118         }
119     }
120 }
121 
122 @end


This and the Java side of the Base64 is an algorithm, only according to the characteristics of the language has a little change.






The Java side Test code is as follows:


1     String plaintext = "ABCD";
2     String ciphertext = des.encryptdes (plaintext, "20120401");
3     System.out.println ("Clear text:" + plaintext);
4     System.out.println ("Key:" + "20120401");
5     System.out.println ("ciphertext:" + ciphertext);
6     System.out.println ("After decryption:" + des.decryptdes (ciphertext, "20120401"));


Output Result:


PlainText: ABCD
Key: 20120401
Ciphertext: w7hr43/usys=
After decryption: ABCD



The test code for the Objective-c end is as follows:


1     nsstring *plaintext = @ "ABCD";
2     nsstring *ciphertext = [encryptutil encryptusedes:plaintext key:@ "20120401"];
3     NSLog (@ "plaintext:%@", plaintext);
4     NSLog (@ "secret key:%@", @ "20120401");
5     NSLog (@ "Ciphertext:%@", ciphertext);


Output Result:


1 2012-04-05 12:00:47.348 testencrypt[806:f803] PlainText: ABCD
2 2012-04-05 12:00:47.350 testencrypt[806:f803] secret key: 20120401
3 2012-04-05 12:00:47.350 testencrypt[806:f803] Ciphertext: w7hr43/usys=




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.