java - 为什么des加密后输出乱码?

查看:233
本文介绍了java - 为什么des加密后输出乱码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

     public static void main(String args[]) {
  
            String string = "abcdef你";
           KeyGenerator keyGenerator = null;
            try {
                keyGenerator = KeyGenerator.getInstance("DES");
    
                SecretKey secretKey = keyGenerator.generateKey();
                byte[] bytesKey = secretKey.getEncoded();
                DESKeySpec desKeySpec = new DESKeySpec(bytesKey);
                SecretKeyFactory factory = SecretKeyFactory.getInstance("DES");
                SecretKey secretKey1 = factory.generateSecret(desKeySpec);
    
                Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, secretKey1);
                byte[] sbytes = string.getBytes("utf-8");
                byte[] bytes = cipher.doFinal(string.getBytes());
                System.out.println("加密前 bytes[]:" + byte2hex(sbytes));
                System.out.println("加密前string:" + new String(sbytes, "UTF-8"));
                System.out.println("加密后 bytes[]:" + byte2hex(bytes));
                System.out.println("加密后string:" + new String(bytes, "UTF-8"));
            } catch (InvalidKeyException e) {
                e.printStackTrace();
            } catch (InvalidKeySpecException e) {
                e.printStackTrace();
            } catch (BadPaddingException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (IllegalBlockSizeException e) {
                e.printStackTrace();
            } catch (NoSuchPaddingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
    
        }
    
        private static String byte2hex(byte[] buffer) {
            String h = "";
    
            for (int i = 0; i < buffer.length; i++) {
                String temp = Integer.toHexString(buffer[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + " " + temp;
            }
            return h;
        }
        

输出结果

加密前 bytes[]: 61 62 63 64 65 66 e4 bd a0
加密前string:abcdef你
加密后 bytes[]: e1 32 7c 94 ce 5d 08 f6 8f b0 af 32 5c d3 dc a5
加密后string:�2|��]����2\�ܥ

解决方案

因为已经不是UTF-8字符串数据了,亲。你加密了啊。DES产生的是不可读的二进制数据,你强行用new String按照UTF-8编码解释,当然是乱码了,如果能直接读出来,要加密何用?
因为大多数基于数学算法加密的数据,产生的都是二进制块或者流数据。只有解密了才能读到原文。
如果你希望加密后的数据能够存储为文本或者HTTP传输,你可以将数据用BASE64编码,编码后就是ASCII字符串,不会乱码了(当然人还是看不懂)。

这篇关于java - 为什么des加密后输出乱码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆