开发手册 欢迎您!
软件开发者资料库

Java密码术 - 创建MAC

Java密码术创建MAC - 从基本到高级概念的简单简单步骤学习Java密码学,其中包括简介,消息摘要,创建MAC,密钥,存储,检索密钥,KeyGenerator,KeyPairGenerator,创建,验证签名,加密,解密数据。

MAC( M essage A 认证 C ode)算法是一种对称密钥加密技术,用于提供消息身份验证.为了建立MAC过程,发送方和接收方共享对称密钥K.

基本上,MAC是在基础消息上生成的加密校验和,与消息一起发送以确保消息认证.

使用MAC进行身份验证的过程如下图所示 :

创建MAC

在Java中, javax.crypto 包的 Mac 类提供了消息验证代码的功能.按照下面给出的步骤使用此类创建消息验证代码.

步骤1:创建KeyGenerator对象

KeyGenerator class提供 getInstance()方法,该方法接受表示所需密钥生成算法的String变量,并返回生成密钥的 KeyGenerator 对象.

使用 getInstance()方法创建 KeyGenerator 对象,如下所示.

//创建KeyGenerator对象KeyGenerator keyGen = KeyGenerator.getInstance("DES");

步骤2:创建SecureRandom对象

SecureRandom 类java.Security 包提供了一个强大的随机数生成器,用于在Java中生成随机数.实例化此类,如下所示.

//创建SecureRandom对象SecureRandom secRandom = new SecureRandom();

步骤3:初始化KeyGenerator

KeyGenerator 类提供名为

初始化KeyGenerator对象使用此方法在上一步中创建.

//初始化KeyGenerator keyGen.init(secRandom);

步骤4:生成密钥

使用 generateKey()方法生成密钥 KeyGenerator 类,如下所示.

//创建/生成密钥Key key = keyGen.generateKey();

步骤5:初始化Mac对象

init()方法Mac类接受一个Key对象,并使用给定的键初始化当前的Mac对象.

//Initializing the Mac objectmac.init(key);

步骤6:完成mac操作

doFinal()方法Mac类用于完成Mac操作.将所需的数据以字节数组的形式传递给此方法并完成操作,如下所示.

//Computing the MacString msg = new String("Hi how are you");byte[] bytes = msg.getBytes();byte[] macResult = mac.doFinal(bytes);

示例

以下示例演示了如何使用JCA生成消息验证代码(MAC).在这里,我们收到一条简单的消息"你好,你好",并为该消息生成一个Mac.

import java.security.Key;import java.security.SecureRandom;import javax.crypto.KeyGenerator;import javax.crypto.Mac;public class MacSample {   public static void main(String args[]) throws Exception{      //Creating a KeyGenerator object      KeyGenerator keyGen = KeyGenerator.getInstance("DES");      //Creating a SecureRandom object      SecureRandom secRandom = new SecureRandom();      //Initializing the KeyGenerator      keyGen.init(secRandom);      //Creating/Generating a key      Key key = keyGen.generateKey();       //Creating a Mac object      Mac mac = Mac.getInstance("HmacSHA256");      //Initializing the Mac object      mac.init(key);      //Computing the Mac      String msg = new String("Hi how are you");      byte[] bytes = msg.getBytes();            byte[] macResult = mac.doFinal(bytes);      System.out.println("Mac result:");      System.out.println(new String(macResult));        }}

输出

上述程序将生成以下输出 :

Mac result:HÖ„^ǃÎ_Utbh…?š_üzØSSÜh_ž_œa0ŽV?