Java tutorial
//package com.java2s; /** * Copyright 2015 Handhandlab.com * * This file is part of AgentDroid. * * AgentDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * AgentDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with AgentDroid. If not, see <http://www.gnu.org/licenses/>. * */ import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.security.KeyPair; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class Main { /** * save private key and public key of a keypair in the directory * * @param dir * @param keyPair * @param name keys will be stored as name_private.key and name_public.key * @throws IOException */ public static void saveKeyPair(File dir, KeyPair keyPair, String name) throws IOException { // Store Public Key. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded()); FileOutputStream fos = new FileOutputStream(new File(dir, name + "_public.key")); fos.write(x509EncodedKeySpec.getEncoded()); fos.close(); // Store Private Key. PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded()); fos = new FileOutputStream(new File(dir, name + "_private.key")); fos.write(pkcs8EncodedKeySpec.getEncoded()); fos.close(); } }