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.nio.file.Files;
import java.io.File;
import java.security.KeyFactory;

import java.security.PublicKey;

import java.security.spec.EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

public class Main {
    public static PublicKey getPublicKey(String filename) {

        try {// w w  w.  j  a  v a 2s .c  om
            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;
    }

    public static PublicKey getPublicKey(File file) {

        try {
            byte[] keyBytes = Files.readAllBytes(file.toPath());

            EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePublic(spec);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

Related

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