read Public Key Form Certificate - Android java.security

Android examples for java.security:Certificate

Description

read Public Key Form Certificate

Demo Code


import android.content.Context;
import android.util.Base64;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
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.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;

public class Main{
    private static final String TAG = RSAUtils.class.getSimpleName();
    public static PublicKey readPublicKeyFormCertificate(Context context,
            int certificateResourceId) throws IOException,
            CertificateException {
        InputStream in = context.getResources().openRawResource(
                certificateResourceId);//from  ww w  .j  a v a 2s. co  m
        byte[] buff = new byte[4000];
        int bytesRead;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((bytesRead = in.read(buff)) != -1) {
            out.write(buff, 0, bytesRead);
            Log.i(TAG, "bytes read: " + bytesRead);
        }

        byte[] publicKeyBytes = out.toByteArray();

        CertificateFactory cf = CertificateFactory.getInstance("X509");
        Certificate cert = cf.generateCertificate(new ByteArrayInputStream(
                publicKeyBytes));

        PublicKey pubKey = cert.getPublicKey();
        Log.i(TAG, "Public Key Info: ");
        Log.i(TAG, "Algorithm = " + pubKey.getAlgorithm());
        Log.i(TAG, "toString = " + pubKey.toString());
        return pubKey;
    }
}

Related Tutorials