1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; import java.security.Key;
public class DesUtil { private static final String ALGORITHM = "Des"; private static final String CIPHER_ALGORITHM = "Des/ECB/PKCS5Padding"; private static final String CHARSET = "utf-8";
private static SecretKey generateKey(String password) throws Exception { DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET)); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM); return keyFactory.generateSecret(dks); }
public static String byte2HexString(byte[] bytes) { StringBuilder hex = new StringBuilder(); if (bytes != null) { for (Byte b : bytes) { hex.append(String.format("%02x", b.intValue() & 0XFF)); } } return hex.toString(); }
public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; try { for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16)); } } catch (Exception exception) { exception.printStackTrace(); } return data; }
public static String encrypt(String password, String data) { if (password == null || password.length() < 8) { throw new RuntimeException("加密失败,key不能小于8位"); } if (data == null) { return null; } try { Key secretKey = generateKey(password); Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] bytes = cipher.doFinal(data.getBytes(CHARSET)); return byte2HexString(bytes); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static String decrypt(String password, String data) { if (password == null || password.length() < 8) { throw new RuntimeException("解密失败,key不能小于8位"); } if (data == null) { return null; } try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); Key secretKey = generateKey(password); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] bytes = hexStringToByteArray(data); return new String(cipher.doFinal(bytes), CHARSET); } catch (Exception ex) { ex.printStackTrace(); return null; } }
public static void main(String[] args) { String str = "xiaoyuge"; String password = "secret_key"; String encrypt = encrypt(password, str); System.out.println("加密结果:"+encrypt); System.out.println("解密结果:"+decrypt(password, encrypt)); } }
|