I want to convert my ssh public key in *.pub file to a PublicKey(java.security.PublicKey).
The reason is that I need to inspect the algorithm of the ssh public key, is there any way to do that?
since I’ve got the below error.
java.lang.IllegalArgumentException: failed to construct sequence from byte[]: unexpected end-of-contents marker
at org.bouncycastle.asn1.ASN1Sequence.getInstance(Unknown Source)
at org.bouncycastle.asn1.x509.SubjectPublicKeyInfo.getInstance(Unknown Source)
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
public static PublicKey loadPublicKey(String encoded)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
byte[] publicBytes = Base64.getDecoder().decode(encoded);
SubjectPublicKeyInfo instance = SubjectPublicKeyInfo.getInstance(publicBytes); <- I've got an error here
instance
.getAlgorithm()
.getAlgorithm()
.toString();
PublicKey publicKey = new JcaPEMKeyConverter().getPublicKey(
SubjectPublicKeyInfo.getInstance(publicBytes));
return KeyFactory.getInstance(
publicKey.getAlgorithm(), new org.bouncycastle.jce.provider.BouncyCastleProvider())
.generatePublic(new X509EncodedKeySpec(publicBytes));
}
below is my build.gradle
implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1'
implementation 'org.bouncycastle:bcpkix-jdk18on:1.78.1'