Java Key Public getPublicEncoded(KeyPair kp)

Here you can find the source of getPublicEncoded(KeyPair kp)

Description

get Public Encoded

License

Apache License

Declaration

public static String getPublicEncoded(KeyPair kp) 

Method Source Code

//package com.java2s;
/*//from   w ww  . j  a  v  a  2s.  c o  m
 * $URL$
 * $Id$
 *
 * Copyright (c) 2013- Charles R. Severance
 *
 * 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.util.Base64;
import java.security.*;

public class Main {
    public static String getPublicEncoded(KeyPair kp) {
        return getPublicEncoded(kp.getPublic());
    }

    public static String getPublicEncoded(Key key) {
        byte[] encodeArray = key.getEncoded();
        Base64.Encoder encoder = Base64.getEncoder();

        String publicRSA = "-----BEGIN PUBLIC KEY-----\n"
                + breakKeyIntoLines(encoder.encodeToString(encodeArray))
                + "\n-----END PUBLIC KEY-----\n";
        return publicRSA;
    }

    public static String breakKeyIntoLines(String rawkey) {
        int len = 65;
        StringBuffer ret = new StringBuffer();

        String trimmed = rawkey.trim();
        for (int i = 0; i < trimmed.length(); i += len) {
            int end = i + len;
            if (ret.length() > 0)
                ret.append("\n");
            if (end > trimmed.length())
                end = trimmed.length();
            ret.append(trimmed.substring(i, end));
        }
        return ret.toString();
    }
}

Related

  1. getPublic(byte[] encodedKey)
  2. getPublic(byte[] keyBytes)
  3. getPublicBytes(KeyPair keyPair)
  4. getPublicDeclaredMethods(Class clz)
  5. getPublicDeclaredMethods(Class clz)
  6. getPublicExponent(PublicKey pubk)
  7. getPublicKey()
  8. getPublicKey(BigInteger modulus, BigInteger exponent)
  9. getPublicKey(byte[] der)