Here you can find the source of getPublicKey(String publicKeyFilepath, String algorithm)
Parameter | Description |
---|---|
publicKeyFilepath | location of public key file |
algorithm | algorithm of specified key file |
Parameter | Description |
---|---|
IOException | an exception |
NoSuchAlgorithmException | an exception |
InvalidKeySpecException | an exception |
public static PublicKey getPublicKey(String publicKeyFilepath, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException
//package com.java2s; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; 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 { /**//from w ww . jav a 2 s .c o m * Creates a PublicKey from the specified public key file and algorithm. * Returns null if failure to generate PublicKey. * * @param publicKeyFilepath location of public key file * @param algorithm algorithm of specified key file * @return PublicKey object representing contents of specified public key * file, null if error in generating key or invalid file specified * @throws IOException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ public static PublicKey getPublicKey(String publicKeyFilepath, String algorithm) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { InputStream pubKey = null; try { URL url = new URL(publicKeyFilepath); pubKey = url.openStream(); } catch (MalformedURLException e) { pubKey = new FileInputStream(publicKeyFilepath); } byte[] bytes = new byte[pubKey.available()]; pubKey.read(bytes); pubKey.close(); X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(bytes); KeyFactory factory = KeyFactory.getInstance(algorithm); return factory.generatePublic(pubSpec); } }