簡體   English   中英

對Java中的文件執行簽名和驗證操作時出錯

[英]Error while performing sign and verify operation to a file in Java

我正在使用Java執行簽名和驗證操作並出現以下錯誤

java.security.SignatureException:簽名長度不正確:得到了155,但是期望是128

請在下面找到我的代碼以簽名並驗證

AddSignature

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.file.Files;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JOptionPane;


public class AddSignature {

    //The constructor of Message class builds the list that will be written to the file. The list consists of the message and the signature.
    public AddSignature(String data, String keyFile) throws InvalidKeyException, Exception {
        sign(data, keyFile);
    }

    //The method that signs the data using the private key that is stored in keyFile path
    public void sign(String data, String keyFile) throws InvalidKeyException, Exception{
        Signature dsa = Signature.getInstance("SHA1withRSA"); 
        dsa.initSign(getPrivate(keyFile));
        dsa.update(data.getBytes());
        writeToFile("encrypt//destination//data.txt", data.getBytes());
         byte[] sign = dsa.sign();
        writeToFile("encrypt//destination//signed.txt", sign);
    }

    //Method to retrieve the Private Key from a file
    public PrivateKey getPrivate(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }

    private void writeToFile(String signedFileLocation, byte[] signedData) throws FileNotFoundException, IOException {
        File f = new File(signedFileLocation);
        f.getParentFile().mkdirs();
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(signedFileLocation));
        out.writeObject(signedData);
        out.close();
    }


    public static void main(String[] args) throws InvalidKeyException, IOException, Exception{
        String data = JOptionPane.showInputDialog("Type your message here");
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        new AddSignature(data, "MyKeys/privateKey");
    }}

VerifySignature

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

public class VerifySignature {

    private static boolean verifySignature(byte[] data, byte[] signature, String keyFile) throws Exception {
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(getPublic(keyFile));
        sig.update(data);
        try {
            return sig.verify(signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static byte[] read(String fileName) throws IOException {
        FileInputStream fin = null;
        try {
            File file = new File(fileName);
            fin = new FileInputStream(file);
            byte fileContent[] = new byte[(int) file.length()];
            fin.read(fileContent);
            return fileContent;
        } catch (Exception e) {
            throw e;
        } finally {
            fin.close();
        }
    }

    // Method to retrieve the Public Key from a file
    public static PublicKey getPublic(String filename) throws Exception {
        byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }

    public static void main(String[] args) throws Exception {
        byte[] data = read("encrypt//destination//data.txt");
        byte[] signed = read("encrypt//destination//signed.txt");
        verifySignature(data, signed, "MyKeys/publicKey");
    }
}

我需要對文件簽名並保留在一個位置,並且需要檢索同一文件以驗證簽名

從文件中檢索私鑰時,可能會出錯。 您可以嘗試這樣:

public PrivateKey getPrivate(String filename) throws Exception {
  //byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
    byte[] keyBytes = Base64Utils.decode(readFile(filename));
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(spec);
}
private static String readFile(String filePath) throws Exception {
    File inFile = new File(filePath);
    long fileLen = inFile.length();
    Reader reader = new FileReader(inFile);
    char[] content = new char[(int) fileLen];
    reader.read(content);
    System.out.println("read content:" + new String(content));
    return new String(content);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM