使用HMAC和SHA-1

时间:2015-03-04 02:29:16

标签: java bouncycastle sha1 hmac hmacsha1

我正在尝试使用SHA-1作为基础来实现HMAC。使用来自弹力城堡的SHA-1算法,并实现HMAC计算。还要使用SHA-1来哈希输入密码以获取HMAC算法的密钥。我一直试图这样做几个小时,但我对HMAC的了解很少。如果有人有任何关于如何做到这一点的提示,将不胜感激。我的代码是我的SHA1实现,通过库函数调用,我基本上只是想用HMAC实现它。

public class HMACSHA1 {
static byte[] password;
static byte[] fileName = null;
static byte[] input = new byte[16];
static String File;
public static void main(String[] args) {
    Security.addProvider(Security.getProvider("BC")); 
    if(args.length != 2){
        System.out.println("Invalid input");
        System.exit(-1);
    }
    File = args[1];
    try {
        password = args[0].getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("Unable to read password");
        System.exit(-1);
    }
    InputStream inputstream = null;
    try {
             inputstream = new FileInputStream(File);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
        System.out.println("No input found\n");
        System.exit(-1);
    }

    MessageDigest hash = null;
    MessageDigest key = null;
    try {
        hash = MessageDigest.getInstance("SHA-1", "BC");
        key = MessageDigest.getInstance("SHA-1", "BC");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    key.update(password);
    byte[] HMACKey = key.digest();
    byte[] digest = null;
    int reader = 0;
    while (reader != -1){
        try {
            reader = inputstream.read(input);
        } catch (IOException e2) {
            e2.printStackTrace();
        }
        hash.update(input);
        digest = hash.digest();
        System.out.println(new String(Hex.encode(digest)));
    }

}
}

1 个答案:

答案 0 :(得分:0)

我不熟悉Bouncy Castle,但你可以只使用Java SE提供的内容编写没有外部库的HMAC-SHA1:

import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public String getHmacSha1(byte[] key, byte[] input) throws NoSuchAlgorithmException {
    SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");

    Mac mac = null;
    mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);
    byte[] digest = mac.doFinal(input);

    return Hex.encodeHexString(digest);
}

自Java 1.4起根据API

可用