Java实现SHA-1算法实例_java

本文实例讲述了Java实现SHA-1算法的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:

public class SHA1Util {
    private static final boolean hexcase = false;
    private static final String b64pad = "=";
    private static final int chrsz = 8;
    // 得到字符串SHA-1值的方法
    public static String hex_sha1(String s) {
        s = (s == null) ? "" : s;
        return binb2hex(core_sha1(str2binb(s), s.length() * chrsz));
    }
    public static String b64_hmac_sha1(String key, String data) {
        return binb2b64(core_hmac_sha1(key, data));
    }
    public static String b64_sha1(String s) {
        s = (s == null) ? "" : s;
        return binb2b64(core_sha1(str2binb(s), s.length() * chrsz));
    }
    private static String binb2b64(int[] binarray) {
        String tab = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/";
        String str = "";
        binarray = strechbinarray(binarray, binarray.length * 4);
        for (int i = 0; i < binarray.length * 4; i += 3) {
            int triplet = (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xff) << 16)
                    | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xff) << 8)
                    | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xff);
            for (int j = 0; j < 4; j++) {
                if (i * 8 + j * 6 > binarray.length * 32) {
                    str += b64pad;
                } else {
                    str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3f);
                }
            }
        }
        return cleanb64str(str);
    }
    private static String binb2hex(int[] binarray) {
        String hex_tab = hexcase ? "0123456789abcdef" : "0123456789abcdef";
        String str = "";
        for (int i = 0; i < binarray.length * 4; i++) {
            char a = (char) hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xf);
            char b = (char) hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xf);
            str += (new Character(a).toString() + new Character(b).toString());
        }
        return str;
    }
    private static String binb2str(int[] bin) {
        String str = "";
        int mask = (1 << chrsz) - 1;
        for (int i = 0; i < bin.length * 32; i += chrsz) {
            str += (char) ((bin[i >> 5] >>> (24 - i % 32)) & mask);
        }
        return str;
    }
    private static int bit_rol(int num, int cnt) {
        return (num << cnt) | (num >>> (32 - cnt));
    }
    private static String cleanb64str(String str) {
        str = (str == null) ? "" : str;
        int len = str.length();
        if (len <= 1) {
            return str;
        }
        char trailchar = str.charAt(len - 1);
        String trailstr = "";
        for (int i = len - 1; i >= 0 && str.charAt(i) == trailchar; i--) {
            trailstr += str.charAt(i);
        }
        return str.substring(0, str.indexOf(trailstr));
    }
    private static int[] complete216(int[] oldbin) {
        if (oldbin.length >= 16) {
            return oldbin;
        }
        int[] newbin = new int[16 - oldbin.length];
        for (int i = 0; i < newbin.length; newbin[i] = 0, i++)
            ;
        return concat(oldbin, newbin);
    }
    private static int[] concat(int[] oldbin, int[] newbin) {
        int[] retval = new int[oldbin.length + newbin.length];
        for (int i = 0; i < (oldbin.length + newbin.length); i++) {
            if (i < oldbin.length) {
                retval[i] = oldbin[i];
            } else {
                retval[i] = newbin[i - oldbin.length];
            }
        }
        return retval;
    }
    private static int[] core_hmac_sha1(String key, String data) {
        key = (key == null) ? "" : key;
        data = (data == null) ? "" : data;
        int[] bkey = complete216(str2binb(key));
        if (bkey.length > 16) {
            bkey = core_sha1(bkey, key.length() * chrsz);
        }
        int[] ipad = new int[16];
        int[] opad = new int[16];
        for (int i = 0; i < 16; ipad[i] = 0, opad[i] = 0, i++)
            ;
        for (int i = 0; i < 16; i++) {
            ipad[i] = bkey[i] ^ 0x36363636;
            opad[i] = bkey[i] ^ 0x5c5c5c5c;
        }
        int[] hash = core_sha1(concat(ipad, str2binb(data)), 512 + data.length() * chrsz);
        return core_sha1(concat(opad, hash), 512 + 160);
    }
    private static int[] core_sha1(int[] x, int len) {
        int size = (len >> 5);
        x = strechbinarray(x, size);
        x[len >> 5] |= 0x80 << (24 - len % 32);
        size = ((len + 64 >> 9) << 4) + 15;
        x = strechbinarray(x, size);
        x[((len + 64 >> 9) << 4) + 15] = len;
        int[] w = new int[80];
        int a = 1732584193;
        int b = -271733879;
        int c = -1732584194;
        int d = 271733878;
        int e = -1009589776;
        for (int i = 0; i < x.length; i += 16) {
            int olda = a;
            int oldb = b;
            int oldc = c;
            int oldd = d;
            int olde = e;
            for (int j = 0; j < 80; j++) {
                if (j < 16) {
                    w[j] = x[i + j];
                } else {
                    w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                }
                int t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)), safe_add(safe_add(e, w[j]), sha1_kt(j)));
                e = d;
                d = c;
                c = rol(b, 30);
                b = a;
                a = t;
            }
            a = safe_add(a, olda);
            b = safe_add(b, oldb);
            c = safe_add(c, oldc);
            d = safe_add(d, oldd);
            e = safe_add(e, olde);
        }
        int[] retval = new int[5];
        retval[0] = a;
        retval[1] = b;
        retval[2] = c;
        retval[3] = d;
        retval[4] = e;
        return retval;
    }
    private static void dotest() {
        String key = "key";
        String data = "data";
        System.out.println("hex_sha1(" + data + ")=" + hex_sha1(data));
        System.out.println("b64_sha1(" + data + ")=" + b64_sha1(data));
        System.out.println("str_sha1(" + data + ")=" + str_sha1(data));
        System.out.println("hex_hmac_sha1(" + key + "," + data + ")=" + hex_hmac_sha1(key, data));
        System.out.println("b64_hmac_sha1(" + key + "," + data + ")=" + b64_hmac_sha1(key, data));
        System.out.println("str_hmac_sha1(" + key + "," + data + ")=" + str_hmac_sha1(key, data));
    }
    public static String hex_hmac_sha1(String key, String data) {
        return binb2hex(core_hmac_sha1(key, data));
    }
    private static int rol(int num, int cnt) {
        return (num << cnt) | (num >>> (32 - cnt));
    }
    private static int safe_add(int x, int y) {
        int lsw = (int) (x & 0xffff) + (int) (y & 0xffff);
        int msw = (x >> 16) + (y >> 16) + (lsw >> 16);
        return (msw << 16) | (lsw & 0xffff);
    }
    private static int sha1_ft(int t, int b, int c, int d) {
        if (t < 20)
            return (b & c) | ((~b) & d);
        if (t < 40)
            return b ^ c ^ d;
        if (t < 60)
            return (b & c) | (b & d) | (c & d);
        return b ^ c ^ d;
    }
    private static int sha1_kt(int t) {
        return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 : (t < 60) ? -1894007588 : -899497514;
    }
    private static boolean sha1_vm_test() {
        return hexcase ? hex_sha1("abc").equals("a9993e364706816aba3e25717850c26c9cd0d89d") : hex_sha1("abc").equals(
                "a9993e364706816aba3e25717850c26c9cd0d89d");
    }
    public static String str_hmac_sha1(String key, String data) {
        return binb2str(core_hmac_sha1(key, data));
    }
    public static String str_sha1(String s) {
        s = (s == null) ? "" : s;
        return binb2str(core_sha1(str2binb(s), s.length() * chrsz));
    }
    private static int[] str2binb(String str) {
        str = (str == null) ? "" : str;
        int[] tmp = new int[str.length() * chrsz];
        int mask = (1 << chrsz) - 1;
        for (int i = 0; i < str.length() * chrsz; i += chrsz) {
            tmp[i >> 5] |= ((int) (str.charAt(i / chrsz)) & mask) << (24 - i % 32);
        }
        int len = 0;
        for (int i = 0; i < tmp.length && tmp[i] != 0; i++, len++)
            ;
        int[] bin = new int[len];
        for (int i = 0; i < len; i++) {
            bin[i] = tmp[i];
        }
        return bin;
    }
    private static int[] strechbinarray(int[] oldbin, int size) {
        int currlen = oldbin.length;
        if (currlen >= size + 1) {
            return oldbin;
        }
        int[] newbin = new int[size + 1];
        for (int i = 0; i < size; newbin[i] = 0, i++)
            ;
        for (int i = 0; i < currlen; i++) {
            newbin[i] = oldbin[i];
        }
        return newbin;
    }
    public static void main(String args[]) {
        System.out.println("admin的SHA1的值为:" + hex_sha1("admin") + ",length=" + hex_sha1("admin").length());
    }
}

希望本文所述对大家的java程序设计有所帮助。

时间: 2024-10-22 23:06:12

Java实现SHA-1算法实例_java的相关文章

Java实现二分查找算法实例分析_java

本文实例讲述了Java实现二分查找算法.分享给大家供大家参考.具体如下: 1. 前提:二分查找的前提是需要查找的数组必须是已排序的,我们这里的实现默认为升序 2. 原理:将数组分为三部分,依次是中值(所谓的中值就是数组中间位置的那个值)前,中值,中值后:将要查找的值和数组的中值进行比较,若小于中值则在中值前面找,若大于中值则在中值后面找,等于中值时直接返回.然后依次是一个递归过程,将前半部分或者后半部分继续分解为三部分.可能描述得不是很清楚,若是不理解可以去网上找.从描述上就可以看出这个算法适合

java实现Fibonacci算法实例_java

本文实例讲述了java实现Fibonacci算法的方法.分享给大家供大家参考.具体如下: package com.yenange.test2; import java.util.Scanner; public class Fibonacci { private static Scanner input = new Scanner(System.in); public static void main(String[] args) { System.out.println("-----------

java之Object类用法实例_java

本文实例讲述了java中Object类用法.分享给大家供大家参考.具体如下: 1.Object类是所有java类的基类 如果在类的声明中未使用extends关键字指明其基类,则默认基类为Object类,ex: public class Person{ ~~~~~ } 等价于 public class Person extends Object{ ~~~~~ } 2.Object类之equals方法 ①.Object类中定义有: public boolean equals(Object obj)方

JAVA 内部类详解及实例_java

JAVA 内部类 一.什么是内部类? 一个类的定义放在另一个类的内部,这个类就叫做内部类 二.内部类有那些特性? 1.内部类仍然是一个独立的类,在编译之后内部类会被编译成独立的.class文件,但是前面冠以外部类的类名和$符号 . 2.内部类不能用普通的方式访问.内部类是外部类的一个成员,因此内部类可以自由地访问外部类的成员变量,无论是否是private的 . 3.内部类声明成静态的,就不能随便的访问外部类的成员变量了,此时内部类只能访问外部类的静态成员变量 . 三.内部类有哪几种? 1.成员内

java自定义拦截器用法实例_java

本文实例讲述了java自定义拦截器及其用法.分享给大家供大家参考.具体如下: LoginInterceptor.java文件如下: package com.tq365.util; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwo

十种JAVA排序算法实例_java

排序算法有很多,所以在特定情景中使用哪一种算法很重要.为了选择合适的算法,可以按照建议的顺序考虑以下标准: (1)执行时间 (2)存储空间 (3)编程工作  对于数据量较小的情形,(1)(2)差别不大,主要考虑(3):而对于数据量大的,(1)为首要.  一.冒泡(Bubble)排序 复制代码 代码如下: void BubbleSortArray() {       for(int i=1;i<n;i++)       {         for(int j=0;i<n-i;j++)      

Java实现的并发任务处理实例_java

本文实例讲述了Java实现的并发任务处理方法.分享给大家供大家参考,具体如下: public void init() { super.init(); this.ioThreadPool = new ThreadPoolExecutor(50, 50, Long.MAX_VALUE, TimeUnit.SECONDS, new java.util.concurrent.LinkedTransferQueue<Runnable>(), new ThreadFactory() { AtomicLon

java针对电话号码正则匹配实例_java

本文实例讲述了java针对电话号码正则匹配的方法.分享给大家供大家参考.具体如下: public interface RegExpConst { /** * 手机号码 * 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188 * 联通:130,131,132,152,155,156,185,186 * 电信:133,1349,153,180,189 */ String MOBILE = "^1(3[0-9]|5[0-35-

JAVA时间日期处理类实例_java

本文实例讲述了JAVA时间日期处理类,主要用来遍历两个日期之间的每一天.分享给大家供大家参考.具体如下: /** * * 文 件 名: AccountDate.java * * 创建时间: 2008-11-18 * * Email : **@163.com */ import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.A