I am trying to create a signature then verify for a message of 40 bytes using the SHA-256 algorithm. I thought I did everything correctly, but it is giving me false for verification, and I cannot find out what I did wrong. I double and triple and quadruple checked, but couldn't find out. Any help would be appreciated. here are the two functions I have created to sign and verify signature for a message.
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;
}
messageOnly[i] = fileContent[i];
should be
messageOnly[j] = fileContent[i];
and
hash[k] = fileContent[j+1];
should be
hash[k] = fileContent[i];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.