我使用Flexi Provider(用于McEliece算法)生成我的公钥和私钥,然后我将其保存到文件中,现在我需要从文件加载keypair,我可以读取文件并获取公钥字节数组和私钥字节数组,但我不知道如何从中创建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");
}
答案 0 :(得分:1)
请尝试以下代码。另请注意,我不直接使用密钥对生成器和密钥工厂实现。
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);