read Public Key From Key File Format - Android java.security

Android examples for java.security:Key

Description

read Public Key From Key File Format

Demo Code


//package com.java2s;
import android.content.Context;
import android.util.Base64;
import android.util.Log;
import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 readPublicKeyFromPemFormat(Context context,
            int publicKeyId) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException {

        InputStream in = context.getResources()
                .openRawResource(publicKeyId);
        BufferedReader pemReader = new BufferedReader(
                new InputStreamReader(in));

        StringBuffer content = new StringBuffer();
        String line = null;//from   ww  w  .  java 2s. c o  m
        while ((line = pemReader.readLine()) != null) {
            if (line.indexOf("-----BEGIN PUBLIC KEY-----") != -1) {
                while ((line = pemReader.readLine()) != null) {
                    if (line.indexOf("-----END PUBLIC KEY") != -1) {
                        break;
                    }
                    content.append(line.trim());
                }
                break;
            }
        }
        if (line == null) {
            throw new IOException("PUBLIC KEY" + " not found");
        }
        Log.i("PUBLIC KEY: ", "PEM content = : " + content.toString());

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        return keyFactory.generatePublic(new X509EncodedKeySpec(Base64
                .decode(content.toString(), Base64.DEFAULT)));
    }
}

Related Tutorials