我使用Flexi Provider(用于McEliece算法)生成我的公钥和私钥,然后将其保存到文件中,现在我需要从文件加载密钥对,我可以读取文件并获取公钥字节数组和私钥字节数组,但是我不知道如何从中创建KeyPair:
我将flexiprovider.de用于McEliece算法:

对于生成McEliece密钥:

import de.flexiprovider.api.keys.KeySpec;
import de.flexiprovider.core.FlexiCoreProvider;
import de.flexiprovider.pqc.FlexiPQCProvider;
import de.flexiprovider.pqc.ecc.mceliece.McElieceKeyFactory;
import de.flexiprovider.pqc.ecc.mceliece.McElieceKeyPairGenerator;

public KeyPair generateKeyPair(){
    KeyPair kp = null;
    int KeySize = 256;
    Security.addProvider(new FlexiCoreProvider());
    Security.addProvider(new FlexiPQCProvider());

    try
    {

        McElieceKeyPairGenerator mcElieceKeyPairGenerator = new McElieceKeyPairGenerator();
        mcElieceKeyPairGenerator.initialize(KeySize, new SecureRandom());
        kp = mcElieceKeyPairGenerator.generateKeyPair();
    } catch (Exception e) {
        System.out.println(e.ToString());
    }
    return kp;
}


对于从字节数组加载KeyPair:

public KeyPair readKeyPair(byte[] privateKey, byte[] publicKey){
       //?? How can i create KeyPair
}


我尝试使用McElieceKeyFactory,但我不知道如何使用它,它需要KeySpec(de.flexiprovider.api.keys.KeySpec)来生成私钥和公钥,但是de.flexiprovider.api.keys.KeySpec是抽象类,我无法从中创建新实例。所以我该怎么做?

编辑1:
保存方法:

public void writeFile(byte[] data, String fileName) throws IOException{
    FileOutputStream out = new FileOutputStream(fileName);
    out.write(data);
    out.close();
}

public void saveKeyPair(KeyPair keyPair){
    byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
    byte[] publicKeyBytes = keyPair.getPublic().getEncoded();

    writeFile(privateKeyBytes,"Private.key");
    writeFile(publicKeyBytes,"Public.key");
}

最佳答案

请尝试以下代码。还要注意,我没有直接使用密钥对生成器和密钥工厂实现。

KeyPairGenerator mcElieceKeyPairGenerator = KeyPairGenerator.getInstance("McEliece");
mcElieceKeyPairGenerator.initialize(keysize, new SecureRandom());
kp = mcElieceKeyPairGenerator.generateKeyPair();

final byte[] publicKeyData = kp.getPublic().getEncoded();
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyData);
KeyFactory mcElieceKeyFactory = KeyFactory.getInstance("McEliece");
PublicKey regeneratedPublicKey = mcElieceKeyFactory.generatePublic(publicKeySpec);

final byte[] privateKeyData = kp.getPrivate().getEncoded();
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyData);
PrivateKey regeneratedPrivateKey = mcElieceKeyFactory.generatePrivate(privateKeySpec);

09-30 21:36