get RSA Public Key from Asset - Android java.security

Android examples for java.security:RSA

Description

get RSA Public 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.PublicKey;
import java.security.spec.InvalidKeySpecException;

import java.security.spec.X509EncodedKeySpec;

public class Main {
    public static PublicKey getPublicKey(Context ctx) {
        try {//from  w ww.ja  v a2  s  .  c  o m
            InputStream is = ctx.getAssets().open("public_key.der");
            byte[] fileBytes = new byte[is.available()];
            is.read(fileBytes);
            is.close();
            X509EncodedKeySpec spec = new X509EncodedKeySpec(fileBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePublic(spec);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related Tutorials