JCA的message digest介紹:
1.使用SHA-256產生HMAC
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Mac;
import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import org.apache.commons.codec.binary.Base64;
/**
*
* @author andy
*/
public class HmacExample {
public static void main(String args[]) {
try {
KeyGenerator kg = KeyGenerator.getInstance("HmacSHA256");
SecretKey sk = kg.generateKey();
Mac mac = Mac.getInstance("HmacSHA256");//use HmacSHA256
mac.init(sk);
byte[] hmac = mac.doFinal("data".getBytes());
String encodedString = new String( Base64.encodeBase64(hmac) );
System.out.println("HMAC:"+encodedString);
} catch (NoSuchAlgorithmException e1) {
System.err.println(e1);
} catch (InvalidKeyException e2) {
System.err.println(e2);
}
}
}
沒有留言:
張貼留言