C#的DES加密与解密算法我就不写了,主要写一下怎么去解密C#用DES加密后串,大家都知道C#的DES加密密钥长度是8位的,而java是8的倍数位,所以用普通的java中的DES是不行的,要解C#的加密的串用下面的方法
- /**
- * 解密c#的des加密串
- * @param message
- * @param key
- * @return
- * @throws Exception
- */
- public static String desDncrypt(byte[] message, String key) throws Exception {
- Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
- DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
- IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
- cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
- byte[] retByte = cipher.doFinal(message);
- return new String(retByte);
- }
同理,如果java用DES加密让C#去解密呢?用以下方法加密
- public static byte[] desEncrypt(String message, String key) throws Exception {
- Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
- DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
- SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
- SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
- IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
- cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
- return cipher.doFinal(message.getBytes("UTF-8"));
- }
这样就没有问题了,快去试试吧
本文转自sucre03 51CTO博客,原文链接:http://blog.51cto.com/sucre/890085,如需转载请自行联系原作者