注意,这里使用PKCS5Padding算法,密钥只能是8个字节。
因为在ios中,支持的DES加密算法是kCCOptionPKCS7Padding |kCCOptionECBMode。在使用PKCS7Padding,它的密钥可以是8个字节,也可以不是。如果密钥不是8个字节的话,那么JAVA端的PKCS5Padding算法就不能解密了。
我对DES算法也了解甚少,这里只说一下自己的理解。在密钥都是8个字节的前提下,PKCS7Padding和PKCS5Padding的加密和解密是通用的。因此,不必纠结于两个算法不一样怎么办,如何让IOS也支持JAVA的加密算法,甚至不用DES了等等。
我觉得都没必要,我们做的是工程,一种需求的实现方法。只要遵守密钥为8个字节的约定,就能实现需求,又何必去找其他的算法。好吧,我理解你觉得这样不安全,其实也没绝对的安全。
回到正题,JAVA中DES加密实现方法如下:
private static byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8};
public static byte[]encryptDES(String encryptString, String encryptKey)
throws Exception {
System.out.println("willencryptedData with UTF-8 encoding =" +parseByte2HexStr(encryptString.getBytes("UTF-8")));
IvParameterSpec zeroIv =new IvParameterSpec(iv);
SecretKeySpec key = newSecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher =Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key, zeroIv);
byte[] encryptedData =cipher.doFinal(encryptString.getBytes("UTF-8"));
System.out.println("didencryptedData =" +parseByte2HexStr(encryptedData));
return encryptedData;
}
public static StringencryptDESwithBase64(String encryptString,String encryptKey) throws Exception
{
returnXYBase64.encode(encryptDES(encryptString,encryptKey));
}
JAVA中DES解密实现方法如下:
public static String decryptDES(byte[] encryptedData, String decryptKey)
throws Exception {
System.out.println("willdecryptedData =" + parseByte2HexStr(encryptedData));
IvParameterSpec zeroIv =new IvParameterSpec(iv);
SecretKeySpec key = newSecretKeySpec(decryptKey.getBytes("UTF-8"), "DES");
Cipher cipher =Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,key, zeroIv);
byte decryptedData[] =cipher.doFinal(encryptedData);
System.out.println("diddecryptedData with UTF-8 encoding =" + parseByte2HexStr(decryptedData));
String decryptedString =new String(decryptedData, "UTF-8");
System.out.println("diddecryptedString with UTF-8 encoding =" + decryptedString);
return decryptedString;
}
public static StringdecryptDESwithBase64(String encryptedString, String decryptKey) throws Exception
{
byte[]encryptedData=XYBase64.decode(encryptedString);
returndecryptDES(encryptedData, decryptKey);
}
在main()中调试一下,结果符合预期。
public static void main(String[] args) throws Exception {
String plainText ="abcdefghihjjjkelaemn";
String keyText ="20120401";
plainText = "miki西游| mikixiyou@126.com";
keyText ="abcd1234";
byte[] encryptedData =encryptDES(plainText, keyText);
StringdecryptedString=decryptDES(encryptedData, keyText);
String cipherText =parseByte2HexStr(encryptedData);
System.out.println("明文:" + plainText);
System.out.println("密钥:" + keyText);
System.out.println("密文 Base64 编码:" + cipherText);
System.out.println("解密后:" + decryptedString);
String encryptedString =encryptDESwithBase64(plainText, keyText);
decryptedString=decryptDESwithBase64(encryptedStr