Here you can find the source of convertToPEM(PublicKey key)
static public String convertToPEM(PublicKey key)
//package com.java2s; /*// w w w. j a v a 2s. c o m * Copyright 2014-2017. * Distributed under the terms of the GPLv3 License. * * Authors: * Clemens Zeidler <czei002@aucklanduni.ac.nz> */ import javax.xml.bind.DatatypeConverter; import java.security.*; import java.util.ArrayList; import java.util.List; public class Main { static private String convertToPEM(String type, Key key) { String pemKey = "-----BEGIN " + type + "-----\n"; List<String> parts = splitIntoEqualParts(DatatypeConverter.printBase64Binary(key.getEncoded()), 64); for (String part : parts) pemKey += part + "\n"; pemKey += "-----END " + type + "-----"; return pemKey; } static public String convertToPEM(PublicKey key) { String algo = key.getAlgorithm(); return convertToPEM(algo + " PUBLIC KEY", key); } static public String convertToPEM(PrivateKey key) { String algo = key.getAlgorithm(); return convertToPEM(algo + " PRIVATE KEY", key); } private static List<String> splitIntoEqualParts(String string, int partitionSize) { List<String> parts = new ArrayList<>(); int length = string.length(); for (int i = 0; i < length; i += partitionSize) parts.add(string.substring(i, Math.min(length, i + partitionSize))); return parts; } }