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 android.content.Context; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.KeyFactory; import java.security.KeyPair; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class Main { public static KeyPair loadKeyPair(Context context, String name) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { // Read Public Key. File filePublicKey = new File(context.getFilesDir(), name + "_public.key"); FileInputStream fis = new FileInputStream(filePublicKey); byte[] encodedPublicKey = new byte[(int) filePublicKey.length()]; fis.read(encodedPublicKey); fis.close(); // Read Private Key. File filePrivateKey = new File(context.getFilesDir(), name + "_private.key"); fis = new FileInputStream(filePrivateKey); byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()]; fis.read(encodedPrivateKey); fis.close(); // Generate KeyPair. KeyFactory keyFactory = KeyFactory.getInstance("RSA"); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey); PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); return new KeyPair(publicKey, privateKey); } }