[Android Pro] DES加密 version1

时间:2023-03-09 02:36:33
[Android Pro]   DES加密 version1

reference to : http://blog.****.net/wfung_kwok/article/details/7766029

加密和解密要用同一個key

AES:

import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec; public class DES { private static final byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 }; /**
*
* @param encryptString 加密内容
* @param encryptKey 加密key
* @return
* @throws Exception
*/
public static String encryptDES(String encryptString, String encryptKey)
throws Exception {
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);
String tmp = Base64.encodeBytes(encryptString.getBytes("UTF-8"));
byte[] encryptedData = cipher.doFinal(tmp.getBytes("UTF-8"));
return Base64.encodeBytes(encryptedData);
} /**
*
* @param decryptString 解密内容
* @param encryptKey 解密key
* @return
* @throws Exception
*/
public static String decryptDES(String decryptString,String encryptKey)throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte[] decryptBytes = cipher.doFinal(Base64.decode(decryptString));
String tmp = new String(decryptBytes,"UTF-8");
return new String(Base64.decode(tmp));
} public static String getKey(){
String p = UUID.randomUUID().toString();
return SHA1.Encrypt(p).substring(0, 8);
} }

Test:

public static void testDES() throws Exception{

        String content = "AES加密";
String key = DES.getKey();
String a = DES.encryptDES(content, key);
System.out.println("DES Encrypt..." + a);
String b = DES.decryptDES(a, key);
System.out.println("DES decrypt..." + b);
}

Console:

DES Encrypt...93koM7boCXsNrH91Y0MDJA==
DES decrypt...AES加密