`
conmind
  • 浏览: 3213 次
  • 性别: Icon_minigender_1
  • 来自: 北京
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

HMAC-SHA1的java源代码实现

    博客分类:
  • BB
阅读更多
由于要进行手机j2me开发,而j2me上没有加密算法实现,在网上没找到hmacsha1的算法源代码,只有sha1的源代码以及mac算法的原理,看来只能自己写了。
研究了RFC2104的说明(中文),原文http://blog.chinaunix.net/u1/38994/showart_2178221.html,如下:
引用

HMAC的定义。
         定义HMAC需要一个加密用散列函数(表示为H)和一个密钥K。我们假设H是
一个将数据块用一个基本的迭代压缩函数来加密的散列函数。我们用B来表示数据块
的字长。(以上说提到的散列函数的分割数据块字长B=64),用L来表示散列函数的
输出数据字长(MD5中L=16,SHA—1中L=20)。鉴别密钥的长度可以是小于等于数
据块字长的任何正整数值。应用程序中使用的密钥长度若是比B大,则首先用使用散列
函数H作用于它,然后用H输出的L长度字符串作为在HMAC中实际使用的密钥。
一般情况下,推荐的最小密钥K长度是L个字长。(与H的输出数据长度相等)。更详
细的信息参见第三部分。
    我们将定义两个固定且不同的字符串ipad,opad:
(‘i','o'标志内部与外部)
        ipad = the byte 0x36 repeated B times
          opad = the byte 0x5C repeated B times.
计算‘text'的HMAC:
           H( K XOR opad, H(K XOR ipad, text))
即为以下步骤:

(1) 在密钥K后面添加0来创建一个子长为B的字符串。(例如,如果K的字长是20
字节,B=60字节,则K后会加入44个零字节0x00)

(2) 将上一步生成的B字长的字符串与ipad做异或运算。

(3) 将数据流text填充至第二步的结果字符串中。

(4) 用H作用于第三步生成的数据流。

(5) 将第一步生成的B字长字符串与opad做异或运算。

(6) 再将第四步的结果填充进第五步的结果中。

(7) 用H作用于第六步生成的数据流,输出最终结果
    
基于MD5的相关代码将作为附录提供

  密钥。
用于HMAC的密钥可以是任意长度(比B长的密钥将首先被H处理)。但当密钥
长度小于L时的情况时非常令人失望的,因为这样将降低函数的安全强度。长度大于
L的密钥是可以接受的,但是额外的长度并不能显著的提高函数的安全强度。(如果一
个随机的密钥被认为是不可靠的,那么选择一个较长的密钥是明智的)。
    密钥必须随机选取(或使用强大的基于随机种子的伪随机生成方法),并且要周期
性的更新。(目前的攻击没有指出一个有效的更换密钥的频率,因为那些攻击实际上并
不可行。然而,周期性更新密钥是一个对付函数和密钥所存在的潜在缺陷的基本
的安全措施,并可以降低泄漏密钥带来的危害。)



代码:
sha1的java实现,来源http://blog.csdn.net/zyg158/archive/2007/06/26/1667542.aspx,原文sha1算法最终生成的结果是大写字母,而java生成的是小写字母,所以我把它改成小写(虽然这里没用到)
public class SHA1 {
    private final int[] abcde = {
            0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0
        };

    // 摘要数据存储数组
    private int[] digestInt = new int[5];

    // 计算过程中的临时数据存储数组
    private int[] tmpData = new int[80];

    // 计算sha-1摘要
    private int process_input_bytes(byte[] bytedata) {
        // 初试化常量
        System.arraycopy(abcde, 0, digestInt, 0, abcde.length);

        // 格式化输入字节数组,补10及长度数据
        byte[] newbyte = byteArrayFormatData(bytedata);

        // 获取数据摘要计算的数据单元个数
        int MCount = newbyte.length / 64;

        // 循环对每个数据单元进行摘要计算
        for (int pos = 0; pos < MCount; pos++) {
            // 将每个单元的数据转换成16个整型数据,并保存到tmpData的前16个数组元素中
            for (int j = 0; j < 16; j++) {
                tmpData[j] = byteArrayToInt(newbyte, (pos * 64) + (j * 4));
            }

            // 摘要计算函数
            encrypt();
        }

        return 20;
    }

    // 格式化输入字节数组格式
    private byte[] byteArrayFormatData(byte[] bytedata) {
        // 补0数量
        int zeros = 0;

        // 补位后总位数
        int size = 0;

        // 原始数据长度
        int n = bytedata.length;

        // 模64后的剩余位数
        int m = n % 64;

        // 计算添加0的个数以及添加10后的总长度
        if (m < 56) {
            zeros = 55 - m;
            size = n - m + 64;
        } else if (m == 56) {
            zeros = 63;
            size = n + 8 + 64;
        } else {
            zeros = 63 - m + 56;
            size = (n + 64) - m + 64;
        }

        // 补位后生成的新数组内容
        byte[] newbyte = new byte[size];
        // 复制数组的前面部分
        System.arraycopy(bytedata, 0, newbyte, 0, n);

        // 获得数组Append数据元素的位置
        int l = n;
        // 补1操作
        newbyte[l++] = (byte) 0x80;

        // 补0操作
        for (int i = 0; i < zeros; i++) {
            newbyte[l++] = (byte) 0x00;
        }

        // 计算数据长度,补数据长度位共8字节,长整型
        long N = (long) n * 8;
        byte h8 = (byte) (N & 0xFF);
        byte h7 = (byte) ((N >> 8) & 0xFF);
        byte h6 = (byte) ((N >> 16) & 0xFF);
        byte h5 = (byte) ((N >> 24) & 0xFF);
        byte h4 = (byte) ((N >> 32) & 0xFF);
        byte h3 = (byte) ((N >> 40) & 0xFF);
        byte h2 = (byte) ((N >> 48) & 0xFF);
        byte h1 = (byte) (N >> 56);
        newbyte[l++] = h1;
        newbyte[l++] = h2;
        newbyte[l++] = h3;
        newbyte[l++] = h4;
        newbyte[l++] = h5;
        newbyte[l++] = h6;
        newbyte[l++] = h7;
        newbyte[l++] = h8;

        return newbyte;
    }

    private int f1(int x, int y, int z) {
        return (x & y) | (~x & z);
    }

    private int f2(int x, int y, int z) {
        return x ^ y ^ z;
    }

    private int f3(int x, int y, int z) {
        return (x & y) | (x & z) | (y & z);
    }

    private int f4(int x, int y) {
        return (x << y) | x >>> (32 - y);
    }

    // 单元摘要计算函数
    private void encrypt() {
        for (int i = 16; i <= 79; i++) {
            tmpData[i] = f4(tmpData[i - 3] ^ tmpData[i - 8] ^ tmpData[i - 14] ^
                    tmpData[i - 16], 1);
        }

        int[] tmpabcde = new int[5];

        for (int i1 = 0; i1 < tmpabcde.length; i1++) {
            tmpabcde[i1] = digestInt[i1];
        }

        for (int j = 0; j <= 19; j++) {
            int tmp = f4(tmpabcde[0], 5) +
                f1(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4] +
                tmpData[j] + 0x5a827999;
            tmpabcde[4] = tmpabcde[3];
            tmpabcde[3] = tmpabcde[2];
            tmpabcde[2] = f4(tmpabcde[1], 30);
            tmpabcde[1] = tmpabcde[0];
            tmpabcde[0] = tmp;
        }

        for (int k = 20; k <= 39; k++) {
            int tmp = f4(tmpabcde[0], 5) +
                f2(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4] +
                tmpData[k] + 0x6ed9eba1;
            tmpabcde[4] = tmpabcde[3];
            tmpabcde[3] = tmpabcde[2];
            tmpabcde[2] = f4(tmpabcde[1], 30);
            tmpabcde[1] = tmpabcde[0];
            tmpabcde[0] = tmp;
        }

        for (int l = 40; l <= 59; l++) {
            int tmp = f4(tmpabcde[0], 5) +
                f3(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4] +
                tmpData[l] + 0x8f1bbcdc;
            tmpabcde[4] = tmpabcde[3];
            tmpabcde[3] = tmpabcde[2];
            tmpabcde[2] = f4(tmpabcde[1], 30);
            tmpabcde[1] = tmpabcde[0];
            tmpabcde[0] = tmp;
        }

        for (int m = 60; m <= 79; m++) {
            int tmp = f4(tmpabcde[0], 5) +
                f2(tmpabcde[1], tmpabcde[2], tmpabcde[3]) + tmpabcde[4] +
                tmpData[m] + 0xca62c1d6;
            tmpabcde[4] = tmpabcde[3];
            tmpabcde[3] = tmpabcde[2];
            tmpabcde[2] = f4(tmpabcde[1], 30);
            tmpabcde[1] = tmpabcde[0];
            tmpabcde[0] = tmp;
        }

        for (int i2 = 0; i2 < tmpabcde.length; i2++) {
            digestInt[i2] = digestInt[i2] + tmpabcde[i2];
        }

        for (int n = 0; n < tmpData.length; n++) {
            tmpData[n] = 0;
        }
    }

    // 4字节数组转换为整数
    private int byteArrayToInt(byte[] bytedata, int i) {
        return ((bytedata[i] & 0xff) << 24) | ((bytedata[i + 1] & 0xff) << 16) |
        ((bytedata[i + 2] & 0xff) << 8) | (bytedata[i + 3] & 0xff);
    }

    // 整数转换为4字节数组
    private void intToByteArray(int intValue, byte[] byteData, int i) {
        byteData[i] = (byte) (intValue >>> 24);
        byteData[i + 1] = (byte) (intValue >>> 16);
        byteData[i + 2] = (byte) (intValue >>> 8);
        byteData[i + 3] = (byte) intValue;
    }

    // 将字节转换为十六进制字符串
    private static String byteToHexString(byte ib) {
        char[] Digit = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c',
                'd', 'e', 'f'
            };
        char[] ob = new char[2];
        ob[0] = Digit[(ib >>> 4) & 0X0F];
        ob[1] = Digit[ib & 0X0F];

        String s = new String(ob);

        return s;
    }

    // 将字节数组转换为十六进制字符串
    private static String byteArrayToHexString(byte[] bytearray) {
        String strDigest = "";

        for (int i = 0; i < bytearray.length; i++) {
            strDigest += byteToHexString(bytearray[i]);
        }

        return strDigest;
    }

    // 计算sha-1摘要,返回相应的字节数组
    public byte[] getDigestOfBytes(byte[] byteData) {
        process_input_bytes(byteData);

        byte[] digest = new byte[20];

        for (int i = 0; i < digestInt.length; i++) {
            intToByteArray(digestInt[i], digest, i * 4);
        }

        return digest;
    }

    // 计算sha-1摘要,返回相应的十六进制字符串
    public String getDigestOfString(byte[] byteData) {
        return byteArrayToHexString(getDigestOfBytes(byteData));
    }

    public static void main(String[] args) {
        String data = "1";
        System.out.println(data);

        String digest = new SHA1().getDigestOfString(data.getBytes());
        System.out.println(digest);
    }
}


实现的hmac-sha1算法:
/**
 * @author conmind
 */
public class HMACSHA1 {
	public static byte[] getHmacSHA1( String data,String key){
		byte[] ipadArray = new byte[64];
		byte[] opadArray = new byte[64];
		byte[] keyArray = new byte[64];
		int ex = key.length();
		SHA1 sha1= new SHA1();
		if (key.length() > 64) {
			byte[] temp = sha1.getDigestOfBytes(key.getBytes());
			ex = temp.length;
			for (int i = 0; i < ex; i++) {
				keyArray[i] = temp[i];
			}
		}else{
			byte[] temp = key.getBytes();
			for (int i = 0; i < temp.length; i++) {
				keyArray[i] = temp[i];
			}
		}
		for (int i = ex; i < 64; i++) {
			keyArray[i] = 0;
		}
		for (int j = 0; j < 64; j++) {
			ipadArray[j] = (byte) (keyArray[j] ^ 0x36);
			opadArray[j] = (byte) (keyArray[j] ^ 0x5C);
		}
		byte[] tempResult = sha1.getDigestOfBytes(join(ipadArray,data.getBytes()));
		
		return sha1.getDigestOfBytes(join(opadArray,tempResult));
	}
	
	private static byte[] join(byte[] b1,byte[] b2){
		int length = b1.length + b2.length;
		byte[] newer = new byte[length];
		for (int i = 0; i < b1.length; i++) {
			newer[i] = b1[i];
		}
		for (int i = 0; i < b2.length; i++) {
			newer[i+b1.length] = b2[i];
		}
		return newer;
	}
}


base64算法的源代码,也是在网上找的,出处未知:

/**
 * A utility class encodes byte array into String using Base64 encoding scheme.
 */
public class BASE64Encoder {
    private static final char last2byte = (char) Integer.parseInt("00000011", 2);
    private static final char last4byte = (char) Integer.parseInt("00001111", 2);
    private static final char last6byte = (char) Integer.parseInt("00111111", 2);
    private static final char lead6byte = (char) Integer.parseInt("11111100", 2);
    private static final char lead4byte = (char) Integer.parseInt("11110000", 2);
    private static final char lead2byte = (char) Integer.parseInt("11000000", 2);
    private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};

    public BASE64Encoder() {
    }

    public String encode(byte[] from) {
        StringBuffer to = new StringBuffer((int) (from.length * 1.34) + 3);
        int num = 0;
        char currentByte = 0;
        for (int i = 0; i < from.length; i++) {
            num = num % 8;
            while (num < 8) {
                switch (num) {
                    case 0:
                        currentByte = (char) (from[i] & lead6byte);
                        currentByte = (char) (currentByte >>> 2);
                        break;
                    case 2:
                        currentByte = (char) (from[i] & last6byte);
                        break;
                    case 4:
                        currentByte = (char) (from[i] & last4byte);
                        currentByte = (char) (currentByte << 2);
                        if ((i + 1) < from.length) {
                            currentByte |= (from[i + 1] & lead2byte) >>> 6;
                        }
                        break;
                    case 6:
                        currentByte = (char) (from[i] & last2byte);
                        currentByte = (char) (currentByte << 4);
                        if ((i + 1) < from.length) {
                            currentByte |= (from[i + 1] & lead4byte) >>> 4;
                        }
                        break;
                }
                to.append(encodeTable[currentByte]);
                num += 6;
            }
        }
        if (to.length() % 4 != 0) {
            for (int i = 4 - to.length() % 4; i > 0; i--) {
                to.append("=");
            }
        }
        return to.toString();
    }
}



测试程序:使用密钥“123”,需要加密的数据“456”,由于返回的结果是byte数组,所以给最终的返回结果进行base64加密,然后输出对比
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author conmind
 */
public class Test {
	public static void main(String[] args) {
		try {
			//需要加密的数据
			String data = "456";
			//密钥
			String key = "123";
			our(data,key);
			standard(data, key);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private static void our(String data, String key){
		byte[] b = HMACSHA1.getHmacSHA1(data, key);
		String s = new BASE64Encoder().encode(b);
		System.out.println("hmacsha1 = " + s);
	}
	private static void standard(String data, String key) {
        byte[] byteHMAC = null;
        try {
            Mac mac = Mac.getInstance("HmacSHA1");
            SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            mac.init(spec);
            byteHMAC = mac.doFinal(data.getBytes());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException ignore) {
        }
        String oauth = new BASE64Encoder().encode(byteHMAC);
        System.out.println("standard = "+oauth);
    }
}


密钥小于64位的情况
data="456",key="123"的输出结果:
hmacsha1 = arl7onB4MoLePp7oTLNSrhxAOWw=      (实现的hmac-sha1算法)
standard = arl7onB4MoLePp7oTLNSrhxAOWw=      (j2se的标准实现)

另外密钥超过64位的情况(70个‘1’):
data="456",key="1111111111111111111111111111111111111111111111111111111111111111111111"的输出结果:
hmacsha1 = nzoqPYMIu91VViA/mEIG5FtJXi8=      (实现的hmac-sha1算法)
standard = nzoqPYMIu91VViA/mEIG5FtJXi8=      (j2se的标准实现)

结果完全相同 大半晚的辛苦,终于没枉费
分享到:
评论
3 楼 nameimei123456 2012-03-06  
LZ,你太好了。
2 楼 conmind 2010-04-09  
晕,这个很好理解吧,
“需要加密的数据”类似你的用户名和密码
“密钥”就是通过这个key来对数据进行加密
1 楼 liuxin15571745 2010-04-08  
LZ,你的那个加密数据和密钥  这2个分别代表的是什么呢?

相关推荐

Global site tag (gtag.js) - Google Analytics