【发布时间】:2015-11-14 00:39:12
【问题描述】:
我有一个包含公共 RSA 密钥的文件(使用 ssh-keygen 生成)。我想读取文件并生成一个PublicKey 对象。
在此之前我转换了文件,因为读取原始文件似乎是不可能的:
# http://unix.stackexchange.com/questions/220354/how-to-convert-public-key-from-pem-to-der-format/220356#220356
ssh-keygen -f ~/.ssh/id_rsa.pub -e -m PEM > ~/.ssh/id_rsa.pub.pem
openssl rsa -RSAPublicKey_in -in ~/.ssh/id_rsa.pub.pem -inform PEM -outform DER -out ~/.ssh/id_rsa.pub.der -RSAPublicKey_out
从Java - Encrypt String with existing public key file我定义了函数readFileBytes:
public static byte[] readFileBytes(String filename) throws IOException {
Path path = Paths.get(System.getProperty("user.home") + filename);
return Files.readAllBytes(path);
}
现在我想读取文件并生成 PublicKey 对象,但我找不到这样做的方法; java.security.spec.RSAPublicKeySpec 没有提供合适的构造函数,java.security.spec.X509EncodedKeySpec 抛出错误 java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence:
//RSAPublicKeySpec publicSpec = new RSAPublicKeySpec(readFileBytes("/.ssh/id_rsa.pub.der"));
// No fitting construktor
X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(readFileBytes("/.ssh/id_rsa.pub.der"));
// Gives: "algid parse error, not a sequence"
【问题讨论】:
标签: java encryption rsa bouncycastle public-key-encryption