Java DES(对称加密) 发表于 2019-01-16 | 更新于 2019-02-22 | 分类于 Java | | 阅读次数: 简单一种对称加密与解密123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class DESUtils { /* * 生成密钥 */ public static byte[] initKey() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("DES"); keyGen.init(56); SecretKey secretKey = keyGen.generateKey(); return secretKey.getEncoded(); } /* * DES 加密 */ public static String encrypt(byte[] data, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] cipherBytes = cipher.doFinal(data); String result = byte2Hex(cipherBytes); return result; } /* * DES 解密 */ public static String decrypt(byte[] data, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] plainBytes = cipher.doFinal(data); String result = new String(plainBytes); return result; } private static int toByte(char c) { byte b = (byte) "0123456789ABCDEF".indexOf(c); return b; } public static byte[] hexToByte(String hex) { int len = (hex.length() / 2); byte[] result = new byte[len]; char[] achar = hex.toCharArray(); for (int i = 0; i < len; i++) { int pos = i * 2; result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1])); } return result; } public static String byte2Hex(byte[] b) { String stmp = ""; StringBuilder sb = new StringBuilder(""); for (int n = 0; n < b.length; n++) { stmp = Integer.toHexString(b[n] & 0xFF); sb.append((stmp.length() == 1) ? "0" + stmp : stmp); } return sb.toString().toUpperCase().trim(); } //加密 public static String encryptStr(String str, String secreytKey) throws Exception { String enResult = encrypt(str.getBytes(), hexToByte(secreytKey)); return enResult; } //解密 public static String decryptStr(String str, String secreytKey) throws Exception { String deResult = decrypt(hexToByte(str), hexToByte(secreytKey)); return deResult; } /*** * 秘钥769bfbae9d20100d 加密结果e3f6b60180661bb0d541de00260afb10 解密结果hello_world * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { //生成秘钥 byte[] desKey = initKey(); String secreytKey = byte2Hex(desKey); System.out.println("秘钥" + secreytKey.toLowerCase()); //加密 String hello_world = encryptStr("hello_world", secreytKey); System.out.println("加密结果" + hello_world.toLowerCase()); //解密 String deResult = decryptStr(hello_world, secreytKey); System.out.println("解密结果" + deResult); }} 打赏 微信支付 支付宝