Java 将HMAC与SHA-1一起使用

Java 将HMAC与SHA-1一起使用,java,bouncycastle,sha1,hmac,hmacsha1,Java,Bouncycastle,Sha1,Hmac,Hmacsha1,我正在尝试使用SHA-1作为基础来实现HMAC。使用bouncy castle的SHA-1算法,实现HMAC计算。还可以使用SHA-1散列输入密码以获取HMAC算法的密钥。我已经试着做了几个小时了,但我对HMAC的理解真的很差。如果有人对如何做到这一点有任何建议,将不胜感激。下面的代码是我对SHA1的实现,通过一个库函数调用,我实际上只是想用HMAC实现它 public class HMACSHA1 { static byte[] password; static byte[] fileName

我正在尝试使用SHA-1作为基础来实现HMAC。使用bouncy castle的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)));
    }

}
}

我对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开始提供的。

如有任何建议,我们将不胜感激。