There are a lot of online demos, but they are basically just a little bit confusing (including me ). Why? When I tried to encrypt the two platforms separately, I found that android DES encryption and Java DES encryption programs cannot interwork. The encryption results are different, not to mention the encrypted input of the Android platform as the decryption output of Java des. In this way, the client and the server cannot communicate. I posted a post on the Internet and asked many people, but they were not satisfied with the answer.
Another colleague from the department spoke to me today to solve this problem.
The best way to call the DES encryption algorithm package is the following two sentences:
Cipher cipher = cipher. getinstance ("des/CBC/pkcs5padding ");
Cipher. INIT (Cipher. encrypt_mode, key, zeroiv );
CBC is the working mode. Des has four modes: Electronic cryptographic mode (ECB), encrypted group connection mode (CBC), encrypted feedback mode (CFB), and output feedback mode (ofB,
Pkcs5padding is the filling mode, and there are other filling modes:
Then, cipher. INIT () has three parameters: cipher. encrypt_mode, key, zeroiv, zeroiv is the initialization vector, and an 8-character array.
The working mode, filling mode, and initialization vector are all three factors. Otherwise, if you do not specify it, the program will call the default implementation. The problem arises, which is related to the platform. It is no wonder that the "DES encryption results are inconsistent" search on the Internet shows N-Plus web page results. (I didn't specify IV before, and I was tortured for 2 weeks)
The source code is as follows (I have not changed a line of code from Java platform to Android platform ):
In addition, the encrypted results are generally transmitted in base64 encoding.
Java platform:
Main Program
public class testDES {/** * @param args * @throws Exception */public static void main(String[] args) throws Exception {// TODO Auto-generated method stubString key = "12345678";String text = "12345678";String result1 = DES.encryptDES(text,key);String result2 = DES.decryptDES(result1, key);System.out.println(result1);System.out.println(result2);}}
Des encryption class used
import javax.crypto.Cipher;import javax.crypto.spec.IvParameterSpec;import javax.crypto.spec.SecretKeySpec;
public class DES {private static byte[] iv = {1,2,3,4,5,6,7,8};public static String encryptDES(String encryptString, String encryptKey) throws Exception {//IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);IvParameterSpec zeroIv = new IvParameterSpec(iv);SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);byte[] encryptedData = cipher.doFinal(encryptString.getBytes()); return Base64.encode(encryptedData);}public static String decryptDES(String decryptString, String decryptKey) throws Exception {byte[] byteMi = new Base64().decode(decryptString);IvParameterSpec zeroIv = new IvParameterSpec(iv);//IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);byte decryptedData[] = cipher.doFinal(byteMi); return new String(decryptedData);}}
Used base64 tool class:
Import Java. io. bytearrayoutputstream; import Java. io. ioexception; import Java. io. outputstream; public class base64 {Private Static final char [] legalchars = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789 + /". tochararray ();/*** data [] encoding * @ Param data * @ return */public static string encode (byte [] data) {int start = 0; int Len = data. length; stringbuffer Buf = new stringbuffer (data. length * 3/2); int end = len-3; int I = start; int n = 0; while (I <= END) {int d = (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) {int d = (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 ("=");} else if (I = start + len-1) {int d = (INT) data [I]) & 0x0ff) <16; Buf. append (legalchars [(d> 18) & 63]); Buf. append (legalchars [(d> 12) & 63]); Buf. append ("=");} return Buf. tostring ();} 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; else if (C> = '0' & C <= '9') Return (INT) c)-48 + 26 + 26; else switch (c) {Case '+': Return 62; Case '/': return 63; Case '=': Return 0; default: Throw new runtimeexception ("unexpected code: "+ C) ;}}/*** decodes the given base64 encoded string to a new byte array. the Byte * array holding the decoded data is returned. */public static byte [] Decode (string s) {bytearrayoutputstream Bos = new bytearrayoutputstream (); try {decode (S, Bos);} catch (ioexception E) {Throw new runtimeexception ();} byte [] decodedbytes = Bos. tobytearray (); try {Bos. close (); Bos = NULL;} catch (ioexception ex) {system. err. println ("error while decoding base64:" + ex. tostring ();} return decodedbytes;} Private Static void decode (string S, outputstream OS) throws ioexception {int I = 0; int Len = S. length (); While (true) {While (I <Len & S. charat (I) <= '') I ++; if (I = Len) break; int tri = (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 ;}}}
Main functions of the adnroid platform:
public class main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); String key = "12345678";String text = "12345678";try {String result1 = DES.encryptDES(text,key);String result2 = DES.decryptDES(result1, key);Log.i("DES encode text is ", result1);Log.i("DES encode text is ", result2);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();} }}
You can view the results by viewing the log.
The results of the two platforms are the same:
Encryption result: x2p9uo45tzk6ntu6w7ev + q =
Decryption result: 12345678