javaserializationbouncycastlepost-quantum-cryptography

How do I serialize a BCMcEliecePublicKey?


I want to serialize a McEliece public key (BCMcEliecePublicKey) but always get a NotSerializableException.

 java.io.NotSerializableException: org.bouncycastle.pqc.crypto.mceliece.McEliecePublicKeyParameters

I tried the same code with XMSSMT and it worked without a problem. The Bouncy Castle version is the new Release 1.61

Here a small code as an example:

    //key generation
    Security.addProvider(new BouncyCastlePQCProvider());
    KeyPairGenerator keygen = null;
    try {
        keygen = KeyPairGenerator.getInstance("McEliece", "BCPQC"); //XMSSMT
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        System.out.println("Error: KeyPairGenerator could not be instanciated. " + e.getMessage());
    }

    //XMSSMTParameterSpec bcSpec = new XMSSMTParameterSpec(10, 5, XMSSMTParameterSpec.SHA256);
    McElieceKeyGenParameterSpec bcSpec = new McElieceKeyGenParameterSpec();

    try {
        keygen.initialize(bcSpec, new SecureRandom());
    } catch (InvalidAlgorithmParameterException e) {
        System.out.println("Error: Initialize failed. " + e.getMessage());
    }

    PublicKey pub = keygen.generateKeyPair().getPublic();

    //BCMcEliecePublicKey pubMcEliece = (BCMcEliecePublicKey) pub;
    //McEliecePublicKeyParameters keyParameters = new McEliecePublicKeyParameters(pubMcEliece.getN(), pubMcEliece.getT(), pubMcEliece.getG());

    //serialization
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(pub); //keyParameters
        System.out.println("OK");
    } catch (IOException e) {
        System.out.println(e);
    }

What do I have to change to serialize the key?


Solution

  • Simple answer: you probably can't.

    That exception tells you that the class of the corresponding does not implement java.io.Serializable.

    And when you dig into the source code, you will find: yes, exactly. Neither that class, nor any of its parent classes does implement that interface.

    Like here, the base class: McElieceParameters (and no, that interface CypherParameters doesn't implement Serializable either).

    Guessing here: the bouncy castle do not want you to use the default serialization for such objects!

    And then: please understand that "old school" java binary object serialization is something that few people would recommend using these days anyway. Nowadays, you rather look towards compiling your configuration data into some "bean" like structures, to write/read them as JSON text.

    Finally, if you really want to, there are dirty hacks, see here for example. But again: I would advise to not spend your time with that. There are much better ways to persist your data these days, compared to java style object serialization!