Java Utililty Methods Key Public

List of utility methods to do Key Public

Description

The list of methods to do Key Public are organized into topic(s).

Method

PublicKeygetPublicKey(KeyStore ks, String alias, char[] password)
Get the Public Key from the keystore
PublicKey publicKey = null;
Key key = ks.getKey(alias, password);
if (key instanceof PrivateKey) {
    Certificate cert = ks.getCertificate(alias);
    publicKey = cert.getPublicKey();
if (publicKey == null) {
    Certificate cert = ks.getCertificate(alias);
...
PublicKeygetPublicKey(String algo)
get Public Key
if (algo.equalsIgnoreCase("DSA")) {
    return getPublicKey("DSA", 1024);
} else if (algo.equalsIgnoreCase("RSA")) {
    return getPublicKey("RSA", 512);
} else {
    throw new RuntimeException("Unsupported key algorithm " + algo);
PublicKeygetPublicKey(String alias)
get Public Key
return ks.getCertificate(alias).getPublicKey();
PublicKeygetPublicKey(String certificatePath)
get Public Key
Certificate certificate = getCertificate(certificatePath);
PublicKey key = certificate.getPublicKey();
return key;
PublicKeygetPublicKey(String certPath)
get Public Key
Certificate cert = getCert(certPath);
return cert.getPublicKey();
PublicKeygetPublicKey(String filename)
get Public Key
byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance(KEY_TYPE_RSA);
return kf.generatePublic(spec);
PublicKeygetPublicKey(String filename)
get Public Key
try {
    final byte[] keyBytes = Files.readAllBytes(Paths.get(filename));
    final X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    return factory().generatePublic(spec);
} catch (IOException ex) {
    throw new RuntimeException("Error loading public key '" + filename + "'.", ex);
} catch (final InvalidKeySpecException ex) {
    throw new RuntimeException("Error reading public key '" + filename + "'.", ex);
...
PublicKeygetPublicKey(String filename)
get Public Key
try {
    byte[] keyBytes = Files.readAllBytes(new File(filename).toPath());
    EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePublic(spec);
} catch (Exception e) {
    e.printStackTrace();
return null;
PublicKeygetPublicKey(String key)
get Public Key
byte[] keyBytes;
keyBytes = (new BASE64Decoder()).decodeBuffer(key);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
PublicKeygetPublicKey(String modulus, String exponent)
get Public Key
try {
    BigInteger b1 = new BigInteger(modulus);
    BigInteger b2 = new BigInteger(exponent);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC");
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
    return keyFactory.generatePublic(keySpec);
} catch (Exception e) {
    throw new RuntimeException("getPublicKey error", e);
...