我有一个从这个函数生成的公钥/私钥对:
public static void generateKey() {
try {
final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(2048);
final KeyPair key = keyGen.generateKeyPair();
File privateKeyFile = new File(PRIVATE_KEY_FILE);
File publicKeyFile = new File(PUBLIC_KEY_FILE);
// Create files to store public and private key
if (privateKeyFile.getParentFile() != null) {
privateKeyFile.getParentFile().mkdirs();
}
privateKeyFile.createNewFile();
if (publicKeyFile.getParentFile() != null) {
publicKeyFile.getParentFile().mkdirs();
}
publicKeyFile.createNewFile();
// Saving the Public key in a file
ObjectOutputStream publicKeyOS = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
publicKeyOS.writeObject(key.getPublic());
publicKeyOS.close();
// Saving the Private key in a file
ObjectOutputStream privateKeyOS = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
privateKeyOS.writeObject(key.getPrivate());
privateKeyOS.close();
} catch (Exception e) {
e.printStackTrace();
}
}
现在我想在编写时将公钥转换为base64
并使用 base64 解码来取回公钥,该怎么做?
如果要以 base 64 存储文件,只需对字节数组进行编码即可。您甚至可以在ObjectOutputStream
和FileOutputStream
之间放置一个 Base64 流(Java 8 中的 Base64 类提供了有用的信息)。
但是,公钥和私钥具有默认编码,可以使用其getEncoded
方法进行访问:
PublicKey publicKey = key.getPublic();
byte[] encodedPublicKey = publicKey.getEncoded();
String b64PublicKey = Base64.getEncoder().encodeToString(encodedPublicKey);
try (OutputStreamWriter publicKeyWriter =
new OutputStreamWriter(
new FileOutputStream(publicKeyFile),
StandardCharsets.US_ASCII.newEncoder())) {
publicKeyWriter.write(b64PublicKey);
}
这将公钥保存为SubjectPublicKeyInfo
格式,该格式可由多种类型的软件和加密库读取和写入。
例如,您可以将其粘贴到在线 ASN.1 解码器中(在线解码器本身会将其转换为十六进制,但它也会解析 base 64)。字节的格式是所谓的ASN.1/DER(这是一种通用格式,就像您可以在XML中编码多种类型的文件一样)。
<小时 />如果你想让密钥采用OpenSSL兼容格式(带有"PUBLIC KEY"页眉和页脚),你可以使用像Bouncy Castle这样的库(例如 org.bouncycastle.openssl.jcajce.JcaPEMWriter
)。