Java Key Public getPublicKey(KeyPair keyPair)

Here you can find the source of getPublicKey(KeyPair keyPair)

Description

get Public Key

License

Apache License

Declaration

public static PublicKey getPublicKey(KeyPair keyPair) 

Method Source Code


//package com.java2s;
/*/*from   ww  w .j a  v a  2s . c  o m*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.IOException;

import java.security.KeyFactory;
import java.security.KeyPair;

import java.security.NoSuchAlgorithmException;

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

import java.security.spec.X509EncodedKeySpec;

import sun.misc.BASE64Decoder;

public class Main {

    public static PublicKey getPublicKey(KeyPair keyPair) {
        if (keyPair == null) {
            return null;
        }
        return keyPair.getPublic();
    }

    public static PublicKey getPublicKey(String key) {
        byte[] keyBytes = null;
        try {
            keyBytes = (new BASE64Decoder()).decodeBuffer(key);
        } catch (IOException e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = null;
        try {
            keyFactory = KeyFactory.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            throw new InternalError(e.getMessage());
        }
        PublicKey publicKey = null;
        try {
            publicKey = keyFactory.generatePublic(keySpec);
        } catch (InvalidKeySpecException e) {
            throw new IllegalArgumentException(e.getMessage(), e);
        }
        return publicKey;
    }
}

Related

  1. getPublicKey(byte[] der)
  2. getPublicKey(byte[] keyBytes, String algorithm)
  3. getPublicKey(final byte[] keyData)
  4. getPublicKey(final byte[] modulus, final byte[] exponent)
  5. getPublicKey(final String algorithm, final File publicKeyFile)
  6. getPublicKey(KeyPair keyPair)
  7. getPublicKey(KeyPair kp)
  8. getPublicKey(KeyStore keyStore, String alias)
  9. getPublicKey(KeyStore keyStore, String alias)