我正在开发一个项目,我需要我的应用程序生成SSH登录的公共/私有RSA密钥.
到目前为止,我有以下代码来获取密钥:
private void createKeyTest()
{
try
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair keyPair = kpg.genKeyPair();
byte[] pri = keyPair.getPrivate().getEncoded();
byte[] pub = keyPair.getPublic().getEncoded();
String privateKey = new String(pri);
String publicKey = new String(pub);
Log.d("SSHKeyManager", "Private Key: " + privateKey);
Log.d("SSHLeyManager", "Public Key: " + publicKey);
}
catch (NoSuchAlgorithmException ex)
{
Log.e("SSHKeyManager", ex.toString());
}
当我在Logcat中打印出来时,我会得到随机的非文本字符,当我期待键看起来像:
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAm8QDThbuEjAbQxbsdDltL2xdFkQOep3L0wseSJAxmDuvH6yB
9I2fEEmF+dcVoNo2DGCDZMw7EgdFsfQZNF+PzKdZwtvSUTDW/TmMHWux2wYimNU3
jhQ3kfxGmiLgMJHQHWLkESwd06rCr7s1yOnPObdPjTybt7Odbp9bu+E59U10Ri3W
JFxIhi9uYQvpRn4LT/VIfH/KBdglpbD9xBAneVbKFXW7....
-----END RSA PRIVATE KEY-----
最佳答案
import android.util.Base64;
你可以改变
String privateKey = Base64.encodeToString(pri, Base64.DEFAULT);
String publicKey = Base64.encodeToString(pub, Base64.DEFAULT);
这将让你拥有Base64版本的公钥和私钥.
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
这些格式称为PEM,您可以自定义添加它或使用库“bouncycastle”.
这是bouncycastle的例子:Export RSA public key to PEM String using java