Java Tutorial/Security/Mac
Содержание
Generating a MAC from a text input using a random key.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import sun.misc.*;
public class MainClass {
public static void main (String[] args) throws Exception {
SecureRandom random = new SecureRandom();
byte[] keyBytes = new byte[20];
random.nextBytes(keyBytes);
SecretKeySpec key = new SecretKeySpec(keyBytes, "HMACSHA1");
System.out.println("Key:"+new
BASE64Encoder().encode(key.getEncoded()));
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(key);
mac.update("test".getBytes("UTF8"));
byte[] result = mac.doFinal();
System.out.println("MAC: "+new BASE64Encoder().encode(result));
}
}
Generating a Message Authentication Code (MAC) Key
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class Main {
public static void main(String[] argv) throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
SecretKey key = keyGen.generateKey();
// Generate a key for the HMAC-SHA1 keyed-hashing algorithm
keyGen = KeyGenerator.getInstance("HmacSHA1");
key = keyGen.generateKey();
}
}
Mac creation
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class MainClass {
public static void main(String args[]) throws Exception {
SecretKeySpec k = new SecretKeySpec("1234".getBytes(), "HMACSHA1");
Mac m = Mac.getInstance("HmacMD5");
m.init(k);
m.update("test".getBytes("UTF8"));
byte s[] = m.doFinal();
for (int i = 0; i < s.length; i++) {
System.out.print( Integer.toHexString((0x000000ff & s[i]) | 0xffffff00).substring(6));
}
}
}
Use MAC
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
public class MainClass {
public static void main(String[] args) throws Exception {
String alg = "HmacMD5";
Mac mac = Mac.getInstance(alg);
KeyGenerator kg = KeyGenerator.getInstance(alg);
SecretKey key = kg.generateKey();
mac.init(key);
mac.update("test".getBytes());
byte[] b = mac.doFinal();
System.out.println(new String(b));
}
}