我试图从文件加载公共ssh rsa密钥(id_rsa.pub):
X509EncodedKeySpec spec = new X509EncodedKeySpec(readBytes(keyFile));
return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
Run Code Online (Sandbox Code Playgroud)
但我明白了
java.security.spec.InvalidKeySpecException:java.security.InvalidKeyException:无效的密钥格式
如何将此文件加载到RSAPublicKey?
x509编码数据应为DER格式.您可以使用OpenSSL生成此类密钥:(注意,请参阅http://codeartisan.blogspot.com/2009/05/public-key-cryptography-in-java.html以获取OpenSSL复习.)
要生成密钥,请使用:
$ openssl genrsa -out private_key.pem 2048
Run Code Online (Sandbox Code Playgroud)
或者,使用密码:
$ openssl genrsa -aes256 -out private_key.pem 2048
Run Code Online (Sandbox Code Playgroud)
或者,使用ssh-keygen(按照您的示例):
$ ssh-keygen -t rsa -C "myEmail" -I X.509
Run Code Online (Sandbox Code Playgroud)
我假设您将密钥保存为'private_key.pem'生成DER格式的公钥:
$ openssl rsa -in private_key.pem -pubout -outform DER -out tst_public.der
Run Code Online (Sandbox Code Playgroud)
现在,X509EncodedKeySpec将接受包含该文件内容的字节数组.
如果要加载私钥,请使用OpenSSL保存私钥的未加密副本(不要在不安全的环境中执行此操作):
$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt
You can then pass this file as a byte array to `PKCS8EncodedKeySpec`.
Run Code Online (Sandbox Code Playgroud)
您还可以在Java中生成密钥对:
private static int rsabits = 2048; // or higher, if you've got the cpu*time
public static SecureRandom sr = new SecureRandom(); // reseed periodically
public static KeyPair newKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(rsabits, sr);
return generator.generateKeyPair();
}
Run Code Online (Sandbox Code Playgroud)
然后您可以使用KeyPair.getPublic()和KeyPair.getPrivate()访问您的密钥.您可以将它们保存或加载为字节数组,例如:
public static byte[] pubKeyToBytes(PublicKey key){
return key.getEncoded(); // X509 for a public key
}
public static byte[] privKeyToBytes(PrivateKey key){
return key.getEncoded(); // PKCS8 for a private key
}
public static PublicKey bytesToPubKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException{
return KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));
}
public static PrivateKey bytesToPrivKey(byte[] bytes) throws InvalidKeySpecException, NoSuchAlgorithmException{
return KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(bytes));
}
Run Code Online (Sandbox Code Playgroud)