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�ܥ
加密后是字节数组,不是所有字节数组都可以通过new String()转换成字符串的
一周热门 更多>