【问题标题】:Verificiation of a Signature HMAC签名 HMAC 的验证
【发布时间】:2018-04-18 03:09:45
【问题描述】:

我正在尝试创建一个签名,然后使用 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;
        }

【问题讨论】:

    标签: java hash signature sha256


    【解决方案1】:
     messageOnly[i] = fileContent[i];
    

    应该是

     messageOnly[j] = fileContent[i];
    

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

    应该是

    hash[k] = fileContent[i];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-12
      • 2015-01-04
      • 2018-12-23
      • 2019-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-04
      相关资源
      最近更新 更多