Java Key Public getPublicKey(String filename)

Here you can find the source of getPublicKey(String filename)

Description

get Public Key

License

Apache License

Declaration

public static PublicKey getPublicKey(String filename) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;

import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;

import java.security.spec.X509EncodedKeySpec;

public class Main {
    public static PublicKey getPublicKey(String filename) {
        try {/*from   w ww.  ja  va 2  s . com*/
            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);
        }
    }

    private static KeyFactory factory() {
        try {
            return KeyFactory.getInstance("RSA");
        } catch (final NoSuchAlgorithmException ex) {
            throw new RuntimeException("Could not find the RSA algorithm.", ex);
        }
    }
}

Related

  1. getPublicKey(String algo)
  2. getPublicKey(String alias)
  3. getPublicKey(String certificatePath)
  4. getPublicKey(String certPath)
  5. getPublicKey(String filename)
  6. getPublicKey(String filename)
  7. getPublicKey(String key)
  8. getPublicKey(String modulus, String exponent)
  9. getPublicKey(String publicKeyContents)