資源簡介
利用jce簡單實現了CBC-MAC算法,程序主要完成了子密鑰生成算法、以及MAC的生成。
代碼片段和文件信息
import?java.io.*;
import?javax.crypto.*;
import?javax.crypto.spec.*;
public?class?CMAC?{
private?static?final?String?fileName?=?“5070309654_徐京_實驗報告3.pdf“;
private?static?int?BLOCK_LEN;
private?Cipher?cipher;
private?byte[]?key;
private?byte[]?k1;
private?byte[]?k2;
public?static?void?main(String[]?args)?throws?Exception?{
CMAC?cmac?=?new?CMAC();
cmac.init();
System.out.println(cmac.getMAC(new?FileInputStream(fileName)));
}
private?void?init()?throws?Exception?{
BLOCK_LEN?=?16;
key?=?getKey(“507030965420101114“.getBytes());
cipher?=?Cipher.getInstance(“AES/CBC/noPadding“);
IvParameterSpec?iv?=?new?IvParameterSpec(key);
SecretKeySpec?sk?=?new?SecretKeySpec(key?0?BLOCK_LEN?“AES“);
cipher.init(Cipher.ENCRYPT_MODE?sk?iv);
byte[]?kl?=?cipher.update(new?byte[BLOCK_LEN]);
k1?=?getSubKey(kl);
k2?=?getSubKey(k1);
}
/**
?*?得到MAC
?*?@param?cipher
?*?@param?k1
?*?@param?k2
?*?@param?text
?*?@return
?*?@throws?Exception
?*/
private?String?getMAC(InputStream?text)?throws?Exception?{
byte[]?cipherText?=?new?byte[BLOCK_LEN];
byte[]?current?=?new?byte[BLOCK_LEN];
byte[]?next?=?new?byte[BLOCK_LEN];
int?currentLen?nextLen;
currentLen?=?text.read(current);
do?{
nextLen?=?text.read(next);
if?(nextLen?!=?-1)?{
cipherText?=?cipher.update(xor(current?cipherText));
current?=?next;
currentLen?=?nextLen;
next?=?new?byte[BLOCK_LEN];
nextLen?=?0;
}
}?while?(nextLen?!=?-1);
if?(currentLen? cipherText?=?cipher.update(xor(xor(padding(current?currentLen)?k2)?cipherText));
else?
- 上一篇:一個使用xutils上傳圖片到服務器的工具類
- 下一篇:java開發的公司訪客系統
評論
共有 條評論