出于安全目的,我正在使用以下代码创建公钥和私钥。
public KeyGenerator(int keylength) throws NoSuchAlgorithmException, NoSuchProviderException {
this.keyGen = KeyPairGenerator.getInstance("RSA");
this.keyGen.initialize(keylength);
}
public void createKeys() {
this.pair = this.keyGen.generateKeyPair();
this.privateKey = pair.getPrivate();
this.publicKey = pair.getPublic();
}
public PrivateKey getPrivateKey() {
return this.privateKey;
}
public PublicKey getPublicKey() {
return this.publicKey;
}
public void writeToFile(String path, byte[] key) throws IOException {
File f = new File(path);
f.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(f);
fos.write(key);
fos.flush();
fos.close();
}
public static void main(String[] args) {
KeyGenerator kg;
try {
kg = new KeyGenerator(2048);
kg.createKeys();
System.out.println(kg.getPublicKey().getFormat()); // this prints out X.509
System.out.println(kg.getPrivateKey().getFormat()); // this prints out PKCS#8
kg.writeToFile(PUBLIC_KEY_PATH, kg.getPublicKey().getEncoded());
kg.writeToFile(PRIVATE_KEY_PATH, kg.getPrivateKey().getEncoded());
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
我需要找到一种方法将私钥(如下图所示)按以下格式存储在保管库中。当我用文本编辑器打开密钥时,我得到如下内容。
有没有办法将此 PKCS#8 转换为适合存储在文件中的编码?
30秒到达战场
千巷猫影
相关分类