天天看點

Java中的mac計算

          封包鑒别在身份認證中占重要位置,是認證系統的一個重要環節,在金融和商業系統中廣泛應用。

          封包鑒别常用封包驗證碼(Message Authentication Code,即MAC)作為鑒别的基礎,

          其基本原理是:用一個密鑰((private Key))生成一個小資料塊附加在要傳輸的封包後面。這種技術是假定通訊雙方共享一個密鑰K,當通訊的一方要給另一方傳輸資料M時,通過特定的算法計算出該封包M的MAC=F(K,M),這裡的F就是指鑒别運算函數,然後封包資料M和MAC一起傳送給另一方。當另一方收到資料時,先用同樣的算法F計算MAC,和傳輸過來的MAC進行比較,如果相同,則認為資料是正确的。 鑒别函數常被認為是加密算法的一種,但是差別在于它不用于逆運算,有一定的安全性。 通常對于不同的應用系統采用各自特定的鑒别函數,這樣在一定程度上保證了資料的安全性。

       從j2sdk1.4以後,java提供了類javax.crypto.Mac類封包鑒别

byte[] macData = "this is a mac test".getBytes(); //get a instance of Mac, using HmacMD5 algorithm

Mac mac = Mac.getInstance("HmacMD5"); //init the IV of the algorithm, 8 bytes. may read from file

byte[] ivInitKey = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07 };

IvParameterSpec spec = new IvParameterSpec(ivInitKey); // the secrete key bytes of the Mac validation, May read from file too

byte[] keyBytes = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f }; //generate the secrete Key Object using secrete bytes and DESede algorithm

SecretKey key = new SecretKeySpec(keyBytes, "DESede"); // init Mac mac.init(key, spec);

byte[] macCode = mac.doFinal(macData);

macCode 就是生成的Mac,用同樣的密鑰能産生同樣的mac。

通訊雙方隻要保證用同樣的密鑰就能保證得到同樣的Mac,達到封包驗證的目的。

看來看去,這和網絡上常用的checksum原理是一樣的。