How to fix this java.lang.ClassCastException: [B cannot be cast to java.util.List

Viewed 17166

I'm creating a digital signature software in Java and I wanna the software to verify the message with parameters (string filename, string keyfile). But I've got this exception at line

this.list2 = (List<byte[]>) in.readObject();

java.lang.ClassCastException: [B cannot be cast to java.util.List. How to solve this?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

private boolean verifySignature(byte[] data, byte[] signature, String 
keyFile) throws Exception {
    Signature sig = Signature.getInstance("SHA1withRSA");
    sig.initVerify(getPublic(keyFile));
    sig.update(data);

    return sig.verify(signature);
}

public void VerifyMessage(String filename, String keyFile) throws Exception 
    {
    try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(filename)))
    {

        this.list2 = (List<byte[]>) in.readObject();
    }

    lbl13.setText(verifySignature(list2.get(0), list2.get(1), keyFile) ? "VERIFIED MESSAGE" + 
      "\n----------------\n" + new String(list2.get(0)) : "Could not verify the signature.");
}
2 Answers

You are trying to cast your in.readObject() file to a List

This does not work in Java because the file is written as a byte[] Array data structure, not an Array List. You're going to have to convert the byte[] Array to a list before making it the value for this.list2.

Here is how you can do that:

this.list2 = Arrays.asList((byte[])in.readObject());

Array.asList() will convert your Array of byte primitives to a List (I'm assuming you're using byte primitives and not the Byte class here based on your code). It is not possible to simply cast an Array to a List in Java.

You can write:

this.list2=Arrays.asList((byte[])in.readObject());

This should help

Related