About DES encryption (encryption and decryption between Android and iOS and the background Java server)

Source: Internet
Author: User
Tags base64 encode

About DES encryption (encryption and decryption between Android and iOS and the background Java server)

Http://blog.sina.com.cn/s/blog_7c8dc2d50101id91.html

(2013-04-17 11:47:23)
Category: iphone development

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:

1 public class DES {
2 private static byte[] IV = {1, 2, 3, 4, 5, 6, 7, 8};

4 public static string Encryptdes (String encryptstring, String encryptkey)
5 throws Exception {
6 Ivparameterspec zeroiv = new Ivparameterspec (iv);
7 Secretkeyspec key = new Secretkeyspec (Encryptkey.getbytes (), "DES");
8 Cipher Cipher = cipher.getinstance ("des/cbc/pkcs5padding");
9 cipher.init (Cipher.encrypt_mode, Key, ZEROIV);
byte[] EncryptedData = cipher.dofinal (Encryptstring.getbytes ());
return Base64.encode (EncryptedData);
-- }
13}

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

1 public class Base64 {
2 private static final char[] Legalchars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/"
3. ToCharArray ();
4
5
public static String encode (byte[] data) {
int start = 0;
int len = data.length;
StringBuffer buf = new StringBuffer (data.length * 3/2);
15
+ int end = len-3;
+ int i = start;
int n = 0;
19
(I <= end) {
int d = ((((int) data[i]) & 0X0FF) << 16)
22 | (((((int) Data[i + 1]) & 0X0FF) << 8)
23 | (((int) Data[i + 2]) & 0X0FF);
24
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >> 6) & 63]);
Buf.append (Legalchars[d & 63]);
29
+ + = 3;
31
if (n++ >= 14) {
n = 0;
Buf.append ("");
35}
36}
37
if (i = = start + len-2) {
data[i int d = ((((int.) ((int)) & 0x0ff) << 16)
40 | (((((int) Data[i + 1]) & 255) << 8);
41
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >> 6) & 63]);
Buf.append ("=");
Len-1} else if (i = = start + * =) {
int d = (((int) data[i]) & 0X0FF) << 16;
48
Buf.append (legalchars[(d >>) & 63]);
Buf.append (legalchars[(d >>) & 63]);
Wuyi Buf.append ("= =");
52}
53
Buf.tostring return ();
55}
56}

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       
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:

1 static Byte iv[] = {1,2,3,4,5,6,7,8};
2 + (NSString *) Encryptusedes: (NSString *) plaintext key: (NSString *) key
3 {
4 NSString *ciphertext = nil;
5 const char *textbytes = [plaintext utf8string];
6 Nsuinteger datalength = [plaintext length];
7 unsigned char buffer[1024];
8 memset (buffer, 0, sizeof (char));
9 size_t numbytesencrypted = 0;
Ten Cccryptorstatus cryptstatus = Cccrypt (Kccencrypt, Kccalgorithmdes,
Kccoptionpkcs7padding,
[Key utf8string], Kcckeysizedes,
IV,
Textbytes, Datalength,
Buffer, 1024,
(&numbytesencrypted);
if (Cryptstatus = = kccsuccess) {
NSData *data = [NSData datawithbytes:buffer length: (Nsuinteger) numbytesencrypted];
ciphertext = [data base64encoding];
20}
return ciphertext;
22}

Here is a key class: the category implementation of NSData, the implementation of the category on the Internet a lot of instructions no longer tell.

1 static const char encodingtable[] = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/";
2-(NSString *) base64encoding;
3 {
4 if (self.length = = 0)
5 return @ "";
6
7 Char *characters = malloc (SELF.LENGTH*3/2);
8
9 if (characters = = NULL)
Ten return @ "";
11
int end = self.length-3;
int index = 0;
charcount int = 0;
int n = 0;
16
(index <= end) {
int d = (((int) (((char *) [self bytes]) [index]) & 0X0FF) << 16)
19 | (((int) (((char *) [self bytes]) [index + 1]) & 0X0FF) << 8)
20 | ((int) (((char *) [self bytes]) [index + 2]) & 0X0FF);
21st
characters[charcount++] = encodingtable[(d >>) & 63];
characters[charcount++] = encodingtable[(d >>) & 63];
characters[charcount++] = encodingtable[(d >> 6) & 63];
characters[charcount++] = encodingtable[d & 63];
26
Index + = 3;
28
if (n++ >= 14)
30 {
n = 0;
[characters[charcount++] = ";
33}
34}
35
if (index = = self.length-2)
37 {
$ int d = (((int) (((char *) [self bytes]) [index]) & 0X0FF) << 16)
39 | (((int) (((char *) [self bytes]) [index + 1]) & 255) << 8);
characters[charcount++] = encodingtable[(d >>) & 63];
characters[charcount++] = encodingtable[(d >>) & 63];
characters[charcount++] = encodingtable[(d >> 6) & 63];
characters[charcount++] = ' = ';
44}
-else if (index = = self.length-1)
46 {
int d = ((int) (((char *) [self bytes]) [index]) & 0X0FF) << 16;
characters[charcount++] = encodingtable[(d >>) & 63];
characters[charcount++] = encodingtable[(d >>) & 63];
characters[charcount++] = ' = ';
Wuyi characters[charcount++] = ' = ';
52}
NSString * Rtnstr = [[NSString alloc] initwithbytesnocopy:characters length:charcount encoding:nsutf8stringencoding Freewhendone:yes];
RTNSTR return;
55}

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

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.

My decryption algorithm is as follows:

1 private static byte[] IV = {1, 2, 3, 4, 5, 6, 7, 8};    
2 public static string Decryptdes (String decryptstring, String decryptkey)
3 throws Exception {
4 byte[] Bytemi = Base64.decode (decryptstring);
5 Ivparameterspec zeroiv = new Ivparameterspec (iv);
6 Secretkeyspec key = new Secretkeyspec (Decryptkey.getbytes (), "DES");
7 Cipher Cipher = cipher.getinstance ("des/cbc/pkcs5padding");
8 Cipher.init (Cipher.decrypt_mode, Key, ZEROIV);
9 byte decrypteddata[] = cipher.dofinal (Bytemi);

return new String (Decrypteddata);
-- }

The Decode method for Base64 is as follows:

1 public static byte[] Decode (String s) {
2
3 Bytearrayoutputstream bos = new Bytearrayoutputstream ();
4 try {
5 decode (S, BOS);
6} catch (IOException e) {
7 throw new RuntimeException ();
8}
9 byte[] decodedbytes = Bos.tobytearray ();
Ten try {
Bos.close ();
The BOS = NULL;
* catch (IOException ex) {
System.err.println ("Error while decoding BASE64:" + ex.tostring ());
15}
Decodedbytes return;
17}
private static void Decode (String s, OutputStream os) throws IOException {
int i = 0;
20
int len = S.length ();
22
(true) {
while (i < Len && S.charat (i) <= ")
i++;
26
if (i = = len)
break;
29
int tri = (decode (S.charat (i)) << 18)
+ (Decode (S.charat (i + 1)) << 12)
+ (Decode (S.charat (i + 2)) << 6)
+ (Decode (S.charat (i + 3)));
34
Os.write (Tri >> & 255);
if (S.charat (i + 2) = = ' = ')
PNS break;
Os.write (Tri >> 8) & 255);
if (S.charat (i + 3) = = ' = ')
a break;
Os.write (Tri & 255);
42
i + = 4;
44}
45}
The private static int decode (char c) {
if (c >= ' A ' && C <= ' Z ')
return ((int) c)-65;
$ else if (c >= ' a ' && c <= ' z ')
return ((int) c)-97 + 26;
if (c >= ' 0 ' && C <= ' 9 ')
return ((int) c)-48 + 26 + 26;
+ Else
Switch (c) {
Case ' + ':
Return 62;
The case '/':
63;
Case ' = ':
return 0;
The default:
RuntimeException throw New ("Unexpected code:" + C);
63}
64}

The above realizes the decryption of the ciphertext after DES encryption.

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=
Share:

11

Like

1

Gift Pen

Read(7688)┊ Comments (2)┊ Collection (4) ┊ prohibited reprint ┊ like ┊ Print ┊ report Previous: Mac configuration Android development environment variables and tool installation diagramNext : iOS advanced interview

About DES encryption (encryption and decryption between Android and iOS and the background Java server)

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.