get RSA Private Key from Asset - Android java.security

Android examples for java.security:RSA

Description

get RSA Private Key from Asset

Demo Code


//package com.java2s;
import android.content.Context;

import java.io.IOException;
import java.io.InputStream;

import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;

public class Main {
    public static PrivateKey getPrivateKey(Context ctx) {
        try {//from   w w w.j a  va 2s  . c  o m
            InputStream is = ctx.getAssets().open("private_key.der");
            byte[] fileBytes = new byte[is.available()];
            is.read(fileBytes);
            is.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(fileBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(spec);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials