签名HMAC的验证

时间:2018-04-18 03:09:46

标签: java hash signature sha256

我正在尝试创建签名,然后使用SHA-256算法验证40字节的消息。我以为我做的一切都是正确的,但它给了我错误的验证,我无法找出我做错了什么。我检查了两倍,三倍和四倍,但无法找到答案。任何帮助,将不胜感激。 这是我为签名和验证邮件签名而创建的两个函数。

   public static byte[] sigAuth(byte[] message, File file, PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException{
            SecretKeySpec secretKey = new SecretKeySpec(sharedKey, "hmacSHA256");
            Mac macHMAC = Mac.getInstance("HmacSHA256");
            macHMAC.init(secretKey);
            byte[] authMessageInHMACC = macHMAC.doFinal(message);

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(privateKey);
            signature.update(authMessageInHMACC);
            byte[] finalSignature = signature.sign();

            FileOutputStream fos = new FileOutputStream(file);
            fos.write(message);
            fos.write(finalSignature);
            fos.close(); 

            return finalSignature;
        }

        public static boolean verify(File file, PublicKey pubKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException{
            byte fileContent[] = new byte[(int)sharedKeyFile.length()];
            FileInputStream fos = new FileInputStream(file);
            fos.read(fileContent);
            fos.close();
            /Split message from signed hash 
            byte[] messageOnly = new byte[40];

            byte[] hash = new byte[256];

            //messageauthmessage
            int j = 0;
            int k = 0;
            for (int i = 0; i < fileContent.length;i++){
                if(i < 40){
                    messageOnly[i] = fileContent[i];
                    j++;
                } else {
                    hash[k] = fileContent[j+1];
                    k++;
                }
            }

            SecretKeySpec secretKey = new SecretKeySpec(sharedKey, "hmacSHA256");
            Mac macHMAC = Mac.getInstance("HmacSHA256");
            macHMAC.init(secretKey);
            byte[] authMessageInHMACC = macHMAC.doFinal(messageOnly);

            Signature pubSignature = Signature.getInstance("SHA256withRSA");
            pubSignature.initVerify(pubKey);
            pubSignature.update(authMessageInHMACC);
            boolean verified = pubSignature.verify(hash);
            return verified;
        }

1 个答案:

答案 0 :(得分:0)

init(named:)

应该是

 messageOnly[i] = fileContent[i];

 messageOnly[j] = fileContent[i];

应该是

hash[k] = fileContent[j+1];