Java使用AES演算法進行加密解密
阿新 • • 發佈:2018-12-16
一、加密
/** * 加密 * @param src 源資料位元組陣列 * @param key 金鑰位元組陣列 * @return 加密後的位元組陣列 */ public static byte[] Encrypt(byte[] src, byte[] key) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");//"演算法/模式/補碼方式" cipher.init(Cipher.ENCRYPT_MODE, skeySpec); return cipher.doFinal(src); }
二、解密
/** * 解密 * @param src 加密後的位元組資料 * @param key 金鑰位元組陣列 * @return 加密後的位元組陣列 * @throws Exception 異常 */ public static byte[] Decrypt(byte[] src, byte[] key) throws Exception {try { SecretKeySpec skeySpec = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); try { return cipher.doFinal(key); } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } }
三、hex字串與位元組陣列互轉
/** * 將二進位制轉換成16進位制字串 * @param buf 位元組陣列 * @return 字串 */ public static String parseByte2HexStr(byte buf[]) { StringBuffer sb = new StringBuffer(); 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.toUpperCase()); } return sb.toString(); } /** * 將16進位制字串轉換為二進位制 * @param hexStr 字串 * @return 位元組陣列 */ public 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; }
注:因工作內容常與微控制器進行資料傳輸,所以不能直接使用字串進行加密解密,需要多進行一次hex字串的轉換
因為上述加密解密使用的補碼模式是NoPadding,所以輸入的位元組必須是128位對應的16個位元組的倍數,如有需要可以將補碼模式改為以下模式