Ошибка при выполнении операции подписи и проверки файла в Java - PullRequest
0 голосов
/ 15 октября 2018

Я использую 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");
    }
}

Мне нужно подписать файл исохраняются в одном месте, и для получения подписи необходимо получить тот же файл

1 Ответ

0 голосов
/ 15 октября 2018

Что-то не так при извлечении закрытого ключа из файла.Вы можете попробовать вот так:

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...