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
|
private static final String KEY = "8f2ae598bc768a12341312313121412412c9";
private static final String OFFSET = "34b373131231241212412bfd7d4790f";
private static final String ENCODING = "UTF-8";
private static final String ALGORITHM = "AES";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static String encrypt(String data) { try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.US_ASCII), ALGORITHM); IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(data.getBytes(ENCODING)); return parseByte2HexStr(encrypted); } catch (Exception e) { e.printStackTrace(); } return null; }
public static String decrypt(String data) { try { Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); SecretKeySpec skeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.US_ASCII), ALGORITHM); IvParameterSpec iv = new IvParameterSpec(OFFSET.getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] buffer = parseHexStr2Byte(data); byte[] encrypted = cipher.doFinal(buffer); return new String(encrypted, ENCODING); } catch (Exception e) { e.printStackTrace(); } return null; }
private static String parseByte2HexStr(byte[] buf) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < buf.length; i++) { String hex = Integer.toHexString(buf[i] & 0xFF); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toLowerCase()); } return sb.toString(); }
private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; i++) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; }
|