import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import org.apache.commons.codec.BinaryDecoder; import org.apache.commons.codec.binary.Hex; public class DESDemo { public static final String src = "des test"; public static void main(String[] args) { jdkDES(); bcDES(); } private static void bcDES() { } private static void jdkDES() { try{ //生成KEY KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); keyGenerator.init(56); System.out.println(keyGenerator.getAlgorithm()); System.out.println(keyGenerator.getProvider()); SecretKey secretKey = keyGenerator.generateKey(); byte[] bytesKey = secretKey.getEncoded(); System.out.println(secretKey.getAlgorithm()); System.out.println(secretKey.getFormat()); //通过KEY转换生成密钥 DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES"); SecretKey convertedKey = factory.generateSecret(desKeySpec); //加密 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");// 算法/工作方式/填充方式 cipher.init(Cipher.ENCRYPT_MODE, convertedKey); byte[] result = cipher.doFinal("要加密的内容".getBytes()); System.out.println("jdk des encrypt:" + Hex.encodeHexString(result)); //解密 cipher.init(Cipher.DECRYPT_MODE,convertedKey); result = cipher.doFinal(result); // System.out.println("jdk des decrypt:" + new String(result)); //jdk des decrypt:?????????? 直接输出会乱码 System.out.println("jdk des decrypt:" + new String( result,"utf-8" )); //jdk des decrypt:?????????? 依旧乱码 } catch(Exception e) { e.printStackTrace(); } } }
请问windows系统默认编码是gbk吗?
//解答-----------------------------------------------------------
byte[] result = cipher.doFinal("要加密的内容".getBytes());
而字节数组转字符串时指定了编码:
System.out.println("jdk des decrypt:" + new String( result,"utf-8" ));
二者编码不一致造成乱码。并非是加解密过程中造成的。
解决方法很简单,字符串转字节数组时设置编码即可:
byte[] result = cipher.doFinal("要加密的内容".getBytes("utf-8"));
补充,为了证明并非是加解密过程中造成的,题主可以试试下面的程序在同样的环境下的运行结果,必定也是输出乱码:
byte[] byteArray = "要加密的内容".getBytes(); // 字符串转字节数组不指定编码(默认编码)
System.out.println(new String( byteArray ,"utf-8" )); // 字节数组转字符串指定UTF-8
最后发现问题还是没能解决,原因是服务器的编码和本地的编码不一致导致解码中文时候变成乱码,把中文转码成base64即可。