load RSA Public Key from String - Android java.security

Android examples for java.security:RSA

Description

load RSA Public Key from String

Demo Code


//package com.java2s;
import android.util.Base64;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;

import java.security.PublicKey;

import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;

import java.security.spec.X509EncodedKeySpec;

public class Main {
    private static String RSA = "RSA";

    public static PublicKey loadPublicKey(String publicKeyStr)
            throws Exception {
        try {// w w w  . j a  v  a2  s.co m
            byte[] buffer = Base64.decode(publicKeyStr, Base64.DEFAULT);
            KeyFactory keyFactory = KeyFactory.getInstance(RSA);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("");
        } catch (InvalidKeySpecException e) {
            throw new Exception("");
        } catch (NullPointerException e) {
            throw new Exception("");
        }
    }
}

Related Tutorials