我需要使用java以PEM格式生成RSA和DSA密钥对(公钥和私钥)。 我希望以这种格式打开公钥和私钥文件:
-----开始公共关键----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO 3Hy8PEUcuyvg / IKC + VcIo2SFFSf18a3IMYldIugqqqZCs4 / 4uVW3sbdLs / 6PfgdX 7O9D22ZiFWHPYA2k2N744MNiCD1UE + tJyllUhSblK48bn + v1oZHCM0nYQ2NqUkvS J + hwUU3RiWl7x3D2s9wSdNt7XUtW05a / FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd OrUZ / wK69Dzu4IvrN4vs9Nes8vbwPa / ddZEzGR0cQMt0JBkhk9kU / qwqUseP1QRJ 5I1jR4g8aYPL / ke9K35PxZWuDp3U0UPAZ3PjFAh + 5T + fc7gzCs9dPzSHloruU + GL FQIDAQAB ----- END PUBLIC KEY -----
我的公钥之前已经生成了我不想要的格式:
0Ÿ0*†H†÷0Ÿ0*†H†÷
好的,这是我的密钥生成代码:
private static void createKey()
throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Password to encrypt the private key: ");
String password = in.readLine();
System.out.println("Generating an RSA keypair...");
// Create an RSA key
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.genKeyPair();
System.out.println("Done generating the keypair.\n");
// Now we need to write the public key out to a file
System.out.print("Public key filename: ");
String publicKeyFilename = "C:/Users/Joe/Desktop/" + in.readLine();
// Get the encoded form of the public key so we can
// use it again in the future. This is X.509 by default.
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
// Write the encoded public key out to the filesystem
FileOutputStream fos = new FileOutputStream(publicKeyFilename);
fos.write(publicKeyBytes);
fos.close();
// Now we need to do the same thing with the private key,
// but we need to password encrypt it as well.
System.out.print("Private key filename: ");
String privateKeyFilename = "C:/Users/Joe/Desktop/" + in.readLine();
// Get the encoded form. This is PKCS#8 by default.
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
// Here we actually encrypt the private key
byte[] encryptedPrivateKeyBytes =
passwordEncrypt(password.toCharArray(),privateKeyBytes);
fos = new FileOutputStream(privateKeyFilename);
fos.write(encryptedPrivateKeyBytes);
fos.close();
}
谢谢你的帮助..
答案 0 :(得分:0)
也许有点迟,但有我的解决方案。希望它能帮助别人。
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
这里你需要占用密钥字节并直接写入文件。所以你得到了合适的结果 - DER编码的文件。但是,PEM是Base64编码格式,每个符号和页眉/页脚都有换行符。
有实现此逻辑的代码:
String publicKeyContent = Base64.encode(publicKeyBytes);
String publicKeyFormatted = "-----BEGIN PUBLIC KEY-----" + System.lineSeparator();
for (final String row:
Splitter
.fixedLength(64)
.split(publicKeyContent)
)
{
publicKeyFormatted += row + System.lineSeparator();
}
publicKeyFormatted += "-----END PUBLIC KEY-----";
因此publicKeyFormatted将包含PEM编码的公钥字符串。
P.S。 Splitter是Guava lib中提供的类,但您可以通过简单的循环或以某种方式拆分字符串。