Java Key Public getPublic(byte[] keyBytes)

Here you can find the source of getPublic(byte[] keyBytes)

Description

Gets the public key from bytes.

License

Apache License

Parameter

Parameter Description
keyBytes the key bytes

Exception

Parameter Description
InvalidKeyException invalid key exception

Return

the public

Declaration

public static PublicKey getPublic(byte[] keyBytes) throws InvalidKeyException 

Method Source Code

//package com.java2s;
/**/*from  www .  j  a  v a2 s  .c  o m*/
 *  Copyright 2014-2016 CyberVision, Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.security.InvalidKeyException;
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 {
    /**
     * Gets the public key from input stream.
     *
     * @param input the input stream
     * @return the public
     * @throws IOException                       the i/o exception
     * @throws java.security.InvalidKeyException invalid key exception
     */
    public static PublicKey getPublic(InputStream input) throws IOException, InvalidKeyException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        byte[] keyBytes = output.toByteArray();

        return getPublic(keyBytes);
    }

    /**
     * Gets the public key from bytes.
     *
     * @param keyBytes the key bytes
     * @return the public
     * @throws InvalidKeyException invalid key exception
     */
    public static PublicKey getPublic(byte[] keyBytes) throws InvalidKeyException {
        try {
            X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePublic(spec);
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new InvalidKeyException(e);
        }
    }
}

Related

  1. getPublic(byte[] encodedKey)
  2. getPublicBytes(KeyPair keyPair)
  3. getPublicDeclaredMethods(Class clz)
  4. getPublicDeclaredMethods(Class clz)
  5. getPublicEncoded(KeyPair kp)